3)libcoap.a library ( do make @lib/libcoap-4.1.1)
4)tinyDTLS library for DTLS enabled applications( enable DTLS = 1 in makefile @connectivity\build/linux)
5)Ethernet, BLE, TimedActions, Timer libraries for arduino support.
-6)scons for scon script compilation.
+6)scons for scons script compilation.
Scope of Release:
1. Supported APIs ( please check below APIs)
How to Build for Linux/DTLS:
-sudo ./sample.sh WITH_DTLS @@connectivity\samples\linux
+./sample.sh WITH_DTLS @@connectivity\samples\linux
+
#include <stdint.h>
#include <stdlib.h>
-
+#include <stdbool.h>
#ifdef __cplusplus
#define CA_MAX_HEADER_OPTION_DATA_LENGTH 16
/**
+* @brief Max token length
+*/
+#define CA_MAX_TOKEN_LEN (8)
+
+/**
* @brief Max URI length
*/
-#define CA_MAX_URI_LENGTH 2048
+#ifdef ARDUINO
+#define CA_MAX_URI_LENGTH 128 /* maximum size of URI for embedded platforms*/
+#else
+#define CA_MAX_URI_LENGTH 512 /* maximum size of URI for other platforms*/
+#endif
/**
- * @brief Max token length
+ * @brief Max PDU length supported
*/
-#define CA_MAX_TOKEN_LEN (8)
+#ifdef ARDUINO
+#define COAP_MAX_PDU_SIZE 320 /* maximum size of a CoAP PDU for embedded platforms*/
+#else
+#define COAP_MAX_PDU_SIZE 1400 /* maximum size of a CoAP PDU for big platforms*/
+#endif
/**
* @brief option types - the highest option number 63
#define CA_OPTION_IF_MATCH 1
#define CA_OPTION_ETAG 4
#define CA_OPTION_IF_NONE_MATCH 5
+#define CA_OPTION_OBSERVE 6
#define CA_OPTION_LOCATION_PATH 8
#define CA_OPTION_URI_PATH 11
#define CA_OPTION_CONTENT_FORMAT 12
#define CA_OPTION_URI_QUERY 15
#define CA_OPTION_ACCEPT 17
#define CA_OPTION_LOCATION_QUERY 20
-#define CA_OPTION_OBSERVE 6
/**
* @brief Payload information from resource model
typedef char *CAToken_t;
/**
- * @enum CABool_t
- * @brief Boolean value used for specifying the success or failure
- */
-typedef enum
-{
- CA_FALSE = 0, /**< False */
- CA_TRUE /**< True */
-} CABool_t;
-
-/**
* @enum CAConnectivityType_t
* @brief Different connectivities that are handled in Connectivity Abstraction
*/
*/
typedef enum
{
- CA_INTERFACE_UP, /**< Connection is Available */
- CA_INTERFACE_DOWN /**< Connection is not available */
+ CA_INTERFACE_DOWN, /**< Connection is not available */
+ CA_INTERFACE_UP /**< Connection is Available */
} CANetworkStatus_t;
/**
struct
{
char ipAddress[CA_IPADDR_SIZE]; /**< Ip address of the interface**/
- uint32_t port; /**< port information**/
+ uint16_t port; /**< port information**/
} IP;
} CAAddress_t;
CA_MSG_CONFIRM = 0, /**< confirmable message (requires ACK/RST) */
CA_MSG_NONCONFIRM, /**< non-confirmable message (one-shot message) */
CA_MSG_ACKNOWLEDGE, /**< used to acknowledge confirmable messages */
- CA_MSG_RESET /**< indicates error in received messages */
+ CA_MSG_RESET /**< used to indicates not-interested or error (lack of context)in
+ received messages */
} CAMessageType_t;
/**
CAURI_t resourceUri; /**< Resource URI information **/
CAAddress_t addressInfo; /**< Remote Endpoint address **/
CAConnectivityType_t connectivityType; /**< Connectivity of the endpoint**/
- CABool_t isSecured; /**< Secure connection**/
+ bool isSecured; /**< Secure connection**/
} CARemoteEndpoint_t;
typedef struct
{
CAAddress_t addressInfo; /**< Address of the interface **/
- CAConnectivityType_t type; /**< Connectivity type that localconnectivity avaialble **/
- CABool_t isSecured; /**< Secure connection**/
+ CAConnectivityType_t type; /**< Connectivity of local device **/
+ bool isSecured; /**< Secure connection**/
} CALocalConnectivity_t;
/**
CA_MEMORY_ALLOC_FAILED, /**< Memory allocation failed */
CA_REQUEST_TIMEOUT, /**< Request is Timeout */
CA_DESTINATION_DISCONNECTED, /**< Destination is disconnected */
- CA_STATUS_FAILED, /**< Failure */
- CA_NOT_SUPPORTED /**< Not supported */
+ CA_NOT_SUPPORTED, /**< Not supported */
+ CA_STATUS_FAILED =255 /**< Failure */
/* Result code - END HERE */
} CAResult_t;
CA_SUCCESS = 200, /**< Success */
CA_CREATED = 201, /**< Created */
CA_DELETED = 202, /**< Deleted */
- CA_EMPTY = 231, /**< Empty */
CA_BAD_REQ = 400, /**< Bad Request */
CA_BAD_OPT = 402, /**< Bad Option */
CA_NOT_FOUND = 404, /**< Not found */
- CA_RETRANSMIT_TIMEOUT = 531 /**< Retransmit timeout */
+ CA_RETRANSMIT_TIMEOUT = 500 /**< Retransmit timeout */
/* Response status code - END HERE */
} CAResponseResult_t;
*/
typedef enum
{
- CA_ADAPTER_ENABLED, /**< Adapter is Enabled */
- CA_ADAPTER_DISABLED /**< Adapter is Disabled */
+ CA_ADAPTER_DISABLED, /**< Adapter is Disabled */
+ CA_ADAPTER_ENABLED /**< Adapter is Enabled */
} CAAdapterState_t;
/**
*/
typedef struct
{
+
+ CAMessageType_t type; /**< Qos for the request */
uint16_t messageId; /**< Message id.
* if message id is zero, it will generated by CA inside.
* otherwise, you can use it */
- CAMessageType_t type; /**< Qos for the request */
CAToken_t token; /**< Token for CA */
CAHeaderOption_t *options; /** Header Options for the request */
uint8_t numOptions; /**< Number of Header options */
*/
typedef struct
{
- CAInfo_t info; /**< Information of the response */
CAResponseResult_t result; /**< Result for response by resource model */
+ CAInfo_t info; /**< Information of the response */
} CAResponseInfo_t;
#ifdef __cplusplus
#endif
#endif //#ifndef __CA_COMMON_H_
+
#define __CA_INTERFACE_H_
/**
- * Connectivity Abstraction Interface Description APIs.
+ * Connectivity Abstraction Interface APIs.
*/
#include "cacommon.h"
* @param RespHandler [IN] Response Handler Callback
* @see CARequestCallback
* @see CAResponseCallback
+ * @return NONE
*/
void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler);
* @param requestInfo [IN] Information for the request.
* @return #CA_STATUS_OK #CA_STATUS_FAILED #CA_MEMORY_ALLOC_FAILED
*/
-CAResult_t CASendRequest(const CARemoteEndpoint_t *object, CARequestInfo_t *requestInfo);
+CAResult_t CASendRequest(const CARemoteEndpoint_t *object,const CARequestInfo_t *requestInfo);
/**
* @brief Send control Request on a resource to multicast group
* @param responseInfo [IN] Information for the response
* @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
*/
-CAResult_t CASendResponse(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo);
+CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
+ const CAResponseInfo_t *responseInfo);
/**
* @brief Send notification to the remote object
* @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
*/
CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
- CAResponseInfo_t *responseInfo);
+ const CAResponseInfo_t *responseInfo);
/**
* @brief To advertise the resource
- * @param resourceUri [IN] URI to be advertised
- * @param token [IN] Token for the request
- * @param options [IN] Header options information
- * @param numOptions [IN] Number of options
+ * @param resourceUri [IN] URI to be advertised
+ * @param token [IN] Token for the request
+ * @param options [IN] Header options information
+ * @param numOptions [IN] Number of options
* @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_MEMORY_ALLOC_FAILED
*/
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAToken_t token,
- CAHeaderOption_t *options, uint8_t numOptions);
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
+ const CAHeaderOption_t *options,const uint8_t numOptions);
/**
* @brief Select network to use
* It should be destroyed by the caller as it Get Information.
* @param info [OUT] LocalConnectivity objects
* @param size [OUT] No Of Array objects
- * @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_STATUS_INVALID_PARAM or #CA_MEMORY_ALLOC_FAILED
+ * @return #CA_STATUS_OK or #CA_STATUS_FAILED or #CA_STATUS_INVALID_PARAM or
+* #CA_MEMORY_ALLOC_FAILED
*/
CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size);
#endif
#endif
+
-=== Pre requites ===
+=== Prerequisites ===
* 1. Scons
3) The above command will build sample also.
- For Enabling Secured server,
+ For Enabling Secured server,
* Note: tinydtls library has to copied to "connectivity/lib/tinydtls" for secured build.
Secured Server will be only used for WIFI and ETHERNET transports.
By Default DEVICE_NAME=OIC-DEVICE, if device name option is not specified
To change the port number, please modify "port" variable in __upload() function in: "/build/arduino/SConscript".
+
clean:
sh arduino/build.sh clean
+
else
$(info *********error**********)
$(error Wrong value for PLATFORM !!)
endif
+
+
+
# True if binary needs to be installed on board. (Might need root permissions)
# set to 'no', 'false' or 0 for only compilation
-require_upload = ARGUMENTS.get('UPLOAD', True)
+require_upload = ARGUMENTS.get('UPLOAD', True)
+
+# Get the device name
+device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")
######################################################################
# Common build options (release, target os, target arch)
help_vars.Add(EnumVariable('SECURED', 'Build with DTLS', '0', allowed_values=('0', '1')))
help_vars.Add(BoolVariable('UPLOAD', 'Upload binary ? (For Arduino)', require_upload))
help_vars.Add(EnumVariable('BUILD_SAMPLE', 'Build with sample', 'ON', allowed_values=('ON', 'OFF')))
+
+help_vars.AddVariables(('DEVICE_NAME', 'Network display name for device', 'OIC-DEVICE', None, None),)
+
######################################################################
# Platform(build target) specific options: SDK/NDK & toolchain
######################################################################
Help(help_vars.GenerateHelpText(env))
-# Get the device name and set it to __OIC_DEVICE_NAME__
-device_name = ARGUMENTS.get('DEVICE_NAME', "OIC-DEVICE")
-print device_name
+# Set device name to __OIC_DEVICE_NAME__
env.AppendUnique(CPPDEFINES = ['-D__OIC_DEVICE_NAME__=' + "\'\"" + device_name + "\"\'"])
tc_set_msg = '''
######################################################################
if target_os == "yocto":
'''
- This code injects Yocto cross-compilation tools+flags into scons'
- build environment in order to invoke the relevant tools while
+ This code injects Yocto cross-compilation tools+flags into scons'
+ build environment in order to invoke the relevant tools while
performing a build.
'''
import os.path
Execute(Delete(dir + '/.sconf_temp'))
Return('env')
+
Compiling Interface APIs FOR Android:
===================================
•Preconditons :
- Please download the glibc directory and keep $(CA_HOME)\lib\android\glib-master
+ Please download the following
+ 1) glib directory and keep at $(CA_HOME)/lib/android/glib-2.40.2
+ 2) tinydlts library and keep at $(CA_HOME)/lib/tinydtls
•Supported version : 5.0 ( Lollipop )
•Required NDK version : android-ndk-r10d ( https://developer.android.com/tools/sdk/ndk/index.html )
• Modify Makefile ( connectivity/build/android/Makefile )
$ cd ${CA_HOME}/connectivity/build/android
$ ndk-build clean; ndk-build
+
env.AppendUnique(CCFLAGS = ['-g'])
env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__ANDROID__','-DTB_LOG'])
-env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
-env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread', '-llog', '-landroid'])
+env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC','`pkg-config','--cflags','glib-2.0`'])
+env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread', '-lglib-2.0', '-lgthread-2.0', '-llog', '-landroid'])
-env.ParseConfig("pkg-config --cflags --libs glib-2.0 gthread-2.0")
+env.Append(LIBS=[
+ '-lglib-2.0', '-lgthread-2.0'
+])
# From android-5 (API > 20), all application must be built with flags '-fPIE' '-pie'.
# Due to the limitation of Scons, it's required to added it into the command line
# directly (otherwise, it will also be added when build share library)
env.Replace(CCCOM = '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SOURCES')
env.Replace(CXXCOM = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SOURCES')
-env.Replace(LINKCOM = '$LINK -o $TARGET -pie $LINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS')
\ No newline at end of file
+env.Replace(LINKCOM = '$LINK -o $TARGET -pie $LINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS')
#Modify below values to enable/disable the Adapter
#Suffix "NO_" to disable given adapter
-EDR = EDR_ADAPTER
+EDR = EDR_ADAPTER
WIFI = WIFI_ADAPTER
-LE = LE_ADAPTER
+LE = LE_ADAPTER
ETHERNET = NO_ETHERNET_ADAPTER
#Add Pre processor definitions
DEFINE_FLAG = -DWITH_POSIX -D__ANDROID__ -D__WITH_DTLS__
-DEFINE_FLAG += -D$(EDR) -D$(LE) -D$(WIFI) -D$(ETHERNET)
+DEFINE_FLAG += -D$(EDR) -D$(LE) -D$(WIFI) -D$(ETHERNET)
#Add Debug flags here
DEBUG_FLAG = -DTB_LOG
#DEBUG_FLAG += -DADB_SHELL
-BUILD_FLAG.debug = $(DEFINE_FLAG) $(DEBUG_FLAG)
+BUILD_FLAG.debug = $(DEFINE_FLAG) $(DEBUG_FLAG)
BUILD_FLAG.release = $(DEFINE_FLAG)
BUILD_FLAG = $(BUILD_FLAG.$(BUILD))
$(WIFI_ADAPTER_PATH)/cawificlient.c $(WIFI_ADAPTER_PATH)/cawifinwmonitor.c \
include $(BUILD_STATIC_LIBRARY)
+
APP_PLATFORM = android-19
APP_CPPFLAGS += -fexceptions
APP_CPPFLAGS += -frtti += -Wno-error=format-security
-APP_CFLAGS = -Wno-error=format-security
\ No newline at end of file
+APP_CFLAGS = -Wno-error=format-security
STEPS to setup Arduino on linux machine for building CA code:
-1) Download the Arduino package as per your system specification from the given link :
+1) Download the Arduino package as per your system specification from the given link :
http://arduino.cc/en/main/software
-
+
2) Unzip the downloaded package to some location say ARDUINO_DIR(This is the arduino installation directory).
ARDUINO_DIR = <PATH_TO_ARDUINO_INSTALL_DIR>/arduino-1.5.x
-3) Change permissions for executable in "ARDUINO_DIR"
- chmod -R +x ./*
-
-4) ONE TIME ONLY - ADDITIONAL LIBRARIES
+3) Change permissions for executable in your "ARDUINO_DIR"
+ chmod -R +x <ARDUINO_DIR>
+
+4.1) ONE TIME ONLY - ADDITIONAL LIBRARIES (Time)
Arduino builds are dependent on latest Time library. Download it from here:
I. http://playground.arduino.cc/Code/Time
- Place this library in the "ARDUINO_DIR/libraries/Time" folder where remaining libraries are present.
- [P.S - The Time library files path should be as follows "ARDUINO_DIR/libraries/Time/Time/{***files***}"]
-
+ Place this library in the "ARDUINO_DIR/libraries/Time" folder where other libraries are present.
+ [P.S - The Time library files path should be as follows "ARDUINO_DIR/libraries/Time/Time/{***files***}"]
+ Some files in this library has windows style line endings, for patch to run properly, please execute following command:
+ cd <ARDUINO_DIR>
+ find ./libraries/Time/ -type f -exec dos2unix {} \;
+
+4.2) ONE TIME ONLY - ADDITIONAL LIBRARIES (BLE)
+ Note: Prior to building for BLE Transport, following additional steps are required:
+ (1) Download RedBearLab Arduino RBL_nRF8001 Library from link(https://github.com/RedBearLab/nRF8001/tree/25643e7b1b7da3740406325a471e3faa4b948747)
+ (2) Extract zip file and apply RBL patch(connectivity/lib/arduino/RBL_nRF8001.patch) to "RBL_nRF8001" folder by following below steps,
+ i) Go to downloaded RBL_Library Folder ("nRF8001-master/Arduino/libraries/RBL_nRF8001")
+ ii) Apply dos2unix for RBL_Library Folder and RBL Patch File (RBL_nRF8001.patch), if we have downloaded Library in Non UNIX Platform.
+ iii) Apply RBL Patch by using the below command
+ patch -p1 < RBL_Patch_File_Location(RBL_nRF8001.patch)
+ (3) Copy the patched RBL_nRF8001 Library and place it in "arduino-<x.x.x>/libraries" folder
+ (4) Download Nordic Arduino BLE library [Tag: "0.9.5.Beta" Version] from the link (https://github.com/NordicSemiconductor/ble-sdk-arduino).
+ Extract the zip file and copy the "BLE" folder available under "libraries" folder and place it in "arduino-<x.x.x>/libraries" folder
+
5) ONE TIME ONLY - PATCH
Complete patch has been provided at : "connectivity\lib\arduino\arduino_libraries.patch"
- Copy this patch file to "ARDUINO_DIR/libraries/"
-
-6) To apply patch give the command :
+ Copy this patch file to "ARDUINO_DIR/"
+
+6) To apply patch give the command :
patch -p1 < arduino_libraries.patch
To undo the patch give the command :
patch -R -p1 < arduino_libraries.patch
-
-7) Launch Arduino IDE (required for logs and port and board selection.)
+
+7) ONE TIME ONLY - FIRMWARE UPGRADE (FOR WIFI SHIELD)
+ To support UDP over WiFi, WiFi shield needs to run latest firmware. Please refer:
+ (http://arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading)
+ for instructions on how to upgrade your firmware.
+
+8) Launch Arduino IDE (required for logs and port and board selection.)
Goto to "ARDUINO_DIR" directory.
Launch command := sudo ./arduino
-
-8) Select your board and port under the tools option in Arduino IDE.
\ No newline at end of file
+
+9) Select your board and port under the tools option in Arduino IDE.
PLATFORM := arduinomega
TRANSPORT := BLE
OBJ_DIR := ./bin
-APP_NAME := sample_main
+APP_NAME := casample
ARDUINO_PORT := ttyACM0
include ./local.properties
+
-Setting Wi-Fi SSID and Password for Arduino Wi-FI Shield
-=====================================
-PreCondition: In connectivity\src\wifi_adapter\arduino\cawifiserver.cpp
-Update the SSID and Password credentials before testing with Wi-Fi Shield
-char ssid[] = ""; // your network SSID (name)
-char pass[] = ""; // your network password
-
BUILDING for ARDUINOMEGA:
========================================
PREREQ: Arduino MUST be installed in the machine where we compile. Refer to Arduino_Setup_README file for help.
sudo make PLATFORM=arduinomega TRANSPORT=<ETHERNET/BLE/WIFI> ARDUINO_DIR = <PATH_TO_ARDUINO_INSTALL_DIR>/arduino-1.5.x
P.S : For PATH_TO_ARDUINO_INSTALL_DIR value refer Arduino_Setup_README.txt file.
-Note: Prior to building for BLE Transport, following additional steps are required:
-1) Download RedBearLab Arduino RBL_nRF8001 Library committed (2014/7/30 18:17:53) from link(https://github.com/RedBearLab/nRF8001)
-2) Extract zip file and apply RBL patch(connectivity/lib/arduino/RBL_nRF8001.patch) to "RBL_nRF8001" folder by following below steps,
- i) Go to downloaded RBL_Library Folder ("nRF8001-master/Arduino/libraries/RBL_nRF8001")
- ii) Apply dos2unix for RBL_Library Folder and RBL Patch File (RBL_nRF8001.patch), if we have downloaded Library in Non UNIX Platform.
- iii) Apply RBL Patch by using the below command
- patch -p1 < RBL Patch File Location(RBL_nRF8001.patch)
-3) Copy the patched RBL_nRF8001 Library and place it in "arduino-<x.x.x>/libraries" folder
-4) Download Nordic Arduino BLE library from the link (https://github.com/NordicSemiconductor/ble-sdk-arduino).
- Extract the zip file and copy the "BLE" folder available under "libraries" folder and place it in "arduino-<x.x.x>/libraries" folder
-
Flashing Interface APIs for ARDUINOMEGA:
========================================
Precondition: Connect Arduino Mega Board to Linux PC. Open Arduino IDE and select corresponding connected PORT
It will flash BLE Transport Adaptor in Arduino Board. Similarly, TRANSPORT can be changed to ETHERNET, BLE, WIFI etc..
To Run Adapter code in ARDUINOMEGA Board:
-========================================
+========================================
PreCondition: Flash the executable in ARDUINO MEGA BOARD. Follow above Step(Flashing Interface APIs for ARDUINOMEGA)
-1) Open Serial Monitor in Arduino IDE. It will execute the flashed binary and logs will be available in serial Monitor under BaudRate(115200)
\ No newline at end of file
+1) Open Serial Monitor in Arduino IDE. It will execute the flashed binary and logs will be available in serial Monitor under BaudRate(115200)
matches = []
for root, dirnames, filenames in os.walk(path):
#BLE library examples throw lot of errors. We dont need examples.
- if 'examples' not in root:
+ if 'examples' not in root:
matches.extend(Glob(root + '/' + pattern, ondisk, source, strings))
return matches
env.AddMethod(__create_bin, "CreateBin") #create binary files(.eep and .hex)
env.AddMethod(__upload, "Upload") #Upload binary to board
env.AddMethod(__upload_help, "UploadHelp") #print the command line that to upload binary to the boardf
+
env.ImportLib('WiFi')
if 'BLE' in env.get('TARGET_TRANSPORT'):
env.ImportLib('BLE')
- env.ImportLib('RBL_nRF8001')
+ env.ImportLib('RBL_nRF8001')
env.ImportLib('Time/Time')
# we have variety of macros for arduino!!
-I$(INCD_ARD_TIME) -I$(IDIR_ARD_SPI) \
-I$(INCD_ARD_BASE1) -I$(INCD_ARD_BASE2) -I$(INCD_ARD_BASE3) \
-I$(INCD_ARD_BASE4) -I$(IDIR_ARD_ETH) -I$(IDIR_ARD_ETH_UTIL) \
- -I$(IDIR_ARD_ETH1)
+ -I$(IDIR_ARD_ETH1)
else ifeq ($(TRANSPORT),WIFI)
IDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi/src
IDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/src/utility
-I$(INCD_ARD_TIME) -I$(IDIR_ARD_SPI) \
-I$(INCD_ARD_BASE1) -I$(INCD_ARD_BASE2) -I$(INCD_ARD_BASE3) \
-I$(INCD_ARD_BASE4) -I$(IDIR_ARD_ETH_UTIL) -I$(IDIR_ARD_WIFI) \
- -I$(IDIR_ARD_WIFI_UTIL)
-else ifeq ($(TRANSPORT),BLE)
+ -I$(IDIR_ARD_WIFI_UTIL)
+else ifeq ($(TRANSPORT),BLE)
IDIR_ARD_BLE = $(ARDUINO_DIR)/libraries/BLE
IDIR_ARD_RBL = $(ARDUINO_DIR)/libraries/RBL_nRF8001
INCD_ARD_BLE1 = $(BASE_DIR)/src/bt_le_adapter/arduino/
LOGGER_OBJ = logger.c.o oic_logger.c.o oic_console_logger.c.o oic_malloc.c.o oic_string.c.o uarraylist.c.o
UTIL_OBJ = caadapterutils.c.o camsgparser.c.o
CACOMMON_OBJ = caconnectivitymanager_singlethread.c.o cainterfacecontroller_singlethread.c.o camessagehandler_singlethread.c.o canetworkconfigurator_singlethread.c.o caprotocolmessage_singlethread.c.o \
- caremotehandler.c.o caretransmission_singlethread.cpp.o
+ caremotehandler.c.o caretransmission_singlethread.c.o
ifeq ($(TRANSPORT),ETHERNET)
ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o EthernetClient.o
INTERFACE_OBJ = caethernetadapterutils.cpp.o caethernetclient.cpp.o caethernetserver.cpp.o caethernetnwmonitor.cpp.o caethernetadapter_singlethread.c.o
PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) $(UTIL_OBJ) $(CACOMMON_OBJ)
else ifeq ($(TRANSPORT),WIFI)
- WIFI_CPPOBJ = WiFi.cpp.o WiFiClient.cpp.o WiFiServer.cpp.o WiFiUdp.cpp.o
+ WIFI_CPPOBJ = WiFi.cpp.o WiFiClient.cpp.o WiFiServer.cpp.o WiFiUdp.cpp.o
WIFI_UTIL_CPPOBJ = server_drv.cpp.o spi_drv.cpp.o wifi_drv.cpp.o
INTERFACE_OBJ = cawificlient.cpp.o cawifiserver.cpp.o cawifinwmonitor.cpp.o cawifiadapter_singlethread.c.o
PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(WIFI_CPPOBJ) $(WIFI_UTIL_CPPOBJ) $(UTIL_OBJ) $(CACOMMON_OBJ)
-else ifeq ($(TRANSPORT),BLE)
+else ifeq ($(TRANSPORT),BLE)
BLE_OBJ = aci_queue.cpp.o aci_setup.cpp.o acilib.cpp.o hal_aci_tl.cpp.o lib_aci.cpp.o
RBL_OBJ = RBL_nRF8001.cpp.o
INTERFACE_OBJ = caleadapter_singlethread.c.o cableserver.cpp.o cablenwmonitor.cpp.o
- PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(BLE_OBJ) $(RBL_OBJ) $(UTIL_OBJ) $(CACOMMON_OBJ)
+ PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(BLE_OBJ) $(RBL_OBJ) $(UTIL_OBJ) $(CACOMMON_OBJ)
else
$(info *********error**********)
$(error Wrong value for TRANSPORT !!)
endif
+
cd ../../build/arduino/
make $1 PLATFORM=$2 TRANSPORT=$3 ARDUINO_DIR=$4 APP_NAME=$5
fi
-fi
+fi
\ No newline at end of file
ARDUINO_DIR = /usr/share/arduino
ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
+
SHELL = /bin/bash
PROJECT_NAME = connectivity_abstraction
PROJECT_ROOT_PATH = ..
-PROJECT_API_PATH = $(PROJECT_ROOT_PATH)/api
-PROJECT_INC_PATH = $(PROJECT_ROOT_PATH)/inc
+PROJECT_API_PATH = $(PROJECT_ROOT_PATH)/api
+PROJECT_INC_PATH = $(PROJECT_ROOT_PATH)/inc
PROJECT_SRC_PATH = $(PROJECT_ROOT_PATH)/src
-PROJECT_COMMON_INC_PATH = $(PROJECT_ROOT_PATH)/common/inc
-PROJECT_COMMON_SRC_PATH = $(PROJECT_ROOT_PATH)/common/src
-PROJECT_COMMON_PATH = $(PROJECT_ROOT_PATH)/common
+PROJECT_COMMON_INC_PATH = $(PROJECT_ROOT_PATH)/common/inc
+PROJECT_COMMON_SRC_PATH = $(PROJECT_ROOT_PATH)/common/src
+PROJECT_COMMON_PATH = $(PROJECT_ROOT_PATH)/common
PROJECT_OUT_PATH = $(PROJECT_ROOT_PATH)/build/out
-PROJECT_LIB_PATH = $(PROJECT_ROOT_PATH)/lib
+PROJECT_LIB_PATH = $(PROJECT_ROOT_PATH)/lib
##
## macro
CD = cd
RANLIB = ranlib
+
LDFLAGS := -L$(libcoap_build_dir) -L$(libtiny_lib_dir)
LDLIBS := -lcoap -ltinydtls
else
-LDFLAGS := -L$(libcoap_build_dir)
-LDLIBS := -lcoap
+LDFLAGS := -L$(libcoap_build_dir)
+LDLIBS := -lcoap
endif
BUILD_FLAG.debug = $(DEFINE_FLAG) $(DEBUG_FLAG)
.PHONY: all clean install
+
else:
env.AppendUnique(CCFLAGS = ['-g'])
env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
-
+
env.AppendUnique(CPPDEFINES = ['WITH_POSIX', '__linux__'])
env.AppendUnique(CCFLAGS = ['-Wall', '-fPIC'])
env.AppendUnique(LINKFLAGS = ['-ldl', '-lpthread'])
CD = cd
RANLIB = ranlib
+
rm -f *.o *.d *.elf *.eep core.a *.hex *.bin *.map *-
rm -rf $(OBJ_DIR)
rm -rf $(LIBCOAP_OBJ_DIR)
+
Execute(Delete(dir + '/.sconf_temp'))
Return('env')
+
--- /dev/null
+<manifest>
+ <define>
+ <domain name="calib" />
+ <permit>
+ <smack permit="system::use_internet" type="rwx"/>
+ </permit>
+ <request>
+ <smack request="system::use_internet" type="rwx"/>
+ <smack request="bt-service" type="rwx"/>
+ <smack request="sap" type="rwx"/>
+ <smack request="bt-service::spp" type="rwx"/>
+ <smack request="bt-service::gap" type="rwx"/>
+ <smack request="bt-service::admin" type="rwx"/>
+ <smack request="bt-service::manager" type="rwx"/>
+ <smack request="bt-service::public" type="rwx"/>
+ <smack request="bt-service::platform" type="rwx"/>
+ </request>
+ </define>
+ <request>
+ <domain name="calib" />
+ </request>
+</manifest>
+
prefix=/usr
exec_prefix=${prefix}
libdir=${prefix}/lib
-includedir=${prefix}/include/interfaceHeaders
+includedir=${prefix}/include/OICHeaders
-Name: com.oic.ca
+Name: com-oic-ca
Description: Oic core library
Version: 1.0
Cflags: -I${includedir}
+
cd $sourcedir
rm -rf $sourcedir/tmp
+
%define PREFIX /usr/apps/com.oic.ca
%define ROOTDIR %{_builddir}/%{name}-%{version}
-%define USR_INC_DIR /usr/include
-%define DEST_INC_DIR %{buildroot}%{USR_INC_DIR}/interfaceHeaders
-%define DEST_LIB_DIR %{buildroot}/usr/lib
+%define DEST_INC_DIR %{buildroot}/%{_includedir}/OICHeaders
+%define DEST_LIB_DIR %{buildroot}/%{_libdir}
-Name: com.oic.ca
+Name: com-oic-ca
Version: 0.1
Release: 1
Summary: Tizen oicca application
URL: http://slp-source.sec.samsung.net
Source: %{name}-%{version}.tar.gz
-License: Apache License, Version 2.0
-Group: OIC/Application
-#BuildRequires: cmake
+License: Apache-2.0
+Group: Applications/OIC
BuildRequires: pkgconfig(dlog)
BuildRequires: pkgconfig(glib-2.0)
BuildRequires: pkgconfig(capi-network-wifi)
BuildRequires: boost-system
BuildRequires: boost-filesystem
BuildRequires: scons
-#BuildRequires: oic-core
+
%description
SLP oicca application
scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT} RELEASE=%{RELEASE}
%install
-rm -rf %{buildroot}
-mkdir -p %{buildroot}/usr/share/license
-mkdir -p %{buildroot}/usr/share/packages
-mkdir -p %{buildroot}/etc/smack/accesses2.d
-mkdir -p %{buildroot}/usr/apps/com.oic.ca/bin/
-mkdir -p %{buildroot}/usr/lib
mkdir -p %{DEST_INC_DIR}
mkdir -p %{DEST_LIB_DIR}/pkgconfig
-cp -rf %{ROOTDIR}/con/src/libconnectivity_abstraction.a %{buildroot}/usr/lib
-cp -rf %{ROOTDIR}/con/lib/libcoap-4.1.1/libcoap.a %{buildroot}/usr/lib
+cp -f %{ROOTDIR}/con/src/libconnectivity_abstraction.a %{buildroot}/%{_libdir}
+cp -f %{ROOTDIR}/con/lib/libcoap-4.1.1/libcoap.a %{buildroot}/%{_libdir}
cp -rf %{ROOTDIR}/con/api/cacommon.h* %{DEST_INC_DIR}/
cp -rf %{ROOTDIR}/con/inc/caadapterinterface.h* %{DEST_INC_DIR}/
cp -rf %{ROOTDIR}/con/common/inc/uthreadpool.h* %{DEST_INC_DIR}/
%files
+%manifest com.oic.ca.manifest
%defattr(-,root,root,-)
-%attr(-,inhouse,inhouse)
%{_libdir}/lib*.a*
-%{_includedir}/interfaceHeaders/*
+%{_includedir}/OICHeaders/*
%{_libdir}/pkgconfig/*.pc
+
env.AppendUnique(CFLAGS = ['-std=c99', '-fPIC', '-D__TIZEN__','-DWITH_POSIX', '-Wall', '-DSLP_SDK_LOG', '-g','-D_GNU_SOURCE','-DTIZEN_DEBUG_ENABLE', '-DTB_LOG'])
env.ParseConfig("pkg-config --cflags --libs capi-network-wifi dlog glib-2.0")
-
if 'ALL' in transport:
env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER', 'NO_ETHERNET_ADAPTER','EDR_ADAPTER','LE_ADAPTER'])
print "CA Transport is ALL"
header = ' '
for item in temp:
header = header + ' -I' + item
-
+
######################################################################
# Source files and Target(s)
######################################################################
ca_common_src_path + 'uarraylist.c',
ca_common_src_path + 'uqueue.c',
]
-
+
if ca_os == 'arduino':
- env.Command(env.get('BUILD_DIR') + 'logger.c', None, '$CXX -o ' + env.get('BUILD_DIR') + 'logger.c' + ' $LINKFLAGS $CCFLAGS $CXXFLAGS ' + header + ' ' + 'common/src/logger.c')
+ env.Command(env.get('BUILD_DIR') + 'logger.c.o', None, '$CXX -o ' + env.get('BUILD_DIR') + 'logger.c.o' + ' $LINKFLAGS $CCFLAGS $CXXFLAGS ' + header + ' ' + 'common/src/logger.c')
platform_src = [
env.get('BUILD_DIR') + 'logger.c.o',
]
* @param tag - Module name
* @param logStr - log string
*/
-void OICLog(LogLevel level, PROGMEM const char *tag, const int16_t lineNum, PROGMEM const char *logStr);
+void OICLog(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
+ PROGMEM const char *logStr);
/**
* Output the contents of the specified buffer (in hex) with the specified priority level.
* @param tag - Module name
* @param format - variadic log string
*/
-void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum, PROGMEM const char *format, ...);
+void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
+ PROGMEM const char *format, ...);
#endif
#ifdef TB_LOG
}
#endif // __cplusplus
#endif /* _U_LOGGER_H_ */
+
/* Basic interface: */
oic_log_ctx_t *oic_log_make_ctx(void *world, const oic_log_level level, oic_log_init_t init,
- oic_log_destroy_t destroy, oic_log_flush_t flush, oic_log_set_level_t set_level,
- oic_log_write_level_t write_level, oic_log_set_module_t set_module);
+ oic_log_destroy_t destroy, oic_log_flush_t flush,
+ oic_log_set_level_t set_level,oic_log_write_level_t write_level,
+ oic_log_set_module_t set_module);
void oic_log_destroy(oic_log_ctx_t *ctx);
#endif
#endif
+
void *OICMalloc(size_t size);
/**
+ * Allocates a block of memory for an array of num elements, each of them
+ * size bytes long and initializes all its bits to zero.
+ *
+ * @param num - The number of elements
+ * @param size - Size of the element type in bytes, where size > 0
+ *
+ * @return
+ * on success, a pointer to the allocated memory block
+ * on failure, a null pointer is returned
+ */
+void *OICCalloc(size_t num, size_t size);
+
+/**
* Deallocate a block of memory previously allocated by a call to OCMalloc
*
* NOTE: This function is intended to be used internally by the TB Stack.
}
#endif // __cplusplus
#endif /* _OIC_MALLOC_H_ */
+
#ifndef _OIC_STRING_H_
#define _OIC_STRING_H_
-#include <stdio.h>
-#include <string.h>
-#include "oic_malloc.h"
-
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus
+
/**
* Duplicates the source string and returns it.
*
#ifdef __cplusplus
}
#endif // __cplusplus
-#endif /* _OIC_STRING_H_ */
+#endif
+/* _OIC_STRING_H_ */
+
#endif
/**
- * Use this default size when initialized
- */
-#define U_ARRAYLIST_DEFAULT_SIZE 1
-
-/**
* @struct u_arraylist_t
* @brief array list structure
*/
/**
* @brief Resets and deletes the array list
- * application should free the memory of data in array list
+ * Arraylist elements are deleted. Calling function must take care of free
+ * dynamic memory allocated before freeing the arraylist
* @param list- u_arraylist pointer
* @return CAResult_t
- * CA_STATUS_OK if Success, CA_STATUS_FAILED otherwise
+ * CA_STATUS_OK if Success, CA_STATUS_INVALID_PARAM if pointer to list is NULL
*/
CAResult_t u_arraylist_free(u_arraylist_t **list);
* [IN] pointer of array list
* @param index
* [IN] index of array list
- * @return void pointer of the data
+ * @return void pointer of data if success or NULL pointer otherwise
*/
void *u_arraylist_get(const u_arraylist_t *list, uint32_t index);
* @param data
* [IN] pointer of data
* @return CAResult_t
- * CA_STATUS_OK if Success, CA_STATUS_FAILED otherwise
+ * CA_STATUS_OK if Success, CA_MEMORY_ALLOC_FAILED if memory allocation fails
*/
CAResult_t u_arraylist_add(u_arraylist_t *list, void *data);
* [IN] pointer of array list
* @param index
* [IN] index of array list
- * @return void pointer of the data
+ * @return void pointer of the data if success or NULL pointer otherwise
*/
void *u_arraylist_remove(u_arraylist_t *list, uint32_t index);
* [IN] pointer of array list
* @param data
* [IN] pointer of data
- * @return 1 if exists, 0 otherwise
+ * @return true if exists, false otherwise
*/
-uint8_t u_arraylist_contains(const u_arraylist_t *list, void *data);
+bool u_arraylist_contains(const u_arraylist_t *list,const void *data);
#ifdef __cplusplus
}
#ifndef __UMUTEX_H_
#define __UMUTEX_H_
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <stdint.h>
-
#include "cacommon.h"
#ifdef __cplusplus
typedef void *u_cond;
/**
- * @fn u_mutex_init
- * @brief Initializes the thread system for using other mutex related APIs
- *
- */
-void u_mutex_init(void);
-
-/**
* @fn u_mutex_new
* @brief Creates new mutex
*
* @return Reference to newly created mutex, otherwise NULL.
*
- * @see u_mutex_Init
*/
u_mutex u_mutex_new(void);
*
* @param mutex The mutex to be locked
*
- * @return CA_TRUE if the mutex is not locked currently, otherwise CA_FALSE.
+ * @return true if the mutex is not locked currently, otherwise false.
*
*/
-CABool_t u_mutex_trylock(u_mutex mutex);
+bool u_mutex_trylock(u_mutex mutex);
/**
* @fn u_mutex_unlock
*
* @return Reference to newly created @u_cond, otherwise NULL.
*
- * @see u_mutex_Init
*/
u_cond u_cond_new(void);
/**
* @fn u_cond_wait
- * @brief Waits untill this thread woken up on @cond
+ * @brief Waits until this thread woken up on @cond
*
* @param cond The condtion to be wait for to signal
* @param mutex The mutex which is currently locked from calling thread
/**
* @fn u_cond_wait
- * @brief Waits untill this thread woken up on @cond,
- * but not longer than until the time specified by milliseconds.
+ * @brief Waits until this thread woken up on @cond,
+ * but not longer than until the time specified by microseconds.
* The mutex is unlocked before falling asleep and locked again before resuming.
- * If milliseconds is 0 or under, u_cond_timed_wait() acts like u_cond_wait().
+ * If microseconds is 0 or under, u_cond_wait_until() acts like u_cond_wait().
*
* @param cond The condtion to be wait for to signal
* @param mutex The mutex which is currently locked from calling thread
* @param microseconds relative time for waiting, microseconds
*
*/
-void u_cond_timed_wait(u_cond cond, u_mutex mutex, int32_t microseconds);
+void u_cond_wait_until(u_cond cond, u_mutex mutex, int32_t microseconds);
/**
* @fn u_cond_free
} /* extern "C" */
#endif /* __cplusplus */
-#endif //__UMUTEX_H_
+#endif /*__UMUTEX_H_ */
+
/**
* @fn u_queue_get_size
- * Returns number of elements in queue
- * Input : queue - pointer to queue
- * Return : number of elements in queue
+ * @param queue - pointer to queue
+ * @return number of elements in queue
*/
uint32_t u_queue_get_size(u_queue_t *queue);
#endif /* __cplusplus */
#endif /* _U_QUEUE_H_ */
+
#ifndef __UTHREAD_POOL_H_
#define __UTHREAD_POOL_H_
-#include <stdio.h>
-#include <malloc.h>
#include <glib.h>
#include "cacommon.h"
* This function adds a routine to be executed by the thread pool at some future time.
*
* @param thread_pool The thread pool structure.
- * @param routine The routine to be executed.
+ * @param method The routine to be executed.
* @param data The data to be passed to the routine.
*
* @return CA_STATUS_OK on success.
* @return Error on failure.
*/
-CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(void *),
+CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, u_thread_func method,
void *data);
/**
#endif /* __cplusplus */
#endif /* __UTHREAD_POOL_H_ */
+
* @param tag - Module name
* @param logStr - log string
*/
-void OICLog(LogLevel level, PROGMEM const char *tag, const int16_t lineNum, PROGMEM const char *logStr)
+void OICLog(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
+ PROGMEM const char *logStr)
{
if (!logStr || !tag)
{
* @param tag - Module name
* @param format - variadic log string
*/
-void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum, PROGMEM const char *format, ...)
+void OICLogv(LogLevel level, PROGMEM const char *tag, const int16_t lineNum,
+ PROGMEM const char *format, ...)
{
char buffer[LINE_BUFFER_SIZE];
va_list ap;
}
#endif //ARDUINO
+
oic_log_ctx_t *oic_make_console_logger()
{
return oic_log_make_ctx(NULL, OIC_LOG_ALL, oic_console_logger_init, oic_console_logger_destroy,
- oic_console_logger_flush, oic_console_logger_set_level, oic_console_logger_write,
- oic_console_logger_set_module);
+ oic_console_logger_flush, oic_console_logger_set_level,
+ oic_console_logger_write,oic_console_logger_set_module);
}
int oic_console_logger_init(oic_log_ctx_t *ctx, void *world)
/* We don't do anything special when the module name changes: */
return 1;
}
+
#include <stdlib.h>
oic_log_ctx_t *oic_log_make_ctx(void *world, const oic_log_level level, oic_log_init_t init,
- oic_log_destroy_t destroy, oic_log_flush_t flush, oic_log_set_level_t set_level,
- oic_log_write_level_t write_level, oic_log_set_module_t set_module)
+ oic_log_destroy_t destroy, oic_log_flush_t flush,
+ oic_log_set_level_t set_level,oic_log_write_level_t write_level,
+ oic_log_set_module_t set_module)
{
oic_log_ctx_t *log_ctx;
return ctx->set_module(ctx, ctx->module_name);
}
+
#endif
}
+void *OICCalloc(size_t num, size_t size)
+{
+ if(0 == size || 0 == num)
+ {
+ return NULL;
+ }
+
+#ifdef ENABLE_MALLOC_DEBUG
+ void *ptr = 0;
+
+ ptr = calloc(num, size);
+ OIC_LOG_V(INFO, TAG, "calloc: ptr=%p, num=%u, size=%u", ptr, num, size);
+ return ptr;
+#else
+ return calloc(num, size);
+#endif
+}
+
void OICFree(void *ptr)
{
#ifdef ENABLE_MALLOC_DEBUG
free(ptr);
}
+
******************************************************************/
#include "oic_string.h"
+#include <string.h>
+#include "oic_malloc.h"
+
char *OICStrdup(const char *str)
{
// Allocate memory for original string length and 1 extra byte for '\0'
char *dup = (char *)OICMalloc(length + 1);
if (NULL != dup)
{
- memcpy(dup, str, length);
- dup[length] = '\0';
+ memcpy(dup, str, length + 1);
}
return dup;
}
+
#define TAG "UARRAYLIST"
+/**
+ * Use this default size when initialized
+ */
+#define U_ARRAYLIST_DEFAULT_SIZE 1
+
u_arraylist_t *u_arraylist_create()
{
u_arraylist_t *list = NULL;
- if (!(list = (u_arraylist_t *) OICMalloc(sizeof(u_arraylist_t))))
+ list = (u_arraylist_t *) OICMalloc(sizeof(u_arraylist_t));
+ if (!list)
{
return NULL;
}
list->size = U_ARRAYLIST_DEFAULT_SIZE;
list->length = 0;
- if (!(list->data = (void *) OICMalloc(list->size * sizeof(void *))))
+ list->data = (void *) OICMalloc(list->size * sizeof(void *));
+ if (!list->data)
{
OIC_LOG(DEBUG, TAG, "Out of memory");
OICFree(list);
CAResult_t u_arraylist_free(u_arraylist_t **list)
{
- if (*list == NULL)
+ if (!list || !(*list))
+ {
return CA_STATUS_INVALID_PARAM;
+ }
OICFree((*list)->data);
OICFree(*list);
void *u_arraylist_get(const u_arraylist_t *list, uint32_t index)
{
- if (index >= list->length)
+ if (!list )
{
return NULL;
}
- if (list->data)
+ if ((index < list->length) && (list->data))
{
return list->data[index];
}
CAResult_t u_arraylist_add(u_arraylist_t *list, void *data)
{
- uint32_t new_size = 0;
+ if (!list)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
if (list->size <= list->length)
{
- new_size = list->size + 1;
+ uint32_t new_size = list->size + 1;
if (!(list->data = (void **) realloc(list->data, new_size * sizeof(void *))))
{
return CA_MEMORY_ALLOC_FAILED;
}
- (void) memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *));
+ memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *));
list->size = new_size;
}
{
void *removed = NULL;
+ if (!list)
+ {
+ return NULL;
+ }
+
if (index >= list->length)
{
return NULL;
uint32_t u_arraylist_length(const u_arraylist_t *list)
{
- if (NULL == list)
+ if (!list)
{
OIC_LOG(DEBUG, TAG, "Invalid Parameter");
return 0;
return list->length;
}
-uint8_t u_arraylist_contains(const u_arraylist_t *list, void *data)
+bool u_arraylist_contains(const u_arraylist_t *list,const void *data)
{
uint32_t i = 0;
- for (i = 0; i < u_arraylist_length(list); i++)
+ if (!list)
+ {
+ return false;
+ }
+
+ uint32_t length = u_arraylist_length(list);
+
+ for (i = 0; i < length; i++)
{
if (data == u_arraylist_get(list, i))
{
- return 1;
- }
- else
- {
- continue;
+ return true;
}
}
- return 0;
+ return false;
}
+
*/
#define TAG PCF("UMUTEX")
-void u_mutex_init(void)
-{
- /*Initialize the glib thread system if it is not. GMutex works only if the threadsystem is initialized*/
- if (!g_thread_supported())
- {
- g_thread_init(NULL);
- }
-}
-
u_mutex u_mutex_new(void)
{
- if (!g_thread_supported())
- {
- return NULL;
- }
-
- GMutex *mutexLock = g_mutex_new();
+ GMutex *mutexLock = g_new(GMutex, 1);
+ g_mutex_init(mutexLock);
return (u_mutex) mutexLock;
}
g_mutex_lock(mutexLock);
}
-CABool_t u_mutex_trylock(u_mutex mutex)
+bool u_mutex_trylock(u_mutex mutex)
{
if (NULL == mutex)
{
OIC_LOG_V(ERROR, TAG, "u_mutex_trylock, Invalid mutex !");
- return CA_FALSE;
+ return false;
}
GMutex *mutexLock = (GMutex *) mutex;
- gboolean ret = g_mutex_trylock(mutexLock);
- if (TRUE == ret)
- {
- return CA_TRUE;
- }
- return CA_FALSE;
+ return(g_mutex_trylock(mutexLock));
}
void u_mutex_unlock(u_mutex mutex)
}
GMutex *mutexLock = (GMutex *) mutex;
- g_mutex_free(mutexLock);
+ g_mutex_clear(mutexLock);
+ g_free(mutexLock);
}
u_cond u_cond_new(void)
{
- if (!g_thread_supported())
- {
- return NULL;
- }
-
- GCond *condition = g_cond_new();
+ GCond *condition = g_new(GCond, 1);
+ g_cond_init(condition);
return (u_cond) condition;
}
g_cond_wait(condition, mutexLock);
}
-void u_cond_timed_wait(u_cond cond, u_mutex mutex, int32_t microseconds)
+void u_cond_wait_until(u_cond cond, u_mutex mutex, int32_t microseconds)
{
if (NULL == mutex)
{
return;
}
- GTimeVal abs_time;
- memset(&abs_time, 0, sizeof(GTimeVal));
-
- g_get_current_time(&abs_time);
- g_time_val_add(&abs_time, microseconds);
+ gint64 end_time;
+ end_time = g_get_monotonic_time() + microseconds;
- g_cond_timed_wait(condition, mutexLock, &abs_time);
+ g_cond_wait_until(condition, mutexLock, end_time);
}
void u_cond_free(u_cond cond)
}
GCond *condition = (GCond *) cond;
- g_cond_free(condition);
+ g_cond_clear(condition);
+ g_free(condition);
}
+
queue->element = element;
queue->count++;
OIC_LOG_V(DEBUG, TAG, "Queue Count : %d", queue->count);
-
- return CA_STATUS_OK;
}
return CA_STATUS_OK;
u_queue_message_t *u_queue_get_element(u_queue_t *queue)
{
- u_queue_element *next = NULL;
u_queue_element *element = NULL;
u_queue_message_t *message = NULL;
return NULL;
}
- next = element->next;
- queue->element = next;
+ queue->element = element->next;;
queue->count--;
message = element->message;
CAResult_t u_queue_reset(u_queue_t *queue)
{
- CAResult_t error = CA_STATUS_FAILED;
-
if (NULL == queue)
{
OIC_LOG(DEBUG, TAG, "QueueReset FAIL, Invalid Queue");
while (NULL != queue->element)
{
- error = u_queue_remove_element(queue);
- if (error == CA_STATUS_FAILED)
- break;
+ u_queue_remove_element(queue);
}
if (NO_MESSAGES != queue->count)
}
return queue->element->message;
}
+
#define TAG PCF("UTHREADPOOL")
/**
- * @var gThreadpool
- * @brief Glib thread pool.
- */
-static GThreadPool *gThreadpool = NULL;
-
-/**
* @fn run
* @brief function which is registed to glib thread pool.
*/
GError *error = NULL;
-#ifdef __ANDROID__
- //If not intialized, gthreadpool intialize check fails
- g_thread_init(NULL);
-#endif //__ANDROID__
+ GThreadPool *threadPool = g_thread_pool_new(run, NULL, num_of_threads, TRUE, &error);
- gThreadpool = g_thread_pool_new(run, NULL, num_of_threads, TRUE, &error);
- if (NULL == gThreadpool)
+ if (NULL == threadPool)
{
OIC_LOG(ERROR, TAG, "g_thread_pool_new failed!");
if (NULL != error)
return CA_STATUS_FAILED;
}
- *thread_pool = (u_thread_pool_t) gThreadpool;
+ *thread_pool = (u_thread_pool_t) threadPool;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
-CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(void *),
+CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, u_thread_func method,
void *data)
{
OIC_LOG(DEBUG, TAG, "IN");
- if (NULL == routine)
+ if (NULL == method)
{
OIC_LOG(ERROR, TAG, "routine is NULL!");
return CA_STATUS_FAILED;
}
message->data = data;
- message->func = routine;
+ message->func = method;
g_thread_pool_push((GThreadPool *) thread_pool, (void *) message, NULL);
// Free message
OICFree(message);
}
+
+++ /dev/null
-Project Name: IoTivity
-Release Version No. / Label Name: CA_v0.1
-API Version: CA_v0.4
-
-Release Description:
-Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports.
-
-Scope of Release:
-1. Supported APIs ( please check below APIs)
-2. Samples to test Supported APIs.
-3. OIC Coding guidelines followed based on the current CSDK source.
-4. Multi-Threaded Connectivity abstraction
-5. Executed Open Source Verification and Prevent analysis.
-
-The following Connectivity Abstraction API features are supported in this release:
-
-Supported APIs
-CAInitialize()
-CATerminate()
-CAStartListeningServer()
-CAStartDiscoveryServer()
-CARegisterHandler()
-CAhandleRequestResponse()
-FindResource()
-SendRequest()
-SendResponse()
-SelectNetwork()
-UnselectNetwork()
-
-Non Supported APIs
-SendNotification()
-AdvertizeResource()
-CAGenerateToken()
-CADestryToken()
-CAGetNetworkInfo()
-
-Type of Release: Source,
-Platform OS: Ubuntu 12.0.4 and above:
-
-Connectivity: WIFI only
-Preconditions:
-1)gcc 4.6.3 and above.
-2)glib library (sudo apt-get install libglib2.0-dev)
-3)libcoap.a library ( do make @lib/libcoap-4.1.1)
-
-Known and Open Issues:
-1) OIC Log, OIC malloc will be removed once name changes applied to OIC Bases code
-2) Support only WIFI Interface.
-3) URI length is 16 characters.
-
-Nature of Release: Partial
-
-How to Build:
-Follow below steps to execute CA Client / server in different systems
-Step 1: Build Libcoap library
-Make File Location @connectivity\lib\libcoap-4.1.1
-Step 2: Build CA library
-Make File Location @connectivity\build\linux
-Step 3: Samples
-Make File Location @connectivity\samples\linux
-
-NOTE: sample.sh script can be used @connectivity\samples\linux for 3 steps together
-
-Execution:
-linux$ export LD_LIBRARY_PATH=../../build/out/
-linux$ ./out/sample_main
-
-Client Option : d, f, h Client
-Server Option : s, h
+++ /dev/null
-Project Name: IoTivity
-Release Version No: CA_v0.2
-API Version: CA_v0.4
-
-Release Description:
-Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports.
-
-Supported Platform OS:
-1) Ubuntu 12.0.4 and above:
- Connectivity : WIFI, ETHERNET
-2) Tizen 2.3
- Connectivity : WIFI, EDR, BLE(1:1).
-
-Preconditions:
-1)gcc 4.6.3 and above.
-2)glib library (sudo apt-get install libglib2.0-dev)
-3)libcoap.a library ( do make @lib/libcoap-4.1.1)
-
-
-Scope of Release:
-1. Supported APIs ( please check below APIs)
-2. Samples to test for Supported APIs.
-3. OIC Coding guidelines followed based on the current CSDK source.
-4. Multi-Threaded Connectivity abstraction.
-5. Executed Open Source Verification and Prevent analysis.
-
-The following Connectivity Abstraction API features are supported in this release:
-
-Supported APIs
-CAInitialize()
-CATerminate()
-CAStartListeningServer()
-CAStartDiscoveryServer()
-CARegisterHandler()
-CAhandleRequestResponse()
-FindResource()
-SendRequest()
-SendResponse()
-SelectNetwork()
-UnselectNetwork()
-SendNotification()
-AdvertizeResource()
-CAGenerateToken()
-CADestryToken()
-
-Non Supported APIs
-CAGetNetworkInfo()
-
-Type of Release: Source
-
-
-Known and Open Issues:
-1) OIC Log, OIC Malloc will be removed once name changes applied to OIC Bases code
-3) Termination sequence is not working.Its blocked.
-
-Nature of Release: Partial
-
-How to Build:
-Follow below steps to execute CA Client / server in different systems
-Step 1: Build Libcoap library
-Make File Location @connectivity\lib\libcoap-4.1.1
-Step 2: Build CA library
-Make File Location @connectivity\build\linux
-Step 3: Samples
-Make File Location @connectivity\samples\linux
-
-Execution:
-linux$ export LD_LIBRARY_PATH=../../build/out/
-linux$ ./out/sample_main
-
-
-Follow below sequence to test
-
-Client Option: c
-Server Option: s
-
-Client Option: f (provide a/light)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Client Option: r (provide “ServerIP:5383/a/request”)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Server Option: a
-Client Option: h (to pick server response)
-
-Server Option: b (provide ServerIP:5383/a/notify)
-Client Option: h (to pick server response)
-
-Client: Server side: n for network selection (WIFI enabled by default)
+++ /dev/null
-Project Name: IoTivity
-Release Version No: CA_v0.3
-API Version: CA_v0.5
-
-Release Description:
-Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports.
-
-Supported Platform OS:
-1) Ubuntu 12.0.4 and above:
- Connectivity : WIFI, ETHERNET
-2) Tizen 2.3
- Connectivity : WIFI, EDR, BLE(1:1).
-3) Arduino Mega
- Connectivity : WIFI, ETH
-
-Preconditions:
-1)gcc 4.6.3 and above.
-2)glib library (sudo apt-get install libglib2.0-dev)
-3)libcoap.a library ( do make @lib/libcoap-4.1.1)
-
-
-Scope of Release:
-1. Supported APIs ( please check below APIs)
-2. Samples to test for Supported APIs.
-3. OIC Coding guidelines followed based on the current CSDK source.
-4. Multi-Threaded, Single threaded Connectivity abstraction.
-5. Executed Open Source Verification and Prevent analysis.
-Type of Release: Source
-The following Connectivity Abstraction API features are supported in this release:
-
-Supported APIs
-CAInitialize()
-CATerminate()
-CAStartListeningServer()
-CAStartDiscoveryServer()
-CARegisterHandler()
-CAhandleRequestResponse()
-FindResource()
-SendRequest()
-SendResponse()
-SelectNetwork()
-UnselectNetwork()
-SendNotification()
-AdvertizeResource()
-CAGenerateToken()
-CADestryToken()
-CAGetNetworkInfo()
-
-
-Known and Open Issues:
-1) OIC Log, OIC Malloc will be removed once name changes applied to OIC Bases code.
-2) Tizen platform BLE stack is not stable. So we may see random crashes.
-
-How to Build:
-Follow below steps to execute CA Client / server in different systems
-Step 1: Build Libcoap library
-Make File Location @connectivity\lib\libcoap-4.1.1
-Step 2: Build CA library
-Make File Location @connectivity\build\linux
-Step 3: Samples
-Make File Location @connectivity\samples\linux
-
-Execution:
-linux$ export LD_LIBRARY_PATH=../../build/out/
-linux$ ./out/sample_main
-
-
-Follow below sequence to test
-
-Client Option: c
-Server Option: s
-
-Client Option: f (provide a/light)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Client Option: r (provide “ServerIP:5383/a/request”)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Server Option: a
-Client Option: h (to pick server response)
-
-Server Option: b (provide ServerIP:5383/a/notify)
-Client Option: h (to pick server response)
-
-Client: Server side: n for network selection (WIFI enabled by default)
+++ /dev/null
-Project Name: IoTivity
-Release Version No: CA_v0.4
-API Version: CA_v0.5
-
-Release Description:
-Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports.
-
-Supported Platform OS:
-1) Ubuntu 12.0.4 and above:
- Connectivity : WIFI, ETHERNET
-2) Tizen 2.3
- Connectivity : WIFI, EDR, BLE(1:1).
-3) Arduino Mega
- Connectivity : WIFI, ETH,BLE
-
-Preconditions:
-1)gcc 4.6.3 and above.
-2)glib library (sudo apt-get install libglib2.0-dev)
-3)libcoap.a library ( do make @lib/libcoap-4.1.1)
-
-
-Scope of Release:
-1. Supported APIs ( please check below APIs)
-2. Samples to test for Supported APIs.
-3. OIC Coding guidelines followed based on the current CSDK source.
-4. Multi-Threaded, Single threaded Connectivity abstraction.
-5. Executed Open Source Verification and Prevent analysis.
-Type of Release: Source
-The following Connectivity Abstraction API features are supported in this release:
-
-Supported APIs
-CAInitialize()
-CATerminate()
-CAStartListeningServer()
-CAStartDiscoveryServer()
-CARegisterHandler()
-CAhandleRequestResponse()
-FindResource()
-SendRequest()
-SendResponse()
-SelectNetwork()
-UnselectNetwork()
-SendNotification()
-AdvertizeResource()
-CAGenerateToken()
-CADestryToken()
-CAGetNetworkInfo()
-
-
-Known and Open Issues:
-1) OIC Log, OIC Malloc will be removed once name changes applied to OIC Bases code.
-2) Tizen platform BLE stack is not stable. So we may see random crashes.
-
-How to Build for Linux:
-Follow below steps to execute CA Client / server in different systems
-Step 1: Build Libcoap library
-Make File Location @connectivity\lib\libcoap-4.1.1
-Step 2: Build CA library
-Make File Location @connectivity\build\linux
-Step 3: Samples
-Make File Location @connectivity\samples\linux
-
-Execution:
-linux$ export LD_LIBRARY_PATH=../../build/out/
-linux$ ./out/sample_main
-
-
-Follow below sequence to test
-
-Client Option: c
-Server Option: s
-
-Client Option: f (provide a/light)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Client Option: r (provide “ServerIP:5383/a/request”)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Server Option: a
-Client Option: h (to pick server response)
-
-Server Option: b (provide ServerIP:5383/a/notify)
-Client Option: h (to pick server response)
-
-Client: Server side: n for network selection (WIFI enabled by default)
+++ /dev/null
-Project Name: IoTivity
-Release Version No: CA_v0.5
-API Version: CA_v0.5
-
-Release Description:
-Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports.
-
-Supported Platform OS:
-1) Ubuntu 12.0.4 and above:
- Connectivity : WIFI, ETHERNET
-2) Tizen 2.3
- Connectivity : WIFI, EDR, BLE(1:1).
-3) Arduino Mega
- Connectivity : WIFI, ETH,BLE
-4) Android 5.0
- Connectivity : WIFI, BLE
-
-Preconditions:
-1)gcc 4.6.3 and above.
-2)glib library (sudo apt-get install libglib2.0-dev)
-3)libcoap.a library ( do make @lib/libcoap-4.1.1)
-
-
-Scope of Release:
-1. Supported APIs ( please check below APIs)
-2. Samples to test for Supported APIs.
-3. OIC Coding guidelines followed based on the current CSDK source.
-4. Multi-Threaded, Single threaded Connectivity abstraction.
-5. Executed Open Source Verification and Prevent analysis.
-Type of Release: Source
-The following Connectivity Abstraction API features are supported in this release:
-
-Supported APIs
-CAInitialize()
-CATerminate()
-CAStartListeningServer()
-CAStartDiscoveryServer()
-CARegisterHandler()
-CAhandleRequestResponse()
-FindResource()
-SendRequest()
-SendResponse()
-SelectNetwork()
-UnselectNetwork()
-SendNotification()
-AdvertizeResource()
-CAGenerateToken()
-CADestryToken()
-CAGetNetworkInfo()
-
-
-Known and Open Issues:
-1) OIC Log, OIC Malloc will be removed once name changes applied to OIC Bases code.
-2) Tizen platform BLE stack is not stable. So we may see random crashes.
-
-How to Build for Linux:
-Follow below steps to execute CA Client / server in different systems
-Step 1: Build Libcoap library
-Make File Location @connectivity\lib\libcoap-4.1.1
-Step 2: Build CA library
-Make File Location @connectivity\build\linux
-Step 3: Samples
-Make File Location @connectivity\samples\linux
-
-Execution:
-linux$ export LD_LIBRARY_PATH=../../build/out/
-linux$ ./out/sample_main
-
-
-Follow below sequence to test
-
-Client Option: c
-Server Option: s
-
-Client Option: f (provide a/light)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Client Option: r (provide “ServerIP:5383/a/request”)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Server Option: a
-Client Option: h (to pick server response)
-
-Server Option: b (provide ServerIP:5383/a/notify)
-Client Option: h (to pick server response)
-
-Client: Server side: n for network selection (WIFI enabled by default)
+++ /dev/null
-Project Name: IoTivity
-Release Version No: CA_v0.6
-API Version: CA_v0.7
-
-Release Description:
-Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports.
-
-Supported Platform OS:
-1) Ubuntu 12.0.4 and above:
- Connectivity : WIFI, ETHERNET
- Security : DTLS for WIFI
-2) Tizen 2.3
- Connectivity : WIFI, EDR, BLE(1:1).
-3) Arduino Mega
- Connectivity : WIFI, ETH,BLE
-4) Android 5.0s
- Connectivity : WIFI, BLE
-
-Preconditions:
-1)gcc 4.6.3 and above.
-2)glib library (sudo apt-get install libglib2.0-dev) for linux, tizen and android devices
-3)libcoap.a library ( do make @lib/libcoap-4.1.1)
-4)tinyDTLS library for DTLS enabled applications( enable DTLS = 1 in makefile @connectivity\build/linux)
-5)Ethernet, BLE, TimedActions, Timer libraries for arduino support.
-
-Scope of Release:
-1. Supported APIs ( please check below APIs)
-2. Samples to test for Supported APIs.
-3. OIC Coding guidelines followed based on the current CSDK source.
-4. Multi-Threaded, Single threaded Connectivity abstraction.
-5. Executed Open Source Verification and Prevent analysis.
-Type of Release: Source
-The following Connectivity Abstraction API features are supported in this release:
-
-Supported APIs
-CAInitialize()
-CATerminate()
-CAStartListeningServer()
-CAStartDiscoveryServer()
-CARegisterHandler()
-CAhandleRequestResponse()
-FindResource()
-SendRequest()
-SendResponse()
-SelectNetwork()
-UnselectNetwork()
-SendNotification()
-AdvertizeResource()
-CAGenerateToken()
-CADestryToken()
-CAGetNetworkInfo()
-
-
-Known and Open Issues:
-1) OIC Log, OIC Malloc will be removed once name changes applied to OIC Bases code.
-2) Tizen platform BLE stack is not stable. So we may see random crashes.
-3) GetDtlsPskCredentials is implemented in sample which will be replace by security call during integration
-
-How to Build for Linux:
-Follow below steps to execute CA Client / server in different systems
-Step 1: Build Libcoap library
-Make File Location @connectivity\lib\libcoap-4.1.1
-Step 2: Build CA library
-Make File Location @connectivity\build\linux
-Step 3: Samples
-Make File Location @connectivity\samples\linux
-
-Execution:
-linux$ export LD_LIBRARY_PATH=../../build/out/
-linux$ ./out/sample_main
-
-
-Follow below sequence to test
-
-Client Option: c
-Server Option: s
-
-Client Option: f (provide a/light)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Client Option: r (provide “ServerIP:5383/a/request”)
-Server Option: h (will pick from queue and send response)
-Client Option: h (to pick server response)
-
-Server Option: a
-Client Option: h (to pick server response)
-
-Server Option: b (provide ServerIP:5383/a/notify)
-Client Option: h (to pick server response)
-
-Client: Server side: n for network selection (WIFI enabled by default)
-
-
-How to Build for Linux/DTLS:
-sudo ./sample.sh WITH_DTLS @@connectivity\samples\linux
#endif //OC_SECURITY_CONFIG_H
+
* port number as per specification.
* EDR will not start any specific servers.
* LE will not start any specific servers.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @return CA_STATUS_OK or CA_STATUS_FAILED
+ * ERROR CODES (CAResult_t error codes in cacommon.h)
*/
typedef CAResult_t (*CAAdapterStart)();
* port number and as per specification.
* EDR Starts RFCOMM Server with prefixed UUID as per specification.
* LE Start GATT Server with prefixed UUID and Characteristics as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @return CA_STATUS_OK or CA_STATUS_FAILED
+ * ERROR CODES (CAResult_t error codes in cacommon.h)
*/
typedef CAResult_t (*CAAdapterStartListeningServer)();
* number as per OIC Specification.
* EDR Starts RFCOMM Server with prefixed UUID as per OIC Specification.
* LE Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @return CA_STATUS_OK or CA_STATUS_FAILED
+ * ERROR CODES (CAResult_t error codes in cacommon.h)
*/
typedef CAResult_t (*CAAdapterStartDiscoveryServer)();
* reference uri and connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
*/
-typedef uint32_t (*CAAdapterSendUnitcastData)(const CARemoteEndpoint_t *endpoint, void *data,
- uint32_t dataLen);
+typedef int32_t (*CAAdapterSendUnitcastData)(const CARemoteEndpoint_t *endpoint,
+ const void *data, uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the adapter connectivity.
* Note: length must be > 0.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return - The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
*/
-typedef uint32_t (*CAAdapterSendMulticastData)(void *data, uint32_t dataLen);
+typedef int32_t (*CAAdapterSendMulticastData)(const void *data, uint32_t dataLen);
/**
* @brief Get Network Information
/**
* @brief Terminate the connectivity adapter.Configuration information will be deleted from
- * further use
+ * further use. Freeing Memory of threadpool and mutexs and cleanup will be done.
*/
typedef void (*CAAdapterTerminate)();
{
/** Start Transport specific functions*/
CAAdapterStart startAdapter;
+
/** Listening Server function address*/
CAAdapterStartListeningServer startListenServer;
+
/** Discovery Server function address **/
- CAAdapterStartDiscoveryServer startDiscoverServer;
+ CAAdapterStartDiscoveryServer startDiscoveryServer;
+
/** Unicast data function address**/
CAAdapterSendUnitcastData sendData;
+
/** Multicast data function address**/
CAAdapterSendMulticastData sendDataToAll;
+
/** Get Networking information **/
CAAdapterGetNetworkInfo GetnetInfo;
+
/** Read Data function address**/
CAAdapterReadData readData;
+
/** Stop Transport specific functions*/
CAAdapterStop stopAdapter;
+
/** Terminate function address stored in this pointer**/
CAAdapterTerminate terminate;
uint32_t dataLen);
/**
- * @brief This will be used to intimate network changes to the connectivity common logic layer
+ * @brief This will be used to notify network changes to the connectivity common logic layer
* @see SendUnitcastData(), SendMulticastData()
*/
typedef void (*CANetworkChangeCallback)(CALocalConnectivity_t *info, CANetworkStatus_t status);
#endif
#endif // __CA_ADAPTER_INTERFACE_H_
+
#include "ocsecurityconfig.h"
#include "cainterface.h"
+/**
+ * Currently DTLS supported adapters(2) WIFI and ETHENET for linux platform.
+ */
#define MAX_SUPPORTED_ADAPTERS 2
/**
*/
extern void OCGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo);
-typedef void (*CAPacketReceivedCallback)(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, const CABool_t isSecured);
+typedef void (*CAPacketReceivedCallback)(const char *ipAddress, const uint16_t port,
+ const void *data, const uint32_t dataLength, const bool isSecured);
-typedef uint32_t (*CAPacketSendCallback)(const char *ipAddress, const uint32_t port,
+typedef uint32_t (*CAPacketSendCallback)(const char *ipAddress, const uint16_t port,
const void *data, const uint32_t dataLength);
/**
/**
* @enum eDtlsAdapterType_t
- * @brief adapter types
+ * @brief This enum is used as array index for storing adapter level callbacks.
+ * So Keeping 0 instead of "1 << 0". It is not going to be used as addition
+ * and removal of adapter.
*
*/
typedef enum
*/
CAResult_t CAAdapterNetDtlsEncrypt(const char *remoteAddress,
- const uint32_t port,
- const void *data,
+ const uint16_t port,
+ void *data,
uint32_t dataLen,
uint8_t *cacheFlag,
eDtlsAdapterType_t type);
*
*/
CAResult_t CAAdapterNetDtlsDecrypt(const char *remoteAddress,
- const uint32_t port,
+ const uint16_t port,
uint8_t *data,
uint32_t dataLen,
eDtlsAdapterType_t type);
#endif //_CA_ADAPTER_NET_DTLS_H
+
#ifndef _CA_ADAPTER_UTILS_H_
#define _CA_ADAPTER_UTILS_H_
-#include <stdbool.h>
-
#include "cacommon.h"
#include "logger.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
+#include "pdu.h"
#ifdef __cplusplus
extern "C"
} \
/**
+ * @def IPV4_ADDR_ONE_OCTECT_LEN
+ * @brief Macro to allocate memory for ipv4 address in the form of uint8_t.
+ */
+#define IPV4_ADDR_ONE_OCTECT_LEN 4
+
+/**
+ * @brief To log the PDU data
+ */
+void CALogPDUData(coap_pdu_t *pdu);
+
+/**
* @fn CAAdapterCreateLocalEndpoint
* @brief Create CALocalConnectivity_t instance.
*/
* @fn CAAdapterCopyLocalEndpoint
* @brief Create CALocalConnectivity_t duplicate instance.
*/
-CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(CALocalConnectivity_t *connectivity);
+CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(const CALocalConnectivity_t *connectivity);
/**
* @fn CAAdapterFreeLocalEndpoint
void CAAdapterFreeRemoteEndpoint(CARemoteEndpoint_t *remoteEndPoint);
/**
+ * @fn CAParseIPv4AddressInternal
+ * @brief To parse the IP address and port from "ipaddress:port"
+ * @param ipAddrStr [IN] IP address to be parsed
+ * @param ipAddr [OUT] Parsed IP address
+ * @param ipAddr [IN] Buffer length for parsed IP address
+ * @param port [OUT] Parsed Port number
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
+ size_t ipAddrLen, uint16_t *port);
+
+/**
* @fn CAAdapterIsSameSubnet
* @brief Check if two ip address belong to same subnet
*/
} /* extern "C" */
#endif
#endif // _CA_ADAPTER_UTILS_H_
+
* Abstraction Layer
* @param reqRespCallback [IN] Callback to notify request and response messages from server(s)
* started at Connectivity Abstraction Layer.
- * @param netCallback [IN] Callback to intimate the network additions to Connectivity
+ * @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
* @param handle [IN] Threadpool Handle
* @return #CA_STATUS_OK or Appropriate error code
* connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data to be sent.
* @param dataLength [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Returns 0 on error.
+ * @return The number of bytes sent on the network. Returns -1 on error.
*
*/
-uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
* connectivity.
* @param data [IN] Data which needs to be sent to all discovered bluetooth OIC device.
* @param dataLength [IN] Length of data in bytes.
- * @return Number of bytes sent on the network. Returns 0 on error.
+ * @return Number of bytes sent on the network. Returns -1 on error.
*/
-uint32_t CASendEDRMulticastData(void *data, uint32_t dataLength);
+int32_t CASendEDRMulticastData(const void *data, uint32_t dataLength);
/**
* @brief Get EDR Connectivity network information.
#endif
#endif //__CA_EDRADAPTER_H_
+
* Abstraction Layer
* @param reqRespCallback [IN] Callback to notify request and response messages from server(s)
* started at Connectivity Abstraction Layer.
- * @param netCallback [IN] Callback to intimate the network additions to Connectivity
+ * @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
* @return #CA_STATUS_OK or Appropriate error code
* @retval #CA_STATUS_OK Successful
* connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data to be sent.
* @param dataLength [IN] Size of data to be sent.
- * @return Number of bytes sent on the network. Returns 0 on error.
+ * @return Number of bytes sent on the network. Returns -1 on error.
*/
-uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
* connectivity.
* @param data [IN] Data which needs to be sent to all discovered bluetooth OIC device.
* @param dataLength [IN] Length of data in bytes.
- * @return Number of bytes sent on the network. Returns 0 on error.
+ * @return Number of bytes sent on the network. Returns -1 on error.
*/
-uint32_t CASendEDRMulticastData(void *data, uint32_t dataLength);
+int32_t CASendEDRMulticastData(const void *data, uint32_t dataLength);
/**
* @brief Get EDR Connectivity network information.
#endif
#endif //__CA_EDRADAPTER_SINGLETHREAD_H_
+
{
#endif
+/**
+* @brief Set context of application
+* @param context [IN] context of application
+* @return None
+*/
void CAEDRJniSetContext(jobject context);
+/**
+* @brief Create JNI Object
+* @param context [IN] context of application
+* @return None
+*/
void CAEDRCreateJNIInterfaceObject(jobject context);
+/**
+ * @brief Initialize client for EDR
+ * @param handle [IN] thread pool handle object
+ * @return None
+ */
void CAEDRInitialize(u_thread_pool_t handle);
+/**
+ * @brief Terminate server for EDR
+ * @return None
+ */
void CAEDRTerminate();
-void CAEDRCoreJniInit(JNIEnv *env, JavaVM* jvm);
+/**
+ * @brief Initialize JNI object
+ * @param env [IN] JNI interface pointer
+ * @param jvm [IN] java virtual machine pointer
+ * @return None
+ */
+void CAEDRCoreJniInit(JNIEnv *env, JavaVM *jvm);
-int32_t CAEDRSendUnicastMessage(const char *address, const char *data, uint32_t dataLen);
+/**
+ * @brief Send data for unicast
+ * @param address [IN] remote address
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendUnicastMessage(const char *address,
+ const char *data, uint32_t dataLen);
-int32_t CAEDRSendMulticastMessage(const char *data, uint32_t dataLen);
+/**
+ * @brief Send data for multicast
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendMulticastMessage(const char *data, uint32_t dataLen);
+/**
+ * @brief Get Local EDR Address
+ * @param address [OUT] local address
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
CAResult_t CAEDRGetInterfaceInfo(char **address);
-void CAEDRGetLocalAddress(char** address);
+/**
+ * @brief Get address from a local device
+ * @param address [OUT] local address
+ * @return None
+ */
+void CAEDRGetLocalAddress(char **address);
-int32_t CAEDRSendUnicastMessageImpl(const char *address, const char *data, uint32_t dataLen);
+/**
+ * @brief Send data for unicast (implement)
+ * @param address [IN] remote address
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendUnicastMessageImpl(const char *address,
+ const char *data, uint32_t dataLen);
-int32_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const char *data, uint32_t dataLen);
+/**
+ * @brief Send data for multicast (implement)
+ * @param env [IN] JNI interface pointer
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const char *data, uint32_t dataLen);
/**
* EDR Method
*/
-void CAEDRNativeSendData(JNIEnv *env, const char* address, const char* data, uint32_t id);
-void CAEDRNativeConnect(JNIEnv *env, const char* address, uint32_t id);
+/**
+ * @brief This function will send the data to remote device.
+ * @param env [IN] JNI interface pointer
+ * @param address [IN] Remote Address
+ * @param data [IN] Data to be transmitted from EDR
+ * @param id [IN] index of remote address
+ * @return None
+ */
+void CAEDRNativeSendData(JNIEnv *env, const char *address, const char *data, uint32_t id);
+
+/**
+ * @brief This function will connect to remote device.
+ * @param env [IN] JNI interface pointer
+ * @param address [IN] Remote Address
+ * @param id [IN] index of remote address
+ * @return None
+ */
+void CAEDRNativeConnect(JNIEnv *env, const char *address, uint32_t id);
-void CAEDRNativeSocketClose(JNIEnv *env, const char* address, uint32_t id);
+/**
+ * @brief This function will close socket.
+ * @param env [IN] JNI interface pointer
+ * @param address [IN] Remote Address
+ * @param id [IN] index of remote address
+ * @return None
+ */
+void CAEDRNativeSocketClose(JNIEnv *env, const char *address, uint32_t id);
/**
* BT State List
*/
+
+/**
+ * @brief This function will create the device state list.
+ * @return None
+ */
void CAEDRNativeCreateDeviceStateList();
-void CAEDRUpdateDeviceState(uint32_t state, const char* address);
+/**
+ * @brief Update connection state of device
+ * @param state [IN] connection state
+ * @param address [IN] remote address
+ * @return None
+ */
+void CAEDRUpdateDeviceState(CAConnectedState_t state, const char *address);
-void CAEDRNativeAddDeviceStateToList(state_t* state);
+/**
+ * @brief Add device object to the list
+ * @param state [IN] connection state object
+ * @return None
+ */
+void CAEDRNativeAddDeviceStateToList(state_t *state);
+/**
+ * @brief Check whether the device exist in the list or not
+ * @param remoteAddress [IN] remote address
+ * @return TRUE or FALSE
+ */
jboolean CAEDRNativeIsDeviceInList(const char *remoteAddress);
+/**
+ * @brief Remove all device objects in the list
+ * @return None
+ */
void CAEDRNativeRemoveAllDeviceState();
-void CAEDRNativeRemoveDevice(const char* remoteAddress);
+/**
+ * @brief Remove target device in the list
+ * @param remoteAddress [IN] remote address
+ * @return None
+ */
+void CAEDRNativeRemoveDevice(const char *remoteAddress);
-jboolean CAEDRIsConnectedDevice(const char* remoteAddress);
+/**
+ * @brief Get current device connection state
+ * @param remoteAddress [IN] remote address
+ * @return STATE_DISCONNECTED or STATE_CONNECTED
+ */
+CAConnectedState_t CAEDRIsConnectedDevice(const char *remoteAddress);
+/**
+ * @brief Reordering for the list
+ * @param index [IN] index of device list that want to reordering
+ * @return None
+ */
void CAEDRReorderingDeviceList(uint32_t index);
/**
* Bluetooth Socket Object List
*/
+
+/**
+ * @brief This function will create the device socket list.
+ * @return None
+ */
void CAEDRNativeCreateDeviceSocketList();
+/**
+ * @brief Add device object to the list
+ * @param env [IN] JNI interface pointer
+ * @param deviceSocket [IN] device socket object
+ * @return None
+ */
void CAEDRNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket);
+/**
+ * @brief Add device object to the list
+ * @param env [IN] JNI interface pointer
+ * @param remoteAddress [IN] remote address
+ * @return TRUE or FALSE
+ */
jboolean CAEDRNativeIsDeviceSocketInList(JNIEnv *env, const char *remoteAddress);
+/**
+ * @brief Add device object to the list
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CAEDRNativeRemoveAllDeviceSocket(JNIEnv *env);
+/**
+ * @brief Add device object to the list
+ * @param env [IN] JNI interface pointer
+ * @param deviceSocket [IN] device socket object
+ * @return None
+ */
void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket);
+/**
+ * @brief Get device socket object from the list
+ * @param idx [IN] index of device list
+ * @return Device socket object or NULL
+ */
jobject CAEDRNativeGetDeviceSocket(uint32_t idx);
+/**
+ * @brief Get length of device socket list
+ * @return length of list
+ */
uint32_t CAEDRGetSocketListLength();
+/**
+ * @brief Reordering for the list
+ * @param index [IN] index of device list that want to reordering
+ * @return None
+ */
void CAEDRReorderingDeviceSocketList(uint32_t index);
-
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
+
#ifndef __CA_EDR_INTERFACE_H_
#define __CA_EDR_INTERFACE_H_
-#include <string.h>
#include "caedradapter.h"
#ifdef __cplusplus
#define OIC_EDR_SERVICE_ID "12341234-1C25-481F-9DFB-59193D238280"
#endif //OIC_EDR_SERVICE_ID
+typedef enum
+{
+ STATE_DISCONNECTED, /**< State is Disconnected */
+ STATE_CONNECTED /**< State is Connected */
+} CAConnectedState_t;
typedef struct connected_state {
- char address[CA_MACADDR_SIZE];
- uint32_t state;
+ uint8_t address[CA_MACADDR_SIZE];
+ CAConnectedState_t state;
} state_t;
/**
/**
* @brief This will be used during the recive of network requests and response.
- * @param remoteAddress [IN] EDR address of remote OIC device
+ * @param remoteAddress [IN] EDR address of remote OIC device from which data received.
* @param data [IN] Data received
* @param dataLength [IN] Length of the Data received
- * @param sentLength [IN] Length of the sent data
+ * @param sentLength [OUT] Length of the sent data
* @return NONE
* @pre Callback must be registered using CAEDRSetPacketReceivedCallback()
*/
-typedef void (*CAEDRDataReceivedCallback)(const char *remoteAddress, void *data, uint32_t dataLength,
- uint32_t *sentLength);
+typedef void (*CAEDRDataReceivedCallback)(const char *remoteAddress,
+ const void *data, uint32_t dataLength, uint32_t *sentLength);
/**
* @brief This will be used during change in network status.
* @brief Destroys the Device list and mutex.
* @return NONE
*/
-void CAEDRTerminateClient();
+void CAEDRClientTerminate();
/**
* @brief Closes all the client connection to peer bluetooth devices.
* @retval #CA_STATUS_FAILED Operation failed
*
*/
-CAResult_t CAEDRServerStart(const char *serviceUUID, int32_t *serverFD, u_thread_pool_t handle);
+CAResult_t CAEDRServerStart(const char *serviceUUID, int *serverFD, u_thread_pool_t handle);
/**
* @brief Stop RFCOMM server
* @retval #CA_STATUS_OK Successful
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAEDRServerStop(const int32_t serverFD);
+CAResult_t CAEDRServerStop(int serverFD);
+
+/**
+ * @brief Terminate server for EDR
+ * @return None
+ */
+void CAEDRServerTerminate();
/**
* @brief All received data will be notified to upper layer.
* @param state [OUT] State of the Adapter.
* @return #CA_STATUS_OK or Appropriate error code
*/
-CAResult_t CAEDRGetAdapterEnableState(CABool_t *state);
+CAResult_t CAEDRGetAdapterEnableState(bool *state);
/**
* @brief This function sends data to specified remote bluetooth device.
* @param serviceUUID [IN] Service UUID of the device
* @param data [IN] Data to be sent
* @param dataLength [IN] Length of the data to be sent
- * @param sentLength [IN] Length of the actual sent data
+ * @param sentLength [OUT] Length of the actual sent data
* @return #CA_STATUS_OK or Appropriate error code
*/
CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength);
+ const void *data, uint32_t dataLength, uint32_t *sentLength);
/**
* @brief This function sends data to all bluetooth devices running OIC service.
* @param serviceUUID [IN] Service UUID of the device
* @param data [IN] Data to be sent
* @param dataLength [IN] Length of the data to be sent
- * @param sentLength [IN] Length of the actual sent data
+ * @param sentLength [OUT] Length of the actual sent data
* @return #CA_STATUS_OK or Appropriate error code
*/
-CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, void *data,
+CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, const void *data,
uint32_t dataLength, uint32_t *sentLength);
#ifdef __cplusplus
#endif //__CA_EDR_INTERFACE_H_
+
typedef void (*CAPacketReceiveCallback)(const char *address, const char *data);
-//getting jvm
+/**
+ * @brief Initialize JNI object
+ * @param env [IN] JNI interface pointer
+ * @param jvm [IN] java virtual machine pointer
+ * @return None
+ */
void CAEDRServerJniInit(JNIEnv *env, JavaVM *jvm);
+/**
+ * @brief Initialize server for EDR
+ * @param handle [IN] thread pool handle object
+ * @return None
+ */
void CAEDRServerInitialize(u_thread_pool_t handle);
-void CAEDRServerTerminate();
-
+/**
+ * @brief Start unicast server
+ * @param address [IN] remote address
+ * @param isSecured [IN] unicast server type
+ * @return Returns -1 on error and 0 on success
+ */
int32_t CAEDRStartUnicastServer(const char *address, bool isSecured);
+/**
+ * @brief Start multicast server
+ * @param isSecured [IN] multicst server type
+ * @return Returns -1 on error and 0 on success
+ */
int32_t CAEDRStartMulticastServer(bool isSecured);
+/**
+ * @brief Stop unicast server
+ * @param serverID [IN] unicast server id
+ * @return Returns -1 on error and 0 on success
+ */
int32_t CAEDRStopUnicastServer(int32_t serverID);
+/**
+ * @brief Stop multicast server
+ * @param serverID [IN] multicast server id
+ * @return Returns -1 on error and 0 on success
+ */
int32_t CAEDRStopMulticastServer(int32_t serverID);
/**
* EDR Method
*/
-uint32_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t type);
+/**
+ * @brief This function will read the data from remote device.
+ * @param env [IN] JNI interface pointer
+ * @param id [IN] index of remote address
+ * @param type [IN] EDR server type
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t type);
+
+/**
+ * @brief This function will listen the connection from remote device.
+ * @param env [IN] JNI interface pointer
+ * @return server socket object or NULL
+ */
jobject CAEDRNativeListen(JNIEnv *env);
+/**
+ * @brief This function will accept the connection from remote device.
+ * @param env [IN] JNI interface pointer
+ * @param severSocketObject [IN] server socket object
+ * @return None
+ */
void CAEDRNativeAccept(JNIEnv *env, jobject severSocketObject);
-void CAEDRNativeServerSocketClose(JNIEnv *env, const char* address, uint32_t id);
+/**
+ * @brief This function will accept the connection from remote device.
+ * @param env [IN] JNI interface pointer
+ * @param address [IN] remote address
+ * @param id [IN] index of remote address
+ * @return None
+ */
+void CAEDRNativeServerSocketClose(JNIEnv *env, const char *address, uint32_t id);
/**
* BT State List
*/
+
+/**
+ * @brief This function will create the device state list.
+ * @return None
+ */
void CAEDRServerNativeCreateDeviceStateList();
-void CAEDRServerUpdateDeviceState(uint32_t state, const char* address);
+/**
+ * @brief Update connection state of device
+ * @param state [IN] connection state
+ * @param address [IN] remote address
+ * @return None
+ */
+void CAEDRServerUpdateDeviceState(uint32_t state, const char *address);
-void CAEDRServerNativeAddDeviceStateToList(state_t* state);
+/**
+ * @brief Add device object to the list
+ * @param state [IN] connection state object
+ * @return None
+ */
+void CAEDRServerNativeAddDeviceStateToList(state_t *state);
+/**
+ * @brief Check whether the device exist in the list or not
+ * @param remoteAddress [IN] remote address
+ * @return TRUE or FALSE
+ */
jboolean CAEDRServerNativeIsDeviceInList(const char *remoteAddress);
+/**
+ * @brief Remove all device objects in the list
+ * @return None
+ */
void CAEDRServerNativeRemoveAllDeviceState();
-void CAEDRServerNativeRemoveDevice(const char* remoteAddress);
+/**
+ * @brief Remove target device in the list
+ * @param remoteAddress [IN] remote address
+ * @return None
+ */
+void CAEDRServerNativeRemoveDevice(const char *remoteAddress);
-jboolean CAEDRServerIsConnectedDevice(const char* remoteAddress);
+/**
+ * @brief Check whether the state is connected or disconnected
+ * @param remoteAddress [IN] remote address
+ * @return TRUE or FALSE
+ */
+jboolean CAEDRServerIsConnectedDevice(const char *remoteAddress);
+/**
+ * @brief Reordering for the list
+ * @param index [IN] index of device list that want to reordering
+ * @return None
+ */
void CAEDRServerReorderingDeviceList(uint32_t index);
/**
* Bluetooth Socket Object List
*/
+
+/**
+ * @brief This function will create the device socket list.
+ * @return None
+ */
void CAEDRServerNativeCreateDeviceSocketList();
+/**
+ * @brief Add device object to the list
+ * @param env [IN] JNI interface pointer
+ * @param deviceSocket [IN] device socket object
+ * @return None
+ */
void CAEDRServerNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket);
+/**
+ * @brief Add device object to the list
+ * @param env [IN] JNI interface pointer
+ * @param remoteAddress [IN] remote address
+ * @return TRUE or FALSE
+ */
jboolean CAEDRServerNativeIsDeviceSocketInList(JNIEnv *env, const char *remoteAddress);
+/**
+ * @brief Add device object to the list
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CAEDRServerNativeRemoveAllDeviceSocket(JNIEnv *env);
+/**
+ * @brief Add device object to the list
+ * @param env [IN] JNI interface pointer
+ * @param deviceSocket [IN] device socket object
+ * @return None
+ */
void CAEDRServerNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket);
+/**
+ * @brief Get device socket object from the list
+ * @param idx [IN] index of device list
+ * @return Device socket object or NULL
+ */
jobject CAEDRServerNativeGetDeviceSocket(uint32_t idx);
+/**
+ * @brief Get length of device socket list
+ * @return length of list
+ */
uint32_t CAEDRServerGetSocketListLength();
+/**
+ * @brief Reordering for the list
+ * @param index [IN] index of device list that want to reordering
+ * @return None
+ */
void CAEDRServerReorderingDeviceSocketList(uint32_t index);
#endif
#endif
+
#include "cacommon.h"
#include "caadapterinterface.h"
-#include "uthreadpool.h" /* for thread pool */
+#include "uthreadpool.h"
#ifdef __cplusplus
extern "C"
* Abstraction Layer
* @param networkPacketCallback [IN] Callback to notify request and response messages from server(s)
* started at Connectivity Abstraction Layer.
- * @param netCallback [IN] Callback to intimate the network additions to Connectivity
+ * @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
* @param handle [IN] Threadpool Handle
* @return #CA_STATUS_OK or Appropriate error code
* reference uri and connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data which is required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *endpoint, void *data,
+int32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the Ethernet connectivity.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendEthernetMulticastData(void *data, uint32_t dataLen);
+int32_t CASendEthernetMulticastData(const void *data, uint32_t dataLen);
/**
* @brief Get Ethernet Connectivity network information
#endif
#endif // #ifndef __CA_ETHERNET_ADAPTER_H__
+
* Abstraction Layer
* @param networkPacketCallback [IN] Callback to notify request and response messages from server(s)
* started at Connectivity Abstraction Layer.
- * @param netCallback [IN] Callback to intimate the network additions to Connectivity
+ * @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
* @return #CA_STATUS_OK or Appropriate error code
*/
* reference uri and connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
* @remark dataLen must be > 0.
*/
-uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *endpoint, void *data,
- uint32_t dataLen);
+int32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+ uint32_t dataLen);
/**
* @brief Send Multicast data to the endpoint using the Ethernet connectivity.
* @param data [IN] Data which is required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Return value equal to zero indicates error.
+ * @return The number of bytes sent on the network. Return value equal to -1 indicates error.
* @remark dataLen must be > 0.
*/
-uint32_t CASendEthernetMulticastData(void *data, uint32_t dataLen);
+int32_t CASendEthernetMulticastData(const void *data, uint32_t dataLen);
/**
* @brief Get Ethernet Connectivity network information
#endif
#endif // #ifndef __CA_ETHERNET_ADAPTER_SINGLETHREAD_H__
+
* @return NONE
* @pre Callback must be registered using CAEthernetSetPacketReceiveCallback()
*/
-typedef void (*CAEthernetPacketReceivedCallback)(const char *ipAddress, const uint32_t port,
+typedef void (*CAEthernetPacketReceivedCallback)(const char *ipAddress, const uint16_t port,
const void *data, const uint32_t dataLength,
- const CABool_t isSecured);
+ const bool isSecured);
/**
* @brief Callback to be notified when exception occures on multicast/unicast server.
* @retval #CA_SERVER_STARTED_ALREADY Multicast server is already started and running.
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAEthernetStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD);
+CAResult_t CAEthernetStartMulticastServer(const char *localAddress,
+ const char *multicastAddress, const uint16_t multicastPort, int32_t *serverFD);
/**
* @brief Start unicast server for specified local address and port
* @retval #CA_SERVER_STARTED_ALREADY Unicast server is already started and running.
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAEthernetStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, const bool secured, int32_t *serverFD);
+CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port,
+ bool forceStart, bool secured, int32_t *serverFD);
/**
* @brief Stop multicast server.
* @retval #CA_STATUS_FAILED Operation failed
* @remarks ipAddress must be freed using free().
*/
-CAResult_t CAEthernetGetUnicastServerInfo(const bool secure, char **ipAddress, int16_t *port,
- int32_t *serverFD);
+CAResult_t CAEthernetGetUnicastServerInfo(bool secure, char **ipAddress,
+ uint16_t *port,int32_t *serverFD);
/**
* @brief Set this callback for receiving data packets from peer devices.
* @param port [IN] Port number used for sending UDP data.
* @return NONE
*/
-void CAEthernetSetUnicastPort(const int32_t port);
+void CAEthernetSetUnicastPort(const uint16_t port);
#ifdef __WITH_DTLS__
/**
* @return The number of bytes sent on the network. Returns 0 on error.
* @remarks isSecure will be ignored when isMulticast is true.
*/
-uint32_t CAEthernetSendData(const char *remoteAddress, const uint32_t port,
+uint32_t CAEthernetSendData(const char *remoteAddress, const uint16_t port,
const void *data, const uint32_t dataLength,
- CABool_t isMulticast, CABool_t isSecure);
+ bool isMulticast, bool isSecure);
/**
* @brief Callback to be notified when Ethernet adapter connection state changes.
* @param callback [IN] Callback to be notified when local Ethernet adapter connection state changes.
* @return NONE
*/
-void CAEthernetSetConnectionStateChangeCallback(CAEthernetConnectionStateChangeCallback callback);
+void CAEthernetSetConnectionStateChangeCallback
+ (CAEthernetConnectionStateChangeCallback callback);
#ifdef __cplusplus
}
#endif
#endif //_CA_ETHERNET_INTERFACE_H_
+
* @return NONE
* @pre Callback must be registered using CAEthernetSetPacketReceiveCallback()
*/
-typedef void (*CAEthernetPacketReceivedCallback)(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength);
+typedef void (*CAEthernetPacketReceivedCallback)(const char *ipAddress, uint32_t port,
+ const void *data, uint32_t dataLength);
/**
* @brief Callback to be notified when exception occures on multicast/unicast server.
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAEthernetStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD);
+ uint16_t multicastPort, int *serverFD);
/**
* @brief Start unicast server for specified local address and port
* @retval #CA_SERVER_STARTED_ALREADY Unicast server is already started and running.
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAEthernetStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, int32_t *serverFD);
+CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port,
+ bool forceStart, int *serverFD);
/**
* @brief Stop multicast server.
* @retval #CA_STATUS_FAILED Operation failed
* @remarks ipAddress must be freed using free().
*/
-CAResult_t CAEthernetGetUnicastServerInfo(char **ipAddress, int16_t *port, int32_t *serverFD);
+CAResult_t CAEthernetGetUnicastServerInfo(char **ipAddress, int16_t *port, int *serverFD);
/**
* @brief Set this callback for receiving data packets from peer devices.
* @param socketFD [IN] Socket descriptor used for sending UDP data.
* @return NONE
*/
-void CAEthernetSetUnicastSocket(const int32_t socketFD);
+void CAEthernetSetUnicastSocket(int socketFD);
/**
* @brief Set the port number for sending unicast UDP data
* @param port [IN] Port number used for sending UDP data.
* @return NONE
*/
-void CAEthernetSetUnicastPort(const int16_t port);
+void CAEthernetSetUnicastPort(uint16_t port);
/**
* @brief Set socket description for sending secured (encrypted) unicast UDP data
* @param socketFD [IN] Socket descriptor used for sending secured (encrypted) UDP data.
* @return NONE
*/
-void CAEthernetSetSecureUnicastSocket(const int32_t socketFD);
+void CAEthernetSetSecureUnicastSocket(int socketFD);
/**
* @brief API to send unicast UDP data
*
* @return The number of bytes sent on the network. Returns 0 on error.
*/
-uint32_t CAEthernetSendData(const char *remoteAddress, const int16_t port,
- const char *buf, const uint32_t bufLen, bool isMulticast);
+uint32_t CAEthernetSendData(const char *remoteAddress, uint16_t port,
+ const char *buf, uint32_t bufLen, bool isMulticast);
/**
* @brief Callback to be notified when ethernet adapter connection state changes.
* @pre Callback must be registered using CAEthernetSetConnectionStateChangeCallback()
*/
typedef void (*CAEthernetConnectionStateChangeCallback)(const char *ipAddress,
- const CANetworkStatus_t status);
+ CANetworkStatus_t status);
/**
* @brief Initialize Ethernet network monitor
* changes.
* @return NONE
*/
-void CAEthernetSetConnectionStateChangeCallback(CAEthernetConnectionStateChangeCallback callback);
+void CAEthernetSetConnectionStateChangeCallback
+ (CAEthernetConnectionStateChangeCallback callback);
#ifdef __cplusplus
}
#endif
#endif //_CA_ETHERNET_INTERFACE_SINGLETHREAD_H_
+
/**
* @brief Initializes different adapters based on the compilation flags.
- * @param handle [IN] thread pool handle created by message handler for different adapters.
+ * @param handle [IN] thread pool handle created by message handler for different adapters.
* @return none
*/
void CAInitializeAdapters(u_thread_pool_t handle);
/**
* @brief Starting different connectivity adapters based on the network selection.
- * @param connectivity [IN] interested network for starting
+ * @param connectivity [IN] network type that want to start
* @return none
*/
-void CAStartAdapter(CAConnectivityType_t connectivity);
+CAResult_t CAStartAdapter(CAConnectivityType_t connectivity);
/**
* @brief Stopping different connectivity adapters based on the network un-selection.
- * @param callback [IN] un selected network for stopping the packets transfer
+ * @param connectivity [IN] network type that want to stop
* @return none
*/
void CAStopAdapter(CAConnectivityType_t connectivity);
/**
* @brief Get network information such as ipaddress and mac information
- * @param info [OUT] connectivity information such as ipaddress and mac information
- * @param size [OUT] number of connectivity information structures
+ * @param info [OUT] connectivity information such as ipaddress and mac information
+ * @param size [OUT] number of connectivity information structures
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size);
/**
* @brief Sends unicast data to the remote endpoint
* @param endpoint [IN] endpoint information where the data has to be sent
- * @param data [IN] data that needs to be sent
- * @param length [IN] length of the data that needs to be sent
+ * @param data [IN] data that needs to be sent
+ * @param length [IN] length of the data that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t length);
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length);
/**
* @brief Sends multicast data to all endpoints in the network.
- * @param data [IN] data that needs to be sent
- * @param length [IN] length of the data that needs to be sent
+ * @param data [IN] data that needs to be sent
+ * @param length [IN] length of the data that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CASendMulticastData(void *data, uint32_t length);
+CAResult_t CASendMulticastData(const void *data, uint32_t length);
/**
* @brief Start listening servers to receive search requests from clients
#endif
#endif //#ifndef __CA_INTERFACE_CONTROLLER_H_
+
/**
* @brief Initializes different adapters based on the compilation flags.
- * @param handle [IN] thread pool handle created by message handler for different adapters.
+ * @param handle [IN] thread pool handle created by message handler for different
+ * adapters.
* @return none
*/
void CAInitializeAdapters();
/**
* @brief Set the received packets callback for message handler
- * @param callback [IN] message handler callback to receive packets from different adapters.
+ * @param callback [IN] message handler callback to receive packets from different
+ * adapters.
* @return none
*/
void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback);
/**
* @brief Set the network status changed callback for message handler
- * @param callback [IN] message handler network status callback to receive network changes.
+ * @param callback [IN] message handler network status callback to receive network
+ * changes.
* @return none
*/
void CASetNetworkChangeCallback(CANetworkChangeCallback callback);
/**
* @brief Starting different connectivity adapters based on the network selection.
- * @param connectivity [IN] interested network for starting
+ * @param connectivity [IN] network type that want to stop
* @return none
*/
-void CAStartAdapter(CAConnectivityType_t connectivity);
+CAResult_t CAStartAdapter(CAConnectivityType_t connectivity);
/**
* @brief Stopping different connectivity adapters based on the network un-selection.
- * @param callback [IN] un selected network for stopping the packets transfer
+ * @param connectivity [IN] un selected network for stopping the packets transfer
* @return none
*/
void CAStopAdapter(CAConnectivityType_t connectivity);
/**
- * @brief Get network information such as ipaddress and mac information
- * @param info [OUT] connectivity information such as ipaddress and mac information
- * @param size [OUT] number of connectivity information structures
+ * @brief Get network information such as ipaddress and mac information. Gets the network
+ * information of the adapter whichever is enabled. Otherwise info is NULL.
+ * @param info [OUT] connectivity information such as ipaddress and mac information
+ * @param size [OUT] number of connectivity information structures
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size);
/**
* @brief Sends unicast data to the remote endpoint
- * @param endpoint [IN] endpoint information where the data has to be sent
- * @param data [IN] data that needs to be sent
- * @param length [IN] length of the data that needs to be sent
+ * @param endpoint [IN] endpoint information where the data has to be sent
+ * @param data [IN] data that needs to be sent
+ * @param length [IN] length of the data that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t length);
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length);
/**
* @brief Sends multicast data to all endpoints in the network.
- * @param data [IN] data that needs to be sent
- * @param length [IN] length of the data that needs to be sent
+ * @param data [IN] data that needs to be sent
+ * @param length [IN] length of the data that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CASendMulticastData(void *data, uint32_t length);
+CAResult_t CASendMulticastData(const void *data, uint32_t length);
/**
* @brief Start listening servers to receive search requests from clients
#endif
#endif //#ifndef __CA_INTERFACE_CONTROLLER_H_
+
#endif
/**
- * @struct CABLEData
+ * @struct CALEData_t
* @brief Stores the information of the Data to be sent from the queues.
* This structure will be pushed to the sender/receiver queue for processing.
*/
*remoteEndpoint; /**< Remote endpoint contains the inforamtion of remote device */
void *data; /**< Data to be transmitted over LE tranport */
uint32_t dataLen; /**< Length of the data being transmitted */
-} CABLEData;
+} CALEData_t;
/**
* @brief Initialize LE connectivity interface.
* Abstraction Layer
* @param reqRespCallback [IN] Callback to notify request and response messages from server(s)
* started at Connectivity Abstraction Layer.
- * @param netCallback [IN] Callback to intimate the network additions to Connectivity
+ * @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
* @param handle [IN] Threadpool Handle
* @return #CA_STATUS_OK or Appropriate error code
* and connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Returns 0 on error.
+ * @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, void *data,
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the LE connectivity.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Returns 0 on error.
+ * @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendLEMulticastData(void *data, uint32_t dataLen);
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen);
/**
* @brief Starts notification server on EDR adapters.
* @return The number of bytes sent on the network. Returns 0 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, void *data,
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
*
*/
CAResult_t CABLEServerReceivedData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength);
+ const void *data, uint32_t dataLength, uint32_t *sentLength);
/**
* @brief This function will receive the data from the GattClient and add the data into the
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABLEClientReceivedData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength);
+ const void *data, uint32_t dataLength, uint32_t *sentLength);
/**
* @brief This function is used to set the NetworkPacket received callback to CA layer from
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
- void *data, uint32_t dataLen);
+ const void *data, uint32_t dataLen);
/**
* @brief This function will push the data from CA layer to the Sender processor queue.
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
- void *data, uint32_t dataLen);
+ const void *data, uint32_t dataLen);
/**
* @brief This function will be associated with the sender queue for GattServer.This function will
CAResult_t CAInitBleClientQueues();
/**
- * @brief This function will initalize the Receiver queue for GattServer. This will initlialize
+ * @brief This function will initalize the Receiver queue for GattServer. This will initialize
* the queue to process the function CABLEServerSendDataThread() when ever the task is
* added to this queue.
*
CAResult_t CAInitBleServerSenderQueue();
/**
- * @brief This function will initalize the Receiver queue for GattClient. This will initlialize
+ * @brief This function will initalize the Receiver queue for GattClient. This will initialize
* the queue to process the function CABLEClientSendDataThread() when ever the task is
* added to this queue.
*
CAResult_t CAInitBleClientSenderQueue();
/**
- * @brief This function will initalize the Receiver queue for GattServer. This will initlialize
+ * @brief This function will initalize the Receiver queue for GattServer. This will initialize
* the queue to process the function CABLEServerDataReceiverHandler() when ever the task
* is added to this queue.
*
CAResult_t CAInitBleServerReceiverQueue();
/**
- * @brief This function will initalize the Receiver queue for GattClient. This will initlialize
+ * @brief This function will initalize the Receiver queue for GattClient. This will initialize
* the queue to process the function CABLEClientDataReceiverHandler() when ever the task
* is added to this queue.
*
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CABLEData *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
* @param bleData [IN] Structure contains the information of a particular data segment.
* @return NONE
*/
-void CAFreeBLEData(CABLEData *bleData);
+void CAFreeBLEData(CALEData_t *bleData);
/**
- * @brief This will be used to intimate device status changes to the LE adapter layer
+ * @brief This will be used to notify device status changes to the LE adapter layer
* @param adapter_state [IN] State of the adapter
* @return NONE
*/
typedef void (*CALEDeviceStateChangedCallback)(CAAdapterState_t adapter_state);
/**
- * @brief This will be used to intimate network packet recieved from GATTClient to adapter layer.
+ * @brief This will be used to notify that network packet recieved from GATTClient to adapter layer.
* @param remoteAddress [IN] Remote endpoint Address
* @param serviceUUID [IN] Service UUID
* @param data [IN] Data received
* @retval #CA_STATUS_FAILED Operation failed
*/
typedef CAResult_t (*CABLEClientDataReceivedCallback)(const char *remoteAddress,
- const char *serviceUUID, void *data,
+ const char *serviceUUID, const void *data,
uint32_t dataLength, uint32_t *sentLength);
/**
- * @brief This will be used to intimate network packet recieved from GATTServer to adapter layer.
+ * @brief This will be used to notify that network packet recieved from GATTServer to adapter layer.
* @param remoteAddress [IN] Remote endpoint Address
* @param serviceUUID [IN] Service UUID
* @param data [IN] Data received
* @retval #CA_STATUS_FAILED Operation failed
*/
typedef CAResult_t (*CABLEServerDataReceivedCallback)(const char *remoteAddress,
- const char *serviceUUID, void *data,
+ const char *serviceUUID, const void *data,
uint32_t dataLength, uint32_t *sentLength);
#ifdef __cplusplus
#endif
#endif //#ifndef _CA_LEADAPTER_H_
+
#endif
/**
- * @struct CABLEData
+ * @struct CALEData_t
* @brief Stores the information of the Data to be sent from the queues.
* This structure will be pushed to the sender/receiver queue for processing.
*/
*remoteEndpoint; /**< Remote endpoint contains the inforamtion of remote device */
void *data; /**< Data to be transmitted over LE tranport */
uint32_t dataLen; /**< Length of the data being transmitted */
-} CABLEData;
+} CALEData_t;
/**
* @brief Initialize LE connectivity interface.
* @param registerCallback [IN] Callback to register LE interfaces to Connectivity Abstraction Layer
* @param reqRespCallback [IN] Callback to notify request and response messages from server(s)
* started at Connectivity Abstraction Layer.
- * @param netCallback [IN] Callback to intimate the network additions to Connectivity
+ * @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
* @return #CA_STATUS_OK or Appropriate error code
*/
* and connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Returns 0 on error.
+ * @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, void *data,
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the LE connectivity.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Returns 0 on error.
+ * @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendLEMulticastData(void *data, uint32_t dataLen);
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen);
/**
* @brief Starts notification server on EDR adapters.
* @return The number of bytes sent on the network. Returns 0 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, void *data,
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABLEServerReceivedData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength);
+ const void *data, uint32_t dataLength, uint32_t *sentLength);
/**
* @brief This function will receive the data from the GattClient and add the data into the
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABLEClientReceivedData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength);
+ const void *data, uint32_t dataLength, uint32_t *sentLength);
/**
* @brief This function is used to set the NetworkPacket received callback to CA layer from
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
- void *data, uint32_t dataLen);
+ const void *data, uint32_t dataLen);
/**
* @brief This function will push the data from CA layer to the Sender processor queue.
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
- void *data, uint32_t dataLen);
+ const void *data, uint32_t dataLen);
/**
* @brief This function will be associated with the sender queue for GattClient.This function will
void CATerminateBleQueues();
/**
- * @brief This function will initalize the Receiver queue for GattClient. This will initlialize
+ * @brief This function will initalize the Receiver queue for GattClient. This will initialize
* the queue to process the function CABLEClientDataReceiverHandler() when ever the task
* is added to this queue.
*
CAResult_t CAInitBleClientReceiverQueue();
/**
- * @brief This function will initalize the Receiver queue for GattServer. This will initlialize
+ * @brief This function will initalize the Receiver queue for GattServer. This will initialize
* the queue to process the function CABLEServerDataReceiverHandler() when ever the task
* is added to this queue.
*
CAResult_t CAInitBleClientQueues();
/**
- * @brief This function will initalize the Receiver queue for GattServer. This will initlialize
+ * @brief This function will initalize the Receiver queue for GattServer. This will initialize
* the queue to process the function CABLEServerSendDataThread() when ever the task is
* added to this queue.
*
CAResult_t CAInitBleServerSenderQueue();
/**
- * @brief This function will initalize the Receiver queue for GattClient. This will initlialize
+ * @brief This function will initalize the Receiver queue for GattClient. This will initialize
* the queue to process the function CABLEClientSendDataThread() when ever the task is
* added to this queue.
*
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CABLEData *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
* @param bleData [IN] Structure contains the information of a particular data segment.
* @return NONE
*/
-void CAFreeBLEData(CABLEData *bleData);
+void CAFreeBLEData(CALEData_t *bleData);
/**
- * @brief This will be used to intimate device status changes to the LE adapter layer
+ * @brief This will be used to notify the device status changes to the LE adapter layer
* @param adapter_state [IN] State of the adapter
* @return NONE
*/
typedef void (*CALEDeviceStateChangedCallback)(CAAdapterState_t adapter_state);
/**
- * @brief This will be used to intimate network packet recieved from GATTClient to adapter layer.
+ * @brief This will be used to notify that network packet recieved from GATTClient to adapter layer.
* @param remoteAddress [IN] Remote endpoint Address
* @param serviceUUID [IN] Service UUID
* @param data [IN] Data received
* @retval #CA_STATUS_FAILED Operation failed
*/
typedef CAResult_t (*CABLEClientDataReceivedCallback)(const char *remoteAddress,
- const char *serviceUUID, void *data, uint32_t dataLength, uint32_t *sentLength);
+ const char *serviceUUID, const void *data, uint32_t dataLength, uint32_t *sentLength);
/**
- * @brief This will be used to intimate network packet recieved from GATTServer to adapter layer.
+ * @brief This will be used to notify that network packet recieved from GATTServer to adapter layer.
* @param remoteAddress [IN] Remote endpoint Address
* @param serviceUUID [IN] Service UUID
* @param data [IN] Data received
* @retval #CA_STATUS_FAILED Operation failed
*/
typedef CAResult_t (*CABLEServerDataReceivedCallback)(const char *remoteAddress,
- const char *serviceUUID, void *data, uint32_t dataLength, uint32_t *sentLength);
+ const char *serviceUUID, const void *data, uint32_t dataLength, uint32_t *sentLength);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif //#ifndef _CA_LEADAPTER_SINGLETHREAD_H_
+
{
#endif
+/**
+ * @brief Callback to be notified on reception of any data from remote devices.
+ * @param address [IN] MAC address of remote device.
+ * @param data [IN] Data received from remote device.
+ * @return NONE
+ * @pre Callback must be registered using CALESetCallback(CAPacketReceiveCallback callback)
+ */
typedef void (*CAPacketReceiveCallback)(const char *address, const char *data);
+/**
+ * @brief set context of application
+ * @param env [IN] JNI interface pointer
+ * @param context [IN] context of application
+ * @return None
+ */
void CALEClientJNISetContext(JNIEnv *env, jobject context);
+/**
+ * @brief create interface object and initialize the object
+ * @return None
+ */
void CALeCreateJniInterfaceObject();
+/**
+ * @brief initialize client for BLE
+ * @param handle [IN] thread pool handle object
+ * @return None
+ */
void CALEInitialize(u_thread_pool_t handle);
+/**
+ * @brief terminate client for BLE
+ * @return None
+ */
void CALETerminate();
-void CANativeSendFinsih(JNIEnv *env, jobject gatt);
+/**
+ * @brief for destroy sending routine
+ * @param env [IN] JNI interface pointer
+ * @param gatt [IN] Gatt profile object
+ * @return None
+ */
+void CANativeSendFinish(JNIEnv *env, jobject gatt);
-int32_t CALESendUnicastMessage(const char *address, const char *data, uint32_t dataLen);
+/**
+ * @brief send data for unicast (interface)
+ * @param address [IN] remote address
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALESendUnicastMessage(const char *address, const char *data, const uint32_t dataLen);
-int32_t CALESendMulticastMessage(const char *data, uint32_t dataLen);
+/**
+ * @brief send data for multicast (interface)
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALESendMulticastMessage(const char *data, const uint32_t dataLen);
-int32_t CALEStartUnicastServer(const char *address);
+/**
+ * @brief start unicast server
+ * @param address [IN] remote address
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEStartUnicastServer(const char *address);
-int32_t CALEStartMulticastServer();
+/**
+ * @brief start multicast server (start discovery)
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEStartMulticastServer();
-int32_t CALEStopUnicastServer(int32_t serverID);
+/**
+ * @brief stop unicast server
+ * @return None
+ */
+void CALEStopUnicastServer();
-int32_t CALEStopMulticastServer(int32_t serverID);
+/**
+ * @brief stop multicast server (stop discovery)
+ * @return None
+ */
+void CALEStopMulticastServer();
+/**
+ * @brief set this callback for receiving data packets from peer devices.
+ * @param callback [IN] callback to be notified on reception of
+ * unicast/multicast data packets.
+ * @return None
+ */
void CALESetCallback(CAPacketReceiveCallback callback);
+/**
+ * @brief get local address (interface)
+ * @param address [OUT] local address
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
CAResult_t CALEGetInterfaceInfo(char **address);
+/**
+ * @brief get local address (inplement)
+ * @param address [OUT] local address
+ * @return None
+ */
void CALEGetLocalAddress(char** address);
-int32_t CALESendUnicastMessageImpl(const char *address, const char *data, uint32_t dataLen);
+/**
+ * @brief send data for unicast (implement)
+ * @param address [IN] remote address
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALESendUnicastMessageImpl(const char *address, const char *data, const uint32_t dataLen);
-int32_t CALESendMulticastMessageImpl(JNIEnv *env, const char *data, uint32_t dataLen);
+/**
+ * @brief send data for multicast (implement)
+ * @param address [IN] remote address
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALESendMulticastMessageImpl(const char *data, const uint32_t dataLen);
/**
* BT Common Method : JNI
*/
+/**
+ * @brief get address from bluetooth gatt object
+ * @param env [IN] JNI interface pointer
+ * @param gatt [IN] Gatt profile object
+ * @return bluetooth address
+ */
jstring CANativeGetAddressFromGattObj(JNIEnv *env, jobject gatt);
+/**
+ * @brief get remote address from bluetooth socket object
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothSocketObj [IN] bluetooth socket
+ * @return bluetooth address
+ */
jstring CANativeGetRemoteAddress(JNIEnv *env, jobject bluetoothSocketObj);
/**
- * BLE Method : JNI
+ * @brief close gatt
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGatt [IN] Gatt profile object
+ * @return None
*/
void CANativeGattClose(JNIEnv *env, jobject bluetoothGatt);
+/**
+ * @brief start to scan whole bluetooth devices (interface)
+ * @return None
+ */
void CANativeLEStartScan();
+/**
+ * @brief start to scan whole bluetooth devices (implement)
+ * @param env [IN] JNI interface pointer
+ * @param callback [IN] callback to receive device object by scanning
+ * @return None
+ */
void CANativeLEStartScanImpl(JNIEnv *env, jobject callback);
+/**
+ * @brief start to scan target bluetooth devices for service uuid (implement)
+ * @param env [IN] JNI interface pointer
+ * @param uuids [IN] target UUID
+ * @param callback [IN] callback to receive device object by scanning
+ * @return None
+ */
void CANativeLEStartScanWithUUIDImpl(JNIEnv *env, jobjectArray uuids, jobject callback);
+/**
+ * @brief get uuid object
+ * @param env [IN] JNI interface pointer
+ * @param uuid [IN] uuid
+ * @return uuid object
+ */
jobject CANativeGetUUIDObject(JNIEnv *env, const char *uuid);
+/**
+ * @brief stop scan (interface)
+ * @return None
+ */
void CANativeLEStopScan();
+/**
+ * @brief stop scan (implement)
+ * @param env [IN] JNI interface pointer
+ * @param callback [IN] callback to receive device object by scanning
+ * @return None
+ */
void CANativeLEStopScanImpl(JNIEnv *env, jobject callback);
-int32_t CANativeLEConnect(JNIEnv *env, jobject bluetoothDevice, jobject context,
+/**
+ * @brief connect to gatt server hosted
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothDevice [IN] bluetooth Device object
+ * @param context [IN] context of application
+ * @param autoconnect [IN] whether to directly connect to the remote device(false) or
+ * to automatically connect as soon as the remote device
+ * becomes available
+ * @param callback [IN] callback for connection state change
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CANativeLEConnect(JNIEnv *env, jobject bluetoothDevice, jobject context,
jboolean autoconnect, jobject callback);
+/**
+ * @brief disconnect to gatt server by a target device
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGatt [IN] Gatt profile object
+ * @return None
+ */
void CANativeLEDisconnect(JNIEnv *env, jobject bluetoothGatt);
+/**
+ * @brief disconnect to gatt server by whole devices
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CANativeLEDisconnectAll(JNIEnv *env);
+/**
+ * @brief start discovery server
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGatt [IN] Gatt profile object
+ * @return None
+ */
void CANativeLEDiscoverServices(JNIEnv *env, jobject bluetoothGatt);
-jboolean CANativeLESendData(JNIEnv *env, jobject bluetoothGatt, jobject gattCharacteristic);
+/**
+ * @brief request to write gatt characteristic
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGatt [IN] Gatt profile object
+ * @param gattCharacteristic [IN] characteristic object that contain data to send
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CANativeWriteCharacteristic(JNIEnv *env, jobject bluetoothGatt, jobject gattCharacteristic);
+/**
+ * @brief request to read gatt characteristic
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGatt [IN] Gatt profile object
+ * @return None
+ */
void CANativeReadCharacteristic(JNIEnv *env, jobject bluetoothGatt);
-jboolean CANativeSetCharacteristicNoti(JNIEnv *env, jobject bluetoothGatt, const char* uuid);
+/**
+ * @brief enable notification for a target device
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGatt [IN] Gatt profile object
+ * @param uuid [IN] for set BluetoothGattCharacteristic object
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_ADAPTER_NOT_ENABLED Adapter is not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CANativeSetCharacteristicNotification(JNIEnv *env, jobject bluetoothGatt,
+ const char* uuid);
+/**
+ * @brief create gatt characteristic object
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGatt [IN] Gatt profile object
+ * @param data [IN] for make Characteristic with data
+ * @return Gatt Characteristic object
+ */
jobject CANativeCreateGattCharacteristic(JNIEnv *env, jobject bluetoothGatt, jbyteArray data);
+/**
+ * @brief get gatt service
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothGatt [IN] Gatt profile object
+ * @param characterUUID [IN] for make BluetoothGattCharacteristic object
+ * @return Gatt Service
+ */
jobject CANativeGetGattService(JNIEnv *env, jobject bluetoothGatt, jstring characterUUID);
+/**
+ * @brief get value from characteristic
+ * @param env [IN] JNI interface pointer
+ * @param characteristic [IN] Characteristic object
+ * @return value in characteristic
+ */
jbyteArray CANativeGetValueFromCharacteristic(JNIEnv *env, jobject characteristic);
+/**
+ * @brief create UUID List
+ * @return None
+ */
void CANativeCreateUUIDList();
+
/**
* BluetoothDevice List
*/
+/**
+ * @brief create scan device list
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CANativeCreateScanDeviceList(JNIEnv *env);
+/**
+ * @brief add device object to scan device list
+ * @param env [IN] JNI interface pointer
+ * @param device [IN] bluetooth device object
+ * @return None
+ */
void CANativeAddScanDeviceToList(JNIEnv *env, jobject device);
+/**
+ * @brief check whether the device exist in list or not
+ * @param env [IN] JNI interface pointer
+ * @param remoteAddress [IN] remote address
+ * @return TRUE or FALSE
+ */
jboolean CANativeIsDeviceInList(JNIEnv *env, const char *remoteAddress);
+/**
+ * @brief remove all devices in scan device list
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CANativeRemoveAllDevices(JNIEnv *env);
+/**
+ * @brief remove target device in scan device list
+ * @param env [IN] JNI interface pointer
+ * @param remoteAddress [IN] remote address
+ * @return None
+ */
void CANativeRemoveDevice(JNIEnv *env, jstring remoteAddress);
+/**
+ * @brief Reordering for scan device list
+ * @param index [IN] index of device list that want to reordering
+ * @return None
+ */
void CAReorderingDeviceList(uint32_t index);
/**
* BluetoothGatt List
*/
+/**
+ * @brief create gatt object list
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CANativeCreateGattObjList(JNIEnv *env);
+/**
+ * @brief add gatt object to gatt object list
+ * @param env [IN] JNI interface pointer
+ * @param gatt [IN] Gatt profile object
+ * @return None
+ */
void CANativeAddGattobjToList(JNIEnv *env, jobject gatt);
+/**
+ * @brief check whether the gatt object exist in list or not
+ * @param env [IN] JNI interface pointer
+ * @param remoteAddress [IN] remote address
+ * @return TRUE or FALSE
+ */
jboolean CANativeIsGattObjInList(JNIEnv *env, const char *remoteAddress);
+/**
+ * @brief remove all gatt objects in gatt object list
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CANativeRemoveAllGattObjsList(JNIEnv *env);
+/**
+ * @brief remove target device in gatt object list
+ * @param env [IN] JNI interface pointer
+ * @param gatt [IN] Gatt profile object
+ * @return None
+ */
void CANativeRemoveGattObj(JNIEnv *env, jobject gatt);
+/**
+ * @brief Reordering for gatt object list
+ * @param index [IN] index of device list that want to reordering
+ * @return None
+ */
void CAReorderingGattList(uint32_t index);
+/**
+ * @brief check whether target device which send data is exist or not
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CANativeupdateSendCnt(JNIEnv *env);
#ifdef __cplusplus
#endif
#endif
+
#endif
/**
- * @enum TRANSFER_TYPE
+ * @enum CALETransferType_t
* @brief Provide info about different mode of data transfer
* This enum is used to differentiate between unicast and multicast data transfer.
*/
typedef enum
{
- MULTICAST, /**< When this enum is selected, data will be updated to all OIC servers. */
- UNICAST /**< When this enum is selected, data will be updated to desired OIC Server. */
-} TRANSFER_TYPE;
+ LE_MULTICAST, /**< When this enum is selected, data will be updated to all OIC servers. */
+ LE_UNICAST /**< When this enum is selected, data will be updated to desired OIC Server. */
+} CALETransferType_t;
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitializeLENwkMonitor();
+CAResult_t CAInitializeLENetworkMonitor();
/**
* @brief Used to terminate the network monitor layer of the LE adapter. The variables intialized
* in CAInitializeLEAdapterController() must be cleared in this function.
* @return NONE
*/
-void CATerminateLENwkMonitor();
+void CATerminateLENetworkMonitor();
/**
* @brief This function is used to set the callback for the Device state changes in the adapter.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitLENwkMonitorMutexVaraibles();
+CAResult_t CAInitLENetworkMonitorMutexVariables();
/**
* @brief Used to terminate all the mutex variables required to operate the LE network monitor
* layer.
* @return NONE
*/
-void CATerminateLENwkMonitorMutexVaraibles();
+void CATerminateLENetworkMonitorMutexVariables();
/**
* @brief Provides the BD address of the local adapter.
* @param remoteAddress [IN] The address of the remote device
* @param data [IN] The value of characteristic (byte array)
* @param dataLen [IN] The length of value
- * @param type [IN] Type of the transfer(#TRANSFER_TYPE)
+ * @param type [IN] Type of the transfer(#CALETransferType_t)
* @param position [IN] The unique index of each ble server. Used for multicast feature.
*
* @return #CA_STATUS_OK or Appropriate error code
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const char *data,
- const int32_t dataLen, TRANSFER_TYPE type,
+ const int32_t dataLen, CALETransferType_t type,
const int32_t position);
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAUpdateCharacteristicsToAllGattServers(const char *data, const int32_t dataLen);
+CAResult_t CAUpdateCharacteristicsToAllGattServers(const char *data, int32_t dataLen);
/**
* @brief Used to store upper layer callback locally which will be used to send the data to
#endif
#endif //_CA_LE_INTERFACE_H_
+
#endif
/**
- * @enum TRANSFER_TYPE
+ * @enum CALETransferType_t
* @brief Provide information about different mode of data transfer
* This enum is used to differentiate between unicast and multicast data transfer.
*/
typedef enum
{
- MULTICAST, /**< When this enum is selected, data will be updated to all OIC servers. */
- UNICAST /**< When this enum is selected, data will be updated to desired OIC Server. */
-} TRANSFER_TYPE;
+ LE_MULTICAST, /**< When this enum is selected, data will be updated to all OIC servers. */
+ LE_UNICAST /**< When this enum is selected, data will be updated to desired OIC Server. */
+} CALETransferType_t;
/**
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAUpdateCharacteristicsInGattServer(const char *charValue,
- const uint32_t charValueLen);
+ uint32_t charValueLen);
/**
* @brief Used to start CAStartBleGattClientThread for initializing Gatt Client
* @param remoteAddress [IN] The address of the remote device
* @param data [IN] The value of characteristic (byte array)
* @param dataLen [IN] The length of value
- * @param type [IN] Type of the transfer(#TRANSFER_TYPE)
+ * @param type [IN] Type of the transfer(#CALETransferType_t)
* @param position [IN] The unique index of each ble server. Used for multicast feature.
*
* @return #CA_STATUS_OK or Appropriate error code
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const char *data,
- const int32_t dataLen, TRANSFER_TYPE type,
+ const int32_t dataLen, CALETransferType_t type,
const int32_t position);
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAUpdateCharacteristicsToAllGattServers(const char *data,
- const int32_t dataLen);
+CAResult_t CAUpdateCharacteristicsToAllGattServers(const char *data, int32_t dataLen);
/**
* @brief Used to store upper layer callback locally which will be used to send the data to
#endif
#endif //_CA_LE_INTERFACE_SINGLETHREAD_H_
+
{
#endif
+/**
+ * @var CALENetStateChantedCallback
+ * @brief Maintains network connection state change callback.
+ */
typedef void (*CALENetStateChantedCallback)(const char* address, const uint32_t status);
+/**
+ * @brief set context of application
+ * @param env [IN] JNI interface pointer
+ * @param context [IN] context of application
+ * @return None
+ */
void CALENetworkMonitorJNISetContext(JNIEnv *env, jobject context);
+/**
+ * @brief initialize JNI object
+ * @param env [IN] JNI interface pointer
+ * @param jvm [IN] java virtual machine pointer
+ * @return None
+ */
void CALeNetworkMonitorJniInit(JNIEnv *env, JavaVM *jvm);
+/**
+ * @brief Set this callback for receiving network information from BT stack.
+ * @param callback [IN] Callback to be notified on reception of BT state information
+ * @return NONE
+ */
void CALESetNetStateCallback(CALENetStateChantedCallback callback);
#ifdef __cplusplus
#endif
+
* @file calecore.h
* @brief This file contains the APIs for BT LE communications.
*/
-#ifndef __CA_LECORE_H_
-#define __CA_LECORE_H_
+#ifndef __CA_LESERVER_H_
+#define __CA_LESERVER_H_
#include "cacommon.h"
#include "uthreadpool.h"
{
#endif
+/**
+ * @brief Callback to be notified on reception of any data from remote devices.
+ * @param address [IN] MAC address of remote device.
+ * @param data [IN] Data received from remote device.
+ * @return None
+ * @pre Callback must be registered using CALEServerSetCallback(CAPacketReceiveCallback callback)
+ */
typedef void (*CAPacketReceiveCallback)(const char *address,
const char *data);
+/**
+ * @brief initialize server for BLE
+ * @param handle [IN] thread pool handle object
+ * @return None
+ */
void CALEServerInitialize(u_thread_pool_t handle);
+/**
+ * @brief terminate client for BLE
+ * @return None
+ */
void CALEServerTerminate();
-int32_t CALEServerSendUnicastMessage(const char *address, const char *data,
+/**
+ * @brief send data for unicast (interface)
+ * @param address [IN] remote address
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEServerSendUnicastMessage(const char *address, const char *data,
uint32_t dataLen);
-int32_t CALEServerSendMulticastMessage(const char *data, uint32_t dataLen);
+/**
+ * @brief send data for multicast (interface)
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEServerSendMulticastMessage(const char *data, uint32_t dataLen);
-int32_t CALEServerStartUnicastServer(const char *address);
+/**
+ * @brief start unicast server
+ * @param address [IN] remote address
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEServerStartUnicastServer(const char *address);
-int32_t CALEServerStartMulticastServer();
+/**
+ * @brief start multicast server (start advertise)
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEServerStartMulticastServer();
-int32_t CALEServerStopUnicastServer(int32_t serverID);
+/**
+ * @brief stop unicast server
+ * @return None
+ */
+CAResult_t CALEServerStopUnicastServer();
-int32_t CALEServerStopMulticastServer(int32_t serverID);
+/**
+ * @brief stop multicast server (stop discovery)
+ * @return None
+ */
+CAResult_t CALEServerStopMulticastServer();
+/**
+ * @brief set this callback for receiving data packets from peer devices.
+ * @param callback [IN] callback to be notified on reception of
+ * unicast/multicast data packets.
+ * @return None
+ */
void CALEServerSetCallback(CAPacketReceiveCallback callback);
+/**
+ * @brief Get local adapter network information.
+ * @param info [OUT] local connectivity information
+ * @param size [OUT] connectivity count
+ * @return None
+ */
void CALEServerGetInterfaceInfo(CALocalConnectivity_t **info,
uint32_t *size);
+/**
+ * @brief get local address
+ * @param address [OUT] local address
+ * @return None
+ */
void CALEServerGetLocalAddress(char *address);
-int32_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char *address,
+/**
+ * @brief send data for unicast (implement)
+ * @param env [IN] JNI interface pointer
+ * @param address [IN] remote address
+ * @param data [IN] data for transmission
+ * @param dataLen [IN] data length
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char *address,
const char *data, uint32_t dataLen);
-int32_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const char *data,
+/**
+ * @brief send data for multicast (implement)
+ * @param env [IN] JNI interface pointer
+ * @param address [IN] remote address
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const char *data,
uint32_t dataLen);
-/* BLE Server Functions */
-
+/* Android BLE Server Functions */
+/**
+ * @brief set context of application
+ * @param env [IN] JNI interface pointer
+ * @param context [IN] context of application
+ * @return None
+ */
void CALEServerJNISetContext(JNIEnv *env, jobject context);
+/**
+ * @brief initialize JNI object
+ * @param env [IN] JNI interface pointer
+ * @param jvm [IN] java virtual machine pointer
+ * @return None
+ */
void CALeServerJniInit(JNIEnv *env, JavaVM* jvm);
+/**
+ * @brief create interface object and initialize the object
+ * @return None
+ */
void CALeServerCreateJniInterfaceObject();
+/**
+ * @brief start advertise in gatt server
+ * @param env [IN] JNI interface pointer
+ * @param advertiseCallback [IN] callback to be notified on reception of
+ * advertisement result
+ * @return None
+ */
void CANativeLEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback);
+/**
+ * @brief stop advertise in gatt server
+ * @param env [IN] JNI interface pointer
+ * @param advertiseCallback [IN] callback to be notified on reception of
+ * advertisement result
+ * @return None
+ */
void CANativeLEServerStopAdvertise(JNIEnv *env, jobject advertiseCallback);
+/**
+ * @brief open a gatt server
+ * @param env [IN] JNI interface pointer
+ * @return gatt server object
+ */
jobject CANativeLEServerOpenGattServer(JNIEnv *env);
+/**
+ * @brief create gatt service
+ * @param env [IN] JNI interface pointer
+ * @return gatt service object
+ */
jobject CANativeLEServerCreateGattService(JNIEnv *env);
-jboolean CANativeLEServerAddGattService(JNIEnv *env, jobject bluetoothGattServer,
+/**
+ * @brief create gatt service
+ * @param env [IN] JNI interface pointer
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_ADAPTER_NOT_ENABLED Adapter is not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CANativeLEServerAddGattService(JNIEnv *env, jobject bluetoothGattServer,
jobject bluetoothGattService);
-jboolean CALEStartGattServer(JNIEnv *env, jobject gattServerCallback);
+/**
+ * @brief start gatt server
+ * @param env [IN] JNI interface pointer
+ * @param gattServerCallback [IN] callback to be notified on reception of
+ * state change of gatt server
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_ADAPTER_NOT_ENABLED Adapter is not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEStartGattServer(JNIEnv *env, jobject gattServerCallback);
-jboolean CALEServerSend(JNIEnv *env, jobject bluetoothDevice, jstring data);
+/**
+ * @brief send data
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothDevice [IN] bluetooth device object
+ * @param data [IN] data which send
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_SEND_FAILED Send request failed
+ * @retval #CA_ADAPTER_NOT_ENABLED Adapter is not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CALEServerSend(JNIEnv *env, jobject bluetoothDevice, jstring data);
+/**
+ * @brief set data in BluetoothGattCharacteristic
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothDevice [IN] bluetooth device object
+ * @return BluetoothGattCharacteristic object
+ */
jobject CANativeLEServerSetResponseData(JNIEnv *env, jbyteArray responseData);
-jboolean CANativeLEServerSendResponseData(JNIEnv *env, jobject device, jobject responseData);
+/**
+ * @brief send data through notifyCharacteristicChanged api of android
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothDevice [IN] bluetooth device object
+ * @param data [IN] data which send
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_SEND_FAILED Send request failed
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CANativeLEServerSendResponseData(JNIEnv *env, jobject device, jobject responseData);
-jboolean CANativeLEServerSendResponse(JNIEnv *env, jobject device, jint requestId, jint status,
+/**
+ * @brief send a response to a write request to a remote device
+ * @param env [IN] JNI interface pointer
+ * @param device [IN] bluetooth device object
+ * @param requestId [IN] the id of request
+ * @param status [IN] the status of the request to be sent to the remote devices
+ * @param offset [IN] value offset for partial write response
+ * @param value [IN] the value of the attribute that written (optional)
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_SEND_FAILED Send request failed
+ * @retval #CA_ADAPTER_NOT_ENABLED Adapter is not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CANativeLEServerSendResponse(JNIEnv *env, jobject device, jint requestId, jint status,
jint offset, jbyteArray value);
-jboolean CANativeLEServerConnect(JNIEnv *env, jobject bluetoothDevice);
+/**
+ * @brief connect BLE to remote device form gatt server
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothDevice [IN] bluetooth device object
+ * @return #CA_STATUS_OK or Appropriate error code
+ * @retval #CA_STATUS_OK Successful
+ * @retval #CA_ADAPTER_NOT_ENABLED Adapter is not enabled
+ * @retval #CA_STATUS_FAILED Operation failed
+ */
+CAResult_t CANativeLEServerConnect(JNIEnv *env, jobject bluetoothDevice);
+/**
+ * @brief disconnect BLE to remote device form gatt server
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothDevice [IN] bluetooth device object
+ * @return None
+ */
void CANativeLEServerDisconnect(JNIEnv *env, jobject bluetoothDevice);
/* BLE Server Utils */
+/**
+ * @brief create connected device list
+ * @return None
+ */
void CALEServerCreateCachedDeviceList();
+/**
+ * @brief check whether the device exist in the list or not
+ * @param env [IN] JNI interface pointer
+ * @param remoteAddress [IN] remote address
+ * @return TRUE or FALSE
+ */
jboolean CALEServerIsDeviceInList(JNIEnv *env, const char* remoteAddress);
+/**
+ * @brief add device object to the list (connected device list)
+ * @param env [IN] JNI interface pointer
+ * @param device [IN] bluetooth device object
+ * @return None
+ */
void CALEServerAddDeviceToList(JNIEnv *env, jobject device);
+/**
+ * @brief remove all devices objects in the list (connected device list)
+ * @param env [IN] JNI interface pointer
+ * @return None
+ */
void CALEServerRemoveAllDevices(JNIEnv *env);
+/**
+ * @brief remove target device in the list (connected device list)
+ * @param env [IN] JNI interface pointer
+ * @param gatt [IN] Gatt profile object
+ * @return None
+ */
void CALEServerRemoveDevice(JNIEnv *env, jstring address);
+/**
+ * @brief Reordering for the list (connected device list)
+ * @param index [IN] index of device list that want to reordering
+ * @return None
+ */
void CALEServerReorderinglist(uint32_t index);
#ifdef __cplusplus
} /* extern "C" */
#endif
-#endif
+#endif /* __CA_LESERVER_H_ */
+
{
#endif
+/**
+ * @brief get uuid(jni object) from uuid(character)
+ * @param env [IN] JNI interface pointer
+ * @param uuid [IN] uuid(character)
+ * @return uuid(jni object)
+ */
jobject CALEGetUuidFromString(JNIEnv *env, const char* uuid);
+/**
+ * @brief get parcel uuid object
+ * @param env [IN] JNI interface pointer
+ * @param uuid [IN] uuid (jni object)
+ * @return parcel uuid object
+ */
jobject CALEGetParcelUuid(JNIEnv *env, jobject uuid);
+/**
+ * @brief get address from a local device
+ * @param env [IN] JNI interface pointer
+ * @return local address
+ */
jstring CALEGetLocalDeviceAddress(JNIEnv *env);
+/**
+ * @brief get bonded list
+ * @param env [IN] JNI interface pointer
+ * @return bonded list
+ */
jobjectArray CALEGetBondedDevices(JNIEnv *env);
+/**
+ * @brief get constants information of bluetooth state-on
+ * @param env [IN] JNI interface pointer
+ * @return constants information of bluetooth state-on
+ */
jint CALEGetBTStateOnInfo(JNIEnv *env);
+/**
+ * @brief get bluetooth adapter state information
+ * @param env [IN] JNI interface pointer
+ * @return true if the local adapter is turned on
+ */
jboolean CALEIsEnableBTAdapter(JNIEnv *env);
+/**
+ * @brief get address from remote device
+ * @param env [IN] JNI interface pointer
+ * @param bluetoothDevice [IN] bluetooth device object
+ * @return remote address
+ */
jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice);
#ifdef __cplusplus
#endif
#endif
+
/**
* @brief Detaches control from the caller for sending unicast request
* @param endpoint [IN] endpoint information where the data has to be sent
- * @param request [IN] request that needs to be sent
+ * @param request [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *endpoint,
/**
* @brief Detaches control from the caller for sending multicast request
* @param endpoint [IN] endpoint information where the data has to be sent
- * @param request [IN] request that needs to be sent
+ * @param request [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CADetachRequestToAllMessage(const CAGroupEndpoint_t *object,
/**
* @brief Detaches control from the caller for sending response
* @param endpoint [IN] endpoint information where the data has to be sent
- * @param response [IN] request that needs to be sent
+ * @param response [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *endpoint,
/**
* @brief Detaches control from the caller for sending request
- * @param resourceUri [IN] resource uri that needs to be sent in the request
- * @param token [IN] token information of the request
- * @param options [IN] header options that need to be append in the request
- * @param numOptions [IN] number of options be appended
+ * @param resourceUri [IN] resource uri that needs to be sent in the request
+ * @param token [IN] token information of the request
+ * @param options [IN] header options that need to be append in the request
+ * @param numOptions [IN] number of options be appended
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
- const CAHeaderOption_t *options, uint8_t numOptions);
+ const CAHeaderOption_t *options, const uint8_t numOptions);
/**
* @brief Setting the request and response callbacks for network packets
- * @param ReqHandler [IN] callback for receiving the requests
- * @param RespHandler [IN] callback for receiving the response
+ * @param ReqHandler [IN] callback for receiving the requests
+ * @param RespHandler [IN] callback for receiving the response
* @return void
*/
void CASetRequestResponseCallbacks(CARequestCallback ReqHandler,
#endif
#endif //#ifndef __CA_MESSAGE_HANDLER_H_
+
#endif
/**
- * @brief Function pointer for message handler callback
- */
-typedef void (*CAMessageHandlerCallback)(CAToken_t token, CAResult_t res);
-
-
-/**
* @brief Detaches control from the caller for sending unicast request
* @param endpoint [IN] endpoint information where the data has to be sent
- * @param request [IN] request that needs to be sent
+ * @param request [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object,
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *endpoint,
const CARequestInfo_t *request);
/**
/**
* @brief Detaches control from the caller for sending response
- * @param endpoint [IN] endpoint information where the data has to be sent
- * @param response [IN] request that needs to be sent
+ * @param object [IN] endpoint information where the data has to be sent
+ * @param response [IN] request that needs to be sent
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
/**
* @brief Detaches control from the caller for sending request
- * @param resourceUri [IN] resource uri that needs to be sent in the request
- * @param token [IN] token information of the request
- * @param options [IN] header options that need to be append in the request
- * @param numOptions [IN] number of options be appended
+ * @param resourceUri [IN] resource uri that needs to be sent in the request
+ * @param token [IN] token information of the request
+ * @param options [IN] header options that need to be append in the request
+ * @param numOptions [IN] number of options be appended
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
const CAHeaderOption_t *options, uint8_t numOptions);
-
-/**
- * @brief Setting the message callback
- * @param callback [IN] callback will be called after data is processed
- * @return void
- */
-void CASetMessageHandlerCallback(CAMessageHandlerCallback callback);
-
/**
* @brief Setting the request and response callbacks for network packets
* @param ReqHandler [IN] callback for receiving the requests
* @param RespHandler [IN] callback for receiving the response
* @return void
*/
-void CASetRequestResponseCallbacks(CARequestCallback ReqHandler,
- CAResponseCallback RespHandler);
+void CASetRequestResponseCallbacks(CARequestCallback ReqHandler,
+ CAResponseCallback RespHandler);
/**
- * @brief Initialize the message handler by starting thread pool and initializing the
- * send and reive queue
+ * @brief Initialize the message handler by starting thread pool and initializing the
+ * send and receive queue
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CAInitializeMessageHandler();
#endif
#endif //#ifndef __CA_MESSAGE_HANDLER_SINGLETHREAD_H_
+
#endif
/*****************************************************************
- * @file The CA Header format *
- * @brief CA Header will be difined by 2 bytes of Header. *
- * First two bits : Header version *
- * Third bit nad fourth bit: Reserved and will be set as Zero. *
- * 5th to 16th bit : 12 bits to provide the length of the data in bits. *
- * *
+ * @file The CA Header format
+ * @brief CA Header will be difined by 2 bytes of Header.
+ * First two bits : Header version(Currently Its not being used)
+ * Third bit and fourth bit: Reserved bits for future use.
+ * 5th to 16th bit : 12 bits to provide the length of the data.
*****************************************************************/
-
-/**
-* @fn printBinaryFormat
-* @brief This function prints the binary format of one byte of data
-* This functoin is added as debug utility and can be used to check the
-* bits set in header while framing/parsing.
-*
-* @param[in] data Pointer to the charcter data which needs to be printed.
-*
-* @return 0 on failure and 1 on success.
-*/
-void printBinaryFormat(char *data);
-
/**
* @fn CAGenerateHeader
* @brief This function is used to generate the CA specific header to maintain the fragmentation
* logic. The header sturcture explained above will be formed and returned to the caller.
*
* @param[in] data Pointer to the charcter data which needs to be printed.
-* @param[in] length The total legth of the data which ll be represed from 5th -16th bits
+* @param[in] length The total legth of the data which will be represented from 5th -16th bits
* in the header.
*
-* @return 0 on success otherwise a positive error value.
+* @return CA_STATUS_OK on success. One of theCA_STATUS_FAILED or other error values on error.
* @retval CA_STATUS_OK Successful
* @retval CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval CA_STATUS_FAILED Operation failed
#endif
#endif // _CA_MSG_PARSER_H_
+
******************************************************************/
/**
* @file canetworkconfigurator.h
- * @brief This file contains utility function for network configurations.
+ * @brief This file contains utility functions for network configurations.
*/
#ifndef _NETWORK_CONFIGURATOR_H_
/**
* @brief Add network type to the selected networks for network packets reception
- * @param CAConnectivityType [IN] connectivity type that needs to be added
+ * @param connectivityType [IN] connectivity type that needs to be added
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CAAddNetworkType(uint32_t CAConnectivityType);
+CAResult_t CAAddNetworkType(CAConnectivityType_t connectivityType);
/**
- * @brief Add network type to the un selected for network packets reception
- * @param CAConnectivityType [IN] connectivity type that needs to be removed
+ * @brief Remove network type from the selected configuration
+ * @param connectivityType [IN] connectivity type that needs to be removed
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
-CAResult_t CARemoveNetworkType(uint32_t CAConnectivityType);
+CAResult_t CARemoveNetworkType(CAConnectivityType_t connectivityType);
/**
* @brief Get selected network information
*/
CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size);
+/**
+ * @brief Terminate network type from selected configuration
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
CAResult_t CATerminateNetworkType();
#endif
#endif //#ifndef _NETWORK_CONFIGURATOR_H_
+
/**
* @brief generates pdu structure from the given information.
- * @param uri [IN] uri information of the pdu
- * @param code [IN] cod of the pdu packet
- * @param info [IN] pdu information such as request code ,response code and payload
+ * @param uri [IN] uri information of the pdu
+ * @param code [IN] code of the pdu packet
+ * @param info [IN] pdu information such as request code, response code, payload
* @return coap_pdu_t created pdu
*/
coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info);
/**
* @brief extracts request information from received pdu.
- * @param pdu [IN] received pdu
- * @param outReqInfo [OUT] request info structure made from received pdu
+ * @param pdu [IN] received pdu
+ * @param outReqInfo [OUT] request info structure made from received pdu
* @param outUri [OUT] uri received in the received pdu
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @param buflen [IN] Buffer Length for outUri parameter
+ * @return None
*/
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,
- char *outUri);
+void CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo, char *outUri,
+ uint32_t buflen);
/**
* @brief extracts response information from received pdu.
- * @param pdu [IN] received pdu
- * @param outResInfo [OUT] request info structure made from received pdu
+ * @param pdu [IN] received pdu
+ * @param outResInfo [OUT] response info structure made from received pdu
* @param outUri [OUT] uri received in the received pdu
- * @return 0 or 1 ( CAResult_t error codes in cacommon.h)
+ * @param buflen [IN] Buffer Length for outUri parameter
+ * @return None
*/
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
- char *outUri);
+void CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo, char *outUri,
+ uint32_t buflen);
/**
* @brief creates pdu from the request information
* @param code [IN] request or response code
- * @param options [IN] options for the request and response
- * @param info [IN] pdu information such as request code ,response code
- * @return coap_pdu_t
- */
-coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,
- const CAInfo_t info);
-
-/**
- * @brief creates pdu for ACK or RESET type
- * @param code [IN] request or response code
- * @param info [IN] pdu information such as response code
- * @return coap_pdu_t
- */
-coap_pdu_t *CACreatePDUforRSTandACK(const code_t code, const CAInfo_t info);
-
-/**
- * @brief creates pdu from the request information and paylod
- * @param code [IN] request or response code alloted
- * @param options [IN] options for the request and response backpacked
+ * @param options [OUT] options for the request and response
+ * @param info [IN] information to create pdu
* @param payload [IN] payload for the request or response consumed
- * @param info [IN] pdu information such as request code ,response code
* @return coap_pdu_t
*/
-
-coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *optlist,
- const char *payload, const CAInfo_t info);
+coap_pdu_t *CAGeneratePduImpl(const code_t code, coap_list_t *options, const CAInfo_t info,
+ const char *payload);
/**
* @brief parse the URI and creates the options
* @param uriInfo [IN] uri information
- * @param options [IN] options information
+ * @param options [OUT] options information
* @return None
*/
void CAParseURI(const char *uriInfo, coap_list_t **options);
* @brief create option list from header information in the info
* @param code [IN] uri information
* @param info [IN] options information
- * @param optlist [IN] options information
+ * @param optlist [OUT] options information
* @return None
*/
void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist);
/**
- * @brief creates option node from key lenght and data
+ * @brief creates option node from key length and data
* @param key [IN] key for the that needs to be sent
* @param length [IN] length of the data that needs to be sent
* @param data [IN] data that needs to be sent
* @return created list
*/
-coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length,
- const uint8_t *data);
+coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length, const uint8_t *data);
/**
* @brief order the inserted options
+ * need to replace queue head if new node has to be added before the existing queue head
* @param a [IN] option 1 for insertion
* @param b [IN] option 2 for insertion
* @return 0 or 1
* @brief gets option data
* @param data [IN] data that is received
* @param length [IN] length of the data
- * @param result [IN] result of the operation
+ * @param option [OUT] option
* @param buflen [IN] buffer length of the result
- * @param encode_always [IN] encoded data
- * @return 0 or 1
+ * @return option count
*/
-uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result, uint32_t buflen,
- uint32_t encode_always);
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *option, uint32_t buflen);
/**
* @brief extracts request information from received pdu.
- * @param pdu [IN] received pdu
+ * @param pdu [IN] received pdu
* @param outCode [OUT] code of the received pdu
* @param outInfo [OUT] request info structure made from received pdu
* @param outUri [OUT] uri received in the received pdu
+ * @param buflen [IN] Buffer Length for outUri parameter
* @return None
*/
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
- char *outUri);
+void CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo, char *outUri,
+ uint32_t buflen);
/**
- * @brief create pdu fromn received data
+ * @brief create pdu from received data
* @param data [IN] received data
* @param length [IN] length of the data received
- * @param outCode [IN] code received
+ * @param outCode [OUT] code received
* @return None
*/
coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode);
/**
- * @brief get Token fromn received data(pdu)
- * @param pdu [IN] received pdu
- * @param outCode [IN] Token received
- * @return None
- */
-CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo);
-
-/**
* @brief generates the token
* @param token [OUT] generated token
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
/**
* @brief destroy the ca info structure
- * @param info [IN] info structure created from received packet
+ * @param info [IN] info structure created from received packet
* @return none
*/
-void CADeinitialize(CAInfo_t *info);
+void CADestroyInfo(CAInfo_t *info);
/**
* @brief gets message type from PDU binary data
*/
uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size);
-/**
- * @brief gets code PDU binary data
- * @param pdu [IN] pdu data
- * @param size [IN] size of pdu data
- * @return code
- */
-CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size);
-
#ifdef __cplusplus
} /* extern "C" */
#endif
/**
* @brief generates pdu structure from the given information.
- * @param uri [IN] uri information of the pdu
- * @param code [IN] cod of the pdu packet
+ * @param uri [IN] uri information of the pdu
+ * @param code [IN] code of the pdu packet
* @param info [IN] pdu information such as request code ,response code and payload
* @return coap_pdu_t created pdu
*/
-coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info);
+coap_pdu_t *CAGeneratePdu(const char *uri, uint32_t code, const CAInfo_t info);
/**
* function for generating
/**
* @brief extracts request information from received pdu.
* @param pdu [IN] received pdu
- * @param outReqInfo [OUT] request info structure made from received pdu
- * @param outUri [OUT] uri received in the received pdu
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @param outReqInfo [OUT] request info structure made from received pdu
+ * @param outUri [OUT] uri received in the received pdu
+ * @param buflen [IN] Buffer Length for outUri parameter
+ * @return NONE
*/
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,
- char *outUri);
+void CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,
+ char *outUri, uint32_t bufLen);
/**
* @brief extracts response information from received pdu.
* @param pdu [IN] received pdu
- * @param outResInfo [OUT] request info structure made from received pdu
- * @param outUri [OUT] uri received in the received pdu
- * @return 0 or 1 ( CAResult_t error codes in cacommon.h)
+ * @param outResInfo [OUT] response info structure made from received pdu
+ * @param outUri [OUT] uri received in the received pdu
+ * @param buflen [IN] Buffer Length for outUri parameter
+ * @return NONE
*/
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
- char *outUri);
+void CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
+ char *outUri, uint32_t bufLen);
/**
* @brief creates pdu from the request information
* @param code [IN] request or response code
- * @param options [IN] options for the request and response
- * @param outUri [IN] information to create pdu
- * @return coap_pdu_t
- */
-coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,
- const CAInfo_t info);
-
-/**
- * @brief creates pdu for ACK or RESET type
- * @param code [IN] request or response code
- * @param info [IN] pdu information such as response code
- * @return coap_pdu_t
- */
-coap_pdu_t *CACreatePDUforRSTandACK(const code_t code, const CAInfo_t info);
-
-/**
- * @brief creates pdu from the request information and paylod
- * @param code [IN] request or response code alloted
- * @param options [IN] options for the request and response backpacked
+ * @param options [OUT] options for the request and response
+ * @param info [IN] information to create pdu
* @param payload [IN] payload for the request or response consumed
- * @param outUri [IN] information to create pdu
* @return coap_pdu_t
*/
-
-coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *optlist,
- const char *payload, const CAInfo_t info);
+coap_pdu_t *CAGeneratePduImpl(const code_t code, coap_list_t *options,
+ const CAInfo_t info, const char *payload);
/**
* @brief parse the URI and creates the options
* @param uriInfo [IN] uri information
- * @param options [IN] options information
+ * @param options [OUT] options information
* @return None
*/
void CAParseURI(const char *uriInfo, coap_list_t **options);
* @brief create option list from header information in the info
* @param code [IN] uri information
* @param info [IN] options information
- * @param optlist [IN] options information
+ * @param optlist [OUT] options information
* @return None
*/
-void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist);
+void CAParseHeadOption(uint32_t code, const CAInfo_t info, coap_list_t **optlist);
/**
- * @brief creates option node from key lenght and data
+ * @brief creates option node from key length and data
+ * need to replace queue head if new node has to be added before the existing queue head
* @param key [IN] key for the that needs to be sent
* @param length [IN] length of the data that needs to be sent
* @param data [IN] data that needs to be sent
* @return created list
*/
-coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length,
+coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length,
const uint8_t *data);
/**
* @brief gets option data
* @param data [IN] data that is received
* @param length [IN] length of the data
- * @param result [IN] result of the operation
+ * @param option [OUT] result of the operation
* @param buflen [IN] buffer length of the result
- * @param encode_always [IN] encoded data
- * @return 0 or 1
+ * @return option count
*/
-uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result, uint32_t buflen,
- uint32_t encode_always);
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *option, uint32_t buflen);
/**
* @brief extracts request information from received pdu.
- * @param pdu [IN] received pdu
+ * @param pdu [IN] received pdu
* @param outCode [OUT] code of the received pdu
* @param outInfo [OUT] request info structure made from received pdu
* @param outUri [OUT] uri received in the received pdu
+ * @param buflen [IN] Buffer Length for outUri parameter
* @return None
*/
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
- char *outUri);
+void CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
+ char *outUri, uint32_t bufLen);
/**
* @brief create pdu fromn received data
* @param data [IN] received data
* @param length [IN] length of the data received
- * @param outCode [IN] code received
+ * @param outCode [OUT] code received
* @return None
*/
coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode);
/**
- * @brief get Token fromn received data(pdu)
- * @param pdu [IN] received pdu
- * @param outCode [IN] Token received
- * @return None
- */
-CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo);
-
-/**
* @brief generates the token
* @param token [OUT] generated token
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
/**
* @brief destroy the ca info structure
- * @param info [IN] info structure created from received packet
+ * @param info [IN] info structure created from received packet
* @return none
*/
-void CADeinitialize(CAInfo_t *info);
+void CADestroyInfo(CAInfo_t *info);
/**
* @brief gets message type from PDU binary data
*/
uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size);
-/**
- * @brief gets code PDU binary data
- * @param pdu [IN] pdu data
- * @param size [IN] size of pdu data
- * @return code
- */
-CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size);
-
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif //#ifndef __CA_PROTOCOL_MESSAGE_SINGLETHREAD_H_
+
/**Data destroy function**/
CADataDestroyFunction destroy;
/** Variable to inform the thread to stop **/
- CABool_t isStop;
+ bool isStop;
/** Que on which the thread is operating. **/
u_queue_t *dataQueue;
} CAQueueingThread_t;
/**
* @brief Initializes the queing thread
- * @param thread [IN] thread data for each thread
- * @param handle [IN] thread pool handle created
- * @param task [IN] function to be called for reach data
+ * @param thread [IN] thread data for each thread
+ * @param handle [IN] thread pool handle created
+ * @param task [IN] function to be called for each data
* @param destroy [IN] function to data destroy
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
/**
* @brief Starting the queueing thread
- * @param thread [IN] thread data that needs to be started
+ * @param thread [IN] thread data that needs to be started
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CAQueueingThreadStart(CAQueueingThread_t *thread);
/**
* @brief Add queueing thread data for new thread
- * @param thread [IN] thread data for new thread control
- * @param data [IN] data that needs to be given for each thread
- * @param size [IN] length of the data
+ * @param thread [IN] thread data for new thread control
+ * @param data [IN] data that needs to be given for each thread
+ * @param size [IN] length of the data
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CAQueueingThreadAddData(CAQueueingThread_t *thread, void *data, uint32_t size);
/**
* @brief Stopping the queueing thread
- * @param thread [IN] thread data that needs to be started
+ * @param thread [IN] thread data that needs to be started
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
/**
* @brief Terminating the queing thread
- * @param thread [IN] thread data for each thread
+ * @param thread [IN] thread data for each thread
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
#endif
#endif // __CA_THREAD_H_
+
#ifndef __CA_REMOTE_HANDLER_H_
#define __CA_REMOTE_HANDLER_H_
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
#include "cacommon.h"
#ifdef __cplusplus
/**
* @brief Creates a new remote endpoint from the input uri
- * @param uri [IN] absolute uri information to create remote endpoint
- * @param type [IN] connectivity type of the endpoint
+ * @param uri [IN] absolute uri information to create remote endpoint
+ * @param connectivityType [IN] connectivity type of the endpoint
* @return remote endpoint created
*/
CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri,
/**
* @brief Creates a new remote endpoint from the input and other information
- * @param resourceUri [IN] absolute uri information to create remote endpoint
- * @param addr [IN] address of the ednpoint
- * @param type [IN] connectivity type of the endpoint
+ * @param resourceUri [IN] absolute uri information to create remote endpoint
+ * @param addr [IN] address of the endpoint
+ * @param type [IN] connectivity type of the endpoint
* @return remote endpoint created
*/
CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
/**
* @brief Creates a new request information
- * @param rep [IN] request information that needs to be duplicated
+ * @param request [IN] request information that needs to be duplicated
* @return remote endpoint created
*/
CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *request);
/**
* @brief Destroy the request information
- * @param rep [IN] request information that needs to be destroyed
+ * @param request [IN] request information that needs to be destroyed
* @return none
*/
void CADestroyRequestInfoInternal(CARequestInfo_t *request);
/**
* @brief Creates a new response information
- * @param rep [IN] response information that needs to be duplicated
+ * @param response [IN] response information that needs to be duplicated
* @return remote endpoint created
*/
CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *response);
/**
* @brief Destroy the response information
- * @param rep [IN] response information that needs to be destroyed
+ * @param response [IN] response information that needs to be destroyed
* @return
*/
void CADestroyResponseInfoInternal(CAResponseInfo_t *response);
#endif
#endif //#ifndef __CA_REMOTE_HANDLER_H_
+
#include "cacommon.h"
/** CA_ETHERNET, CA_WIFI, CA_EDR, CA_LE **/
-#define DEFAULT_RETRANSMISSION_TYPE ((1<<0)|(1<<1)|(1<<2)|(1<<3))
+#define DEFAULT_RETRANSMISSION_TYPE (CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE)
/** default ACK time is 2 sec.(CoAP) **/
-#define DEFAULT_ACK_TIMEOUT 2
+#define DEFAULT_ACK_TIMEOUT_SEC 2
/** default max retransmission trying count is 4.(CoAP) **/
#define DEFAULT_MAX_RETRANSMIT 4
/** check period is 1 sec. **/
-#define RETRANSMISSION_CHECK_PERIOD 1000000
+#define RETRANSMISSION_CHECK_PERIOD_SEC 1
/** retransmission data send method type**/
-typedef CAResult_t (*CADataSendMethod_t)(const CARemoteEndpoint_t *endpoint, void *pdu,
+typedef CAResult_t (*CADataSendMethod_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
uint32_t size);
/** retransmission timeout callback type**/
-typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, void *pdu, uint32_t size);
+typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size);
typedef struct
{
/** retransmission configure data **/
CARetransmissionConfig_t config;
/** Variable to inform the thread to stop **/
- CABool_t isStop;
+ bool isStop;
/** array list on which the thread is operating. **/
u_arraylist_t *dataList;
} CARetransmission_t;
/**
* @brief Initializes the retransmission context
- * @param context [IN]context for retransmission
- * @param handle [IN]thread pool handle
- * @param retransmissionSendMethod [IN]function to be called for retransmission
- * @param timeoutCallback [IN]callback for retransmit timeout
- * @param config [IN]configuration for retransmission. if NULL is coming, it will set default values.
+ * @param context [IN] context for retransmission
+ * @param handle [IN] thread pool handle
+ * @param retransmissionSendMethod [IN] function to be called for retransmission
+ * @param timeoutCallback [IN] callback for retransmit timeout
+ * @param config [IN] configuration for retransmission.
+ * if NULL is coming, it will set default values.
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionInitialize(CARetransmission_t *context, u_thread_pool_t handle,
- CADataSendMethod_t retransmissionSendMethod, CATimeoutCallback_t timeoutCallback,
- CARetransmissionConfig_t* config);
+ CADataSendMethod_t retransmissionSendMethod,
+ CATimeoutCallback_t timeoutCallback,
+ CARetransmissionConfig_t* config);
/**
* @brief Starting the retransmission context
- * @param context [IN]context for retransmission
+ * @param context [IN] context for retransmission
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionStart(CARetransmission_t *context);
/**
* @brief Pass the sent pdu data. if retransmission process need, internal thread will wake up and
- * process the retransmission data.
- * @param context [IN]context for retransmission
- * @param endpoint [IN]endpoint information
- * @param pdu [IN]sent pdu binary data
- * @param size [IN]sent pdu binary data size
+ * process the retransmission data.
+ * @param context [IN] context for retransmission
+ * @param endpoint [IN] endpoint information
+ * @param pdu [IN] sent pdu binary data
+ * @param size [IN] sent pdu binary data size
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionSentData(CARetransmission_t* context,
- const CARemoteEndpoint_t* endpoint,const void* pdu, uint32_t size);
+ const CARemoteEndpoint_t* endpoint,const void* pdu,
+ uint32_t size);
/**
- * @brief Paas the received pdu data. if received pdu is ACK data for the retransmission CON data,
- * the specified CON data will remove on retransmission list.
- * @param context [IN]context for retransmission
- * @param endpoint [IN]endpoint information
- * @param pdu [IN]received pdu binary data
- * @param size [IN]received pdu binary data size
- * @param void [OUT] pdu data of the request for reset and ack
+ * @brief Pass the received pdu data. if received pdu is ACK data for the retransmission CON data,
+ * the specified CON data will remove on retransmission list.
+ * @param context [IN] context for retransmission
+ * @param endpoint [IN] endpoint information
+ * @param pdu [IN] received pdu binary data
+ * @param size [IN] received pdu binary data size
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
const CARemoteEndpoint_t *endpoint, const void *pdu,
- uint32_t size, void **retransmissionPdu);
+ uint32_t size);
/**
* @brief Stopping the retransmission context
- * @param context [IN]context for retransmission
+ * @param context [IN] context for retransmission
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionStop(CARetransmission_t *context);
/**
* @brief Terminating the retransmission context
- * @param context [IN]context for retransmission
+ * @param context [IN] context for retransmission
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionDestroy(CARetransmission_t *context);
#endif
#endif // __CA_RETRANSMISSION_H_
+
#define DEFAULT_RETRANSMISSION_COUNT 4
/** check period is 1 sec. **/
-#define RETRANSMISSION_CHECK_PERIOD 1000000
+#define RETRANSMISSION_CHECK_PERIOD_SEC 1
/** retransmission data send method type**/
-typedef CAResult_t (*CADataSendMethod_t)(const CARemoteEndpoint_t *endpoint, void *pdu,
- uint32_t size);
+typedef CAResult_t (*CADataSendMethod_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
+ uint32_t size);
/** retransmission timeout callback type**/
-typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, void *pdu,
+typedef void (*CATimeoutCallback_t)(const CARemoteEndpoint_t *endpoint, const void *pdu,
uint32_t size);
typedef struct
{
/** retransmission support connectivity type **/
CAConnectivityType_t supportType;
+
/** retransmission trying count **/
uint8_t tryingCount;
{
/** send method for retransmission data **/
CADataSendMethod_t dataSendMethod;
+
/** callback function for retransmit timeout **/
CATimeoutCallback_t timeoutCallback;
+
/** retransmission configure data **/
CARetransmissionConfig_t config;
+
/** Variable to inform the thread to stop **/
- CABool_t isStop;
+ bool isStop;
+
/** array list on which the thread is operating. **/
u_arraylist_t *dataList;
+
} CARetransmission_t;
#ifdef __cplusplus
/**
* @brief Initializes the retransmission context
- * @param context [IN] context for retransmission
- * @param handle [IN] thread pool handle
- * @param retransmissionSendMethod [IN] function to be called for retransmission
- * @param timeoutCallback [IN] callback for retransmit timeout
- * @param config [IN] configuration for retransmission.
+ * @param context [IN] context for retransmission
+ * @param retransmissionSendMethod [IN] function to be called for retransmission
+ * @param timeoutCallback [IN] callback for retransmit timeout
+ * @param config [IN] configuration for retransmission.
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionInitialize(CARetransmission_t *context,
CARetransmissionConfig_t *config);
/**
- * @brief Pass the sent pdu data. if retransmission process need, internal thread will wake up and
- * process the retransmission data.
+ * @brief Pass the sent pdu data. if retransmission process need, internal thread will wake up
+ * and process the retransmission data.
* @param context [IN] context for retransmission
* @param endpoint [IN] endpoint information
* @param pdu [IN] sent pdu binary data
/**
* @brief Paas the received pdu data. if received pdu is ACK data for the retransmission CON data,
- * the specified CON data will remove on retransmission list.
+ * the specified CON data will remove on retransmission list.
* @param context [IN] context for retransmission
* @param endpoint [IN] endpoint information
* @param pdu [IN] received pdu binary data
* @param size [IN] received pdu binary data size
- * @param void [OUT] pdu data of the request for reset and ack
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
const CARemoteEndpoint_t *endpoint, const void *pdu,
- uint32_t size, void **retransmissionPdu);
+ uint32_t size);
/**
* @brief Stopping the retransmission context
#endif
#endif // __CA_RETRANSMISSION_SINGLETHREAD_H_
+
* Abstraction Layer
* @param networkPacketCallback [IN] Callback to notify request and response messages from server(s)
* started at Connectivity Abstraction Layer.
- * @param netCallback [IN] Callback to intimate the network additions to Connectivity
+ * @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
* @param handle [IN] Threadpool Handle
* @return #CA_STATUS_OK or Appropriate error code
* connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Returns 0 on error.
+ * @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *endpoint, void *data,
+int32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the WIFI connectivity.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Returns 0 on error.
+ * @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLen);
+int32_t CASendWIFIMulticastData(const void *data, uint32_t dataLen);
/**
* @brief Get WIFI Connectivity network information
* Configuration information will be deleted from further use
* @return NONE
*/
-void CATerminateWIfI();
+void CATerminateWIFI();
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // #ifndef __CA_WIFI_ADAPTER_H__
+
* Abstraction Layer
* @param networkPacketCallback [IN] Callback to notify request and response messages from server(s)
* started at Connectivity Abstraction Layer.
- * @param netCallback [IN] Callback to intimate the network additions to Connectivity
+ * @param netCallback [IN] Callback to notify the network additions to Connectivity
* Abstraction Layer.
* @return #CA_STATUS_OK or Appropriate error code
*/
* connectivity type) to which the unicast data has to be sent.
* @param data [IN] Data to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return The number of bytes sent on the network. Returns 0 on error.
+ * @return The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *endpoint, void *data,
- uint32_t dataLen);
+int32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+ uint32_t dataLen);
/**
* @brief Sends Multicast data to the endpoint using the WIFI connectivity.
* @param data [IN] Data which required to be sent.
* @param dataLen [IN] Size of data to be sent.
- * @return - The number of bytes sent on the network. Returns 0 on error.
+ * @return - The number of bytes sent on the network. Returns -1 on error.
* @remarks dataLen must be > 0.
*/
-uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLen);
+int32_t CASendWIFIMulticastData(const void *data, uint32_t dataLen);
/**
* @brief Get WIFI Connectivity network information
* Configuration information will be deleted from further use
* @return NONE
*/
-void CATerminateWIfI();
+void CATerminateWIFI();
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // #ifndef __CA_WIFI_ADAPTER_SINGLETHREAD_H__
+
* @return NONE
* @pre Callback must be registered using CAWiFiSetPacketReceiveCallback()
*/
-typedef void (*CAWiFiPacketReceivedCallback)(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, const CABool_t isSecure);
+typedef void (*CAWiFiPacketReceivedCallback)(const char *ipAddress, uint16_t port,
+ const void *data, uint32_t dataLength, bool isSecure);
/**
* @brief Callback to be notified when exception occures on multicast/unicast server.
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD);
+ uint16_t multicastPort, int *serverFD);
/**
* @brief Start unicast server for specified local address and port
* @retval #CA_SERVER_STARTED_ALREADY Unicast server is already started and running.
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAWiFiStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, const CABool_t isSecured,
- int32_t *serverFD);
+CAResult_t CAWiFiStartUnicastServer(const char *localAddress, uint16_t *port,
+ bool forceStart, bool isSecured,
+ int *serverFD);
/**
* @brief Stop multicast server.
* @retval #CA_STATUS_FAILED Operation failed
* @remarks ipAddress must be freed using free().
*/
-CAResult_t CAWiFiGetUnicastServerInfo(const CABool_t isSecured, char **ipAddress, int16_t *port,
- int32_t *serverFD);
+CAResult_t CAWiFiGetUnicastServerInfo(bool isSecured, char **ipAddress, uint16_t *port,
+ int *serverFD);
/**
* @brief Set this callback for receiving data packets from peer devices.
* @param socketFD [IN] Socket descriptor used for sending UDP data.
* @return NONE
*/
-void CAWiFiSetUnicastSocket(const int32_t socketFD);
+void CAWiFiSetUnicastSocket(int socketFD);
#ifdef __WITH_DTLS__
/**
* @param socketFD [IN] Socket descriptor used for sending secured (encrypted) UDP data.
* @return NONE
*/
-void CAWiFiSetSecureUnicastSocket(const int32_t socketFD);
+void CAWiFiSetSecureUnicastSocket(int socketFD);
#endif
/**
* @return The number of bytes sent on the network. Returns 0 on error.
* @remarks isSecure will be ignored when isMulticast is true.
*/
-uint32_t CAWiFiSendData(const char *remoteAddress, const uint32_t port,
- const void *data, const uint32_t dataLength,
- CABool_t isMulticast, CABool_t isSecured);
+uint32_t CAWiFiSendData(const char *remoteAddress, uint16_t port,
+ const void *data, uint32_t dataLength,
+ bool isMulticast, bool isSecured);
/**
* @brief Callback to be notified when wifi adapter connection state changes.
* @pre Callback must be registered using CAWiFiSetConnectionStateChangeCallback()
*/
typedef void (*CAWiFiConnectionStateChangeCallback)(const char *ipAddress,
- const CANetworkStatus_t status);
+ CANetworkStatus_t status);
/**
* @brief Initialize Wifi network monitor
#endif
#endif //_CA_WIFI_INTERFACE_H_
+
* @return NONE
* @pre Callback must be registered using CAWiFiSetPacketReceiveCallback()
*/
-typedef void (*CAWiFiPacketReceivedCallback)(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength);
+typedef void (*CAWiFiPacketReceivedCallback)(const char *ipAddress, uint32_t port,
+ const void *data, uint32_t dataLength);
/**
* @brief Callback to be notified when exception occures on multicast/unicast server.
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD);
+ int16_t multicastPort, int *serverFD);
/**
* @brief Start unicast server for specified local address and port
* @retval #CA_STATUS_FAILED Operation failed
*/
CAResult_t CAWiFiStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, int32_t *serverFD);
+ bool forceStart, int *serverFD);
/**
* @brief Stop multicast server.
* @retval #CA_STATUS_FAILED Operation failed
* @remarks ipAddress must be freed using free().
*/
-CAResult_t CAWiFiGetUnicastServerInfo(char **ipAddress, int16_t *port, int32_t *serverFD);
+CAResult_t CAWiFiGetUnicastServerInfo(char **ipAddress, int16_t *port, int *serverFD);
/**
* @brief Set this callback for receiving data packets from peer devices.
* @param socketFD [IN] Socket descriptor used for sending UDP data.
* @return NONE
*/
-void CAWiFiSetUnicastSocket(const int32_t socketFD);
+void CAWiFiSetUnicastSocket(int socketFD);
#ifdef __WITH_DTLS__
/**
* @param socketFD [IN] Socket descriptor used for sending secured (encrypted) UDP data.
* @return NONE
*/
-void CAWiFiSetSecureUnicastSocket(const int32_t socketFD);
+void CAWiFiSetSecureUnicastSocket(int socketFD);
#endif
/**
*
* @return The number of bytes sent on the network. Returns 0 on error.
*/
-uint32_t CAWiFiSendData(const char *remoteAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, bool isMulticast);
+uint32_t CAWiFiSendData(const char *remoteAddress, uint32_t port,
+ const void *data, uint32_t dataLength, bool isMulticast);
/**
* @brief Callback to be notified when wifi adapter connection state changes.
* @pre Callback must be registered using CAWiFiSetConnectionStateChangeCallback()
*/
typedef void (*CAWiFiConnectionStateChangeCallback)(const char *ipAddress,
- const CANetworkStatus_t status);
+ CANetworkStatus_t status);
/**
* @brief Initialize Wifi network monitor
#endif
#endif //_CA_WIFI_INTERFACE_SINGLETHREAD_H_
+
+++ /dev/null
-/* DO NOT EDIT THIS FILE - it is machine generated */
-#include <jni.h>
-/* Header for class com_iotivity_jar_CAWiFiInterface */
-
-#ifndef _Included_com_iotivity_jar_CAWiFiInterface
-#define _Included_com_iotivity_jar_CAWiFiInterface
-#ifdef __cplusplus
-extern "C" {
-#endif
-/*
- * Class: com_iotivity_jar_CAWiFiInterface
- * Method: CAWiFiStateEnabled
- * Signature: ()V
- */
-JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CAWiFiInterface_CAWiFiStateEnabled
-(JNIEnv *, jclass);
-
-/*
- * Class: com_iotivity_jar_CAWiFiInterface
- * Method: CAWiFiStateDisabled
- * Signature: ()V
- */
-JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CAWiFiInterface_CAWiFiStateDisabled
-(JNIEnv *, jclass);
-
-#ifdef __cplusplus
-}
-#endif
-#endif
+ tempAddr += 3;
+ }
+ gLeAddress[BLE_ADDRESS_SIZE - 1] = '\0';
-+ Serial.println("LEAddress :");
++ Serial.println("LEAddress :");
+ Serial.println((char *)gLeAddress);
+ return;
+ }
#endif
+
+++ /dev/null
-External libs for arduino platform
-
-diff -rupN ./Ethernet/src/Ethernet.cpp ../../arduino-1.5.8/libraries/Ethernet/src/Ethernet.cpp
---- ./Ethernet/src/Ethernet.cpp 2014-10-01 20:45:35.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Ethernet/src/Ethernet.cpp 2014-12-12 16:39:26.000000000 +0530
-@@ -7,10 +7,11 @@ uint8_t EthernetClass::_state[MAX_SOCK_N
+diff -rupN ./libraries/Ethernet/src/Ethernet.cpp ./arduino-1.5.8/libraries/Ethernet/src/Ethernet.cpp
+--- ./libraries/Ethernet/src/Ethernet.cpp 2014-10-01 20:45:35.000000000 +0530
++++ ./arduino-1.5.8/libraries/Ethernet/src/Ethernet.cpp 2015-02-05 15:51:09.000000000 +0530
+@@ -7,10 +7,10 @@ uint8_t EthernetClass::_state[MAX_SOCK_N
0, 0, 0, 0 };
uint16_t EthernetClass::_server_port[MAX_SOCK_NUM] = {
0, 0, 0, 0 };
int EthernetClass::begin(uint8_t *mac_address)
{
- static DhcpClass s_dhcp;
-+ //static DhcpClass s_dhcp;
_dhcp = &s_dhcp;
-diff -rupN ./Ethernet/src/utility/socket.cpp ../../arduino-1.5.8/libraries/Ethernet/src/utility/socket.cpp
---- ./Ethernet/src/utility/socket.cpp 2014-10-01 20:45:35.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Ethernet/src/utility/socket.cpp 2014-12-17 17:02:20.000000000 +0530
+diff -rupN ./libraries/Ethernet/src/utility/socket.cpp ./arduino-1.5.8/libraries/Ethernet/src/utility/socket.cpp
+--- ./libraries/Ethernet/src/utility/socket.cpp 2014-10-01 20:45:35.000000000 +0530
++++ ./arduino-1.5.8/libraries/Ethernet/src/utility/socket.cpp 2015-02-05 15:55:18.000000000 +0530
@@ -295,6 +295,7 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
{
uint8_t head[8];
uint16_t ptr=0;
if ( len > 0 )
-@@ -316,10 +317,10 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+@@ -316,10 +317,6 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
data_len = head[6];
data_len = (data_len << 8) + head[7];
- W5100.read_data(s, ptr, buf, data_len); // data copy.
- ptr += data_len;
-+ //W5100.read_data(s, ptr, buf, data_len); // data copy.
-+ //ptr += data_len;
-
+-
- W5100.writeSnRX_RD(s, ptr);
-+ //W5100.writeSnRX_RD(s, ptr);
break;
case SnMR::IPRAW :
-@@ -333,10 +334,10 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+@@ -332,11 +329,6 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+ addr[3] = head[3];
data_len = head[4];
data_len = (data_len << 8) + head[5];
-
+-
- W5100.read_data(s, ptr, buf, data_len); // data copy.
- ptr += data_len;
-+ //W5100.read_data(s, ptr, buf, data_len); // data copy.
-+ //ptr += data_len;
-
+-
- W5100.writeSnRX_RD(s, ptr);
-+ //W5100.writeSnRX_RD(s, ptr);
break;
case SnMR::MACRAW:
-@@ -345,18 +346,25 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+@@ -344,19 +336,22 @@ uint16_t recvfrom(SOCKET s, uint8_t *buf
+ ptr+=2;
data_len = head[0];
data_len = (data_len<<8) + head[1] - 2;
-
+-
- W5100.read_data(s, ptr, buf, data_len);
- ptr += data_len;
- W5100.writeSnRX_RD(s, ptr);
-+ //W5100.read_data(s, ptr, buf, data_len);
-+ //ptr += data_len;
-+ //W5100.writeSnRX_RD(s, ptr);
break;
default :
}
/**
-diff -rupN ./Time/Time/DateStrings.cpp ../../arduino-1.5.8/libraries/Time/Time/DateStrings.cpp
---- ./Time/Time/DateStrings.cpp 2010-03-06 11:09:22.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/DateStrings.cpp 2013-03-24 00:28:08.000000000 +0530
-@@ -1,80 +1,90 @@
--/* DateStrings.cpp
-- * Definitions for date strings for use with the Time library
-- *
-- * No memory is consumed in the sketch if your code does not call any of the string methods
-- * You can change the text of the strings, make sure the short strings are each exactly 3 characters
-- * the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in Time.h
-- *
-- */
+diff -rupN ./libraries/Time/Time/DateStrings.cpp ./arduino-1.5.8/libraries/Time/Time/DateStrings.cpp
+--- ./libraries/Time/Time/DateStrings.cpp 2010-03-06 11:09:22.000000000 +0530
++++ ./arduino-1.5.8/libraries/Time/Time/DateStrings.cpp 2015-02-05 16:35:01.000000000 +0530
+@@ -6,8 +6,18 @@
+ * the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in Time.h
+ *
+ */
-
-#include <avr/pgmspace.h>
--#include "Time.h"
--
--// the short strings for each day or month must be exactly dt_SHORT_STR_LEN
--#define dt_SHORT_STR_LEN 3 // the length of short strings
--
--static char buffer[dt_MAX_STRING_LEN+1]; // must be big enough for longest string and the terminating null
--
--char monthStr1[] PROGMEM = "January";
--char monthStr2[] PROGMEM = "February";
--char monthStr3[] PROGMEM = "March";
--char monthStr4[] PROGMEM = "April";
--char monthStr5[] PROGMEM = "May";
--char monthStr6[] PROGMEM = "June";
--char monthStr7[] PROGMEM = "July";
--char monthStr8[] PROGMEM = "August";
--char monthStr9[] PROGMEM = "September";
--char monthStr10[] PROGMEM = "October";
--char monthStr11[] PROGMEM = "November";
--char monthStr12[] PROGMEM = "December";
--
--PGM_P monthNames_P[] PROGMEM =
--{
-- "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6,
-- monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12
--};
--
--char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";
--
--char dayStr0[] PROGMEM = "Err";
--char dayStr1[] PROGMEM = "Sunday";
--char dayStr2[] PROGMEM = "Monday";
--char dayStr3[] PROGMEM = "Tuesday";
--char dayStr4[] PROGMEM = "Wednesday";
--char dayStr5[] PROGMEM = "Thursday";
--char dayStr6[] PROGMEM = "Friday";
--char dayStr7[] PROGMEM = "Saturday";
--
--PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
--char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
--
--/* functions to return date strings */
--
--char* monthStr(uint8_t month)
--{
-- strcpy_P(buffer, (PGM_P)pgm_read_word(&(monthNames_P[month])));
-- return buffer;
--}
--
--char* monthShortStr(uint8_t month)
--{
-- for (int i=0; i < dt_SHORT_STR_LEN; i++)
-- buffer[i] = pgm_read_byte(&(monthShortNames_P[i+ (month*dt_SHORT_STR_LEN)]));
-- buffer[dt_SHORT_STR_LEN] = 0;
-- return buffer;
--}
--
--char* dayStr(uint8_t day)
--{
-- strcpy_P(buffer, (PGM_P)pgm_read_word(&(dayNames_P[day])));
-- return buffer;
--}
--
--char* dayShortStr(uint8_t day)
--{
-- uint8_t index = day*dt_SHORT_STR_LEN;
-- for (int i=0; i < dt_SHORT_STR_LEN; i++)
-- buffer[i] = pgm_read_byte(&(dayShortNames_P[index + i]));
-- buffer[dt_SHORT_STR_LEN] = 0;
-- return buffer;
--}
-+/* DateStrings.cpp
-+ * Definitions for date strings for use with the Time library
-+ *
-+ * No memory is consumed in the sketch if your code does not call any of the string methods
-+ * You can change the text of the strings, make sure the short strings are each exactly 3 characters
-+ * the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in Time.h
-+ *
-+ */
+
+#if defined(__AVR__)
+#include <avr/pgmspace.h>
+#define strcpy_P(dest, src) strcpy((dest), (src))
+#endif
+#include <string.h> // for strcpy_P or strcpy
-+#include "Time.h"
-+
-+// the short strings for each day or month must be exactly dt_SHORT_STR_LEN
-+#define dt_SHORT_STR_LEN 3 // the length of short strings
-+
-+static char buffer[dt_MAX_STRING_LEN+1]; // must be big enough for longest string and the terminating null
-+
+ #include "Time.h"
+
+ // the short strings for each day or month must be exactly dt_SHORT_STR_LEN
+@@ -15,38 +25,38 @@
+
+ static char buffer[dt_MAX_STRING_LEN+1]; // must be big enough for longest string and the terminating null
+
+-char monthStr1[] PROGMEM = "January";
+-char monthStr2[] PROGMEM = "February";
+-char monthStr3[] PROGMEM = "March";
+-char monthStr4[] PROGMEM = "April";
+-char monthStr5[] PROGMEM = "May";
+-char monthStr6[] PROGMEM = "June";
+-char monthStr7[] PROGMEM = "July";
+-char monthStr8[] PROGMEM = "August";
+-char monthStr9[] PROGMEM = "September";
+-char monthStr10[] PROGMEM = "October";
+-char monthStr11[] PROGMEM = "November";
+-char monthStr12[] PROGMEM = "December";
+const char monthStr1[] PROGMEM = "January";
+const char monthStr2[] PROGMEM = "February";
+const char monthStr3[] PROGMEM = "March";
+const char monthStr10[] PROGMEM = "October";
+const char monthStr11[] PROGMEM = "November";
+const char monthStr12[] PROGMEM = "December";
-+
-+PGM_P monthNames_P[] PROGMEM =
-+{
-+ "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6,
-+ monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12
-+};
-+
+
+-PGM_P monthNames_P[] PROGMEM =
++PGM_P const monthNames_P[] PROGMEM =
+ {
+ "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6,
+ monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12
+ };
+
+-char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";
+const char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";
-+
+
+-char dayStr0[] PROGMEM = "Err";
+-char dayStr1[] PROGMEM = "Sunday";
+-char dayStr2[] PROGMEM = "Monday";
+-char dayStr3[] PROGMEM = "Tuesday";
+-char dayStr4[] PROGMEM = "Wednesday";
+-char dayStr5[] PROGMEM = "Thursday";
+-char dayStr6[] PROGMEM = "Friday";
+-char dayStr7[] PROGMEM = "Saturday";
+const char dayStr0[] PROGMEM = "Err";
+const char dayStr1[] PROGMEM = "Sunday";
+const char dayStr2[] PROGMEM = "Monday";
+const char dayStr5[] PROGMEM = "Thursday";
+const char dayStr6[] PROGMEM = "Friday";
+const char dayStr7[] PROGMEM = "Saturday";
-+
-+PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
-+char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
-+
-+/* functions to return date strings */
-+
-+char* monthStr(uint8_t month)
-+{
-+ strcpy_P(buffer, (PGM_P)pgm_read_word(&(monthNames_P[month])));
-+ return buffer;
-+}
-+
-+char* monthShortStr(uint8_t month)
-+{
-+ for (int i=0; i < dt_SHORT_STR_LEN; i++)
-+ buffer[i] = pgm_read_byte(&(monthShortNames_P[i+ (month*dt_SHORT_STR_LEN)]));
-+ buffer[dt_SHORT_STR_LEN] = 0;
-+ return buffer;
-+}
-+
-+char* dayStr(uint8_t day)
-+{
-+ strcpy_P(buffer, (PGM_P)pgm_read_word(&(dayNames_P[day])));
-+ return buffer;
-+}
-+
-+char* dayShortStr(uint8_t day)
-+{
-+ uint8_t index = day*dt_SHORT_STR_LEN;
-+ for (int i=0; i < dt_SHORT_STR_LEN; i++)
-+ buffer[i] = pgm_read_byte(&(dayShortNames_P[index + i]));
-+ buffer[dt_SHORT_STR_LEN] = 0;
-+ return buffer;
-+}
-diff -rupN ./Time/Time/examples/Processing/SyncArduinoClock/readme.txt ../../arduino-1.5.8/libraries/Time/Time/examples/Processing/SyncArduinoClock/readme.txt
---- ./Time/Time/examples/Processing/SyncArduinoClock/readme.txt 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/Processing/SyncArduinoClock/readme.txt 2013-03-28 07:20:13.000000000 +0530
-@@ -0,0 +1,9 @@
-+SyncArduinoClock is a Processing sketch that responds to Arduino requests for
-+time synchronization messages.
-+
-+The portIndex must be set the Serial port connected to Arduino.
-+
-+Download TimeSerial.pde onto Arduino and you should see the time
-+message displayed when you run SyncArduinoClock in Processing.
-+The Arduino time is set from the time on your computer through the
-+Processing sketch.
-diff -rupN ./Time/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde ../../arduino-1.5.8/libraries/Time/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde
---- ./Time/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde 2013-03-28 08:26:26.000000000 +0530
-@@ -0,0 +1,78 @@
-+/**
-+ * SyncArduinoClock.
-+ *
-+ * portIndex must be set to the port connected to the Arduino
-+ *
-+ * The current time is sent in response to request message from Arduino
-+ * or by clicking the display window
-+ *
-+ * The time message is 11 ASCII text characters; a header (the letter 'T')
-+ * followed by the ten digit system time (unix time)
-+ */
-+
-+
-+import processing.serial.*;
-+import java.util.Date;
-+import java.util.Calendar;
-+import java.util.GregorianCalendar;
-+
-+public static final short portIndex = 0; // select the com port, 0 is the first port
-+public static final String TIME_HEADER = "T"; //header for arduino serial time message
-+public static final char TIME_REQUEST = 7; // ASCII bell character
-+public static final char LF = 10; // ASCII linefeed
-+public static final char CR = 13; // ASCII linefeed
-+Serial myPort; // Create object from Serial class
-+
-+void setup() {
-+ size(200, 200);
-+ println(Serial.list());
-+ println(" Connecting to -> " + Serial.list()[portIndex]);
-+ myPort = new Serial(this,Serial.list()[portIndex], 9600);
-+ println(getTimeNow());
-+}
-+
-+void draw()
-+{
-+ textSize(20);
-+ textAlign(CENTER);
-+ fill(0);
-+ text("Click to send\nTime Sync", 0, 75, 200, 175);
-+ if ( myPort.available() > 0) { // If data is available,
-+ char val = char(myPort.read()); // read it and store it in val
-+ if(val == TIME_REQUEST){
-+ long t = getTimeNow();
-+ sendTimeMessage(TIME_HEADER, t);
-+ }
-+ else
-+ {
-+ if(val == LF)
-+ ; //igonore
-+ else if(val == CR)
-+ println();
-+ else
-+ print(val); // echo everying but time request
-+ }
-+ }
-+}
-+
-+void mousePressed() {
-+ sendTimeMessage( TIME_HEADER, getTimeNow());
-+}
-+
-+
-+void sendTimeMessage(String header, long time) {
-+ String timeStr = String.valueOf(time);
-+ myPort.write(header); // send header and time to arduino
-+ myPort.write(timeStr);
-+ myPort.write('\n');
-+}
-+
-+long getTimeNow(){
-+ // java time is in ms, we want secs
-+ Date d = new Date();
-+ Calendar cal = new GregorianCalendar();
-+ long current = d.getTime()/1000;
-+ long timezone = cal.get(cal.ZONE_OFFSET)/1000;
-+ long daylight = cal.get(cal.DST_OFFSET)/1000;
-+ return current + timezone + daylight;
-+}
-diff -rupN ./Time/Time/examples/TimeArduinoDue/TimeArduinoDue.ino ../../arduino-1.5.8/libraries/Time/Time/examples/TimeArduinoDue/TimeArduinoDue.ino
---- ./Time/Time/examples/TimeArduinoDue/TimeArduinoDue.ino 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeArduinoDue/TimeArduinoDue.ino 2013-03-28 06:08:18.000000000 +0530
-@@ -0,0 +1,69 @@
-+/*
-+ * TimeRTC.pde
-+ * example code illustrating Time library with Real Time Clock.
-+ *
-+ * This example requires Markus Lange's Arduino Due RTC Library
-+ * https://github.com/MarkusLange/Arduino-Due-RTC-Library
-+ */
-+
-+#include <Time.h>
-+#include <rtc_clock.h>
-+
-+// Select the Slowclock source
-+//RTC_clock rtc_clock(RC);
-+RTC_clock rtc_clock(XTAL);
-+
-+void setup() {
-+ Serial.begin(9600);
-+ rtc_clock.init();
-+ if (rtc_clock.date_already_set() == 0) {
-+ // Unfortunately, the Arduino Due hardware does not seem to
-+ // be designed to maintain the RTC clock state when the
-+ // board resets. Markus described it thusly: "Uhh the Due
-+ // does reset with the NRSTB pin. This resets the full chip
-+ // with all backup regions including RTC, RTT and SC. Only
-+ // if the reset is done with the NRST pin will these regions
-+ // stay with their old values."
-+ rtc_clock.set_time(__TIME__);
-+ rtc_clock.set_date(__DATE__);
-+ }
-+ setSyncProvider(getArduinoDueTime);
-+ if(timeStatus()!= timeSet)
-+ Serial.println("Unable to sync with the RTC");
-+ else
-+ Serial.println("RTC has set the system time");
-+}
-+
-+time_t getArduinoDueTime()
-+{
-+ return rtc_clock.unixtime();
-+}
-+
-+void loop()
-+{
-+ digitalClockDisplay();
-+ delay(1000);
-+}
-+
-+void digitalClockDisplay(){
-+ // digital clock display of the time
-+ Serial.print(hour());
-+ printDigits(minute());
-+ printDigits(second());
-+ Serial.print(" ");
-+ Serial.print(day());
-+ Serial.print(" ");
-+ Serial.print(month());
-+ Serial.print(" ");
-+ Serial.print(year());
-+ Serial.println();
-+}
-+
-+void printDigits(int digits){
-+ // utility function for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-diff -rupN ./Time/Time/examples/TimeGPS/TimeGPS.ino ../../arduino-1.5.8/libraries/Time/Time/examples/TimeGPS/TimeGPS.ino
---- ./Time/Time/examples/TimeGPS/TimeGPS.ino 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeGPS/TimeGPS.ino 2013-03-31 01:18:40.000000000 +0530
-@@ -0,0 +1,87 @@
-+/*
-+ * TimeGPS.pde
-+ * example code illustrating time synced from a GPS
-+ *
-+ */
-+
-+#include <Time.h>
-+#include <TinyGPS.h> // http://arduiniana.org/libraries/TinyGPS/
-+#include <SoftwareSerial.h>
-+// TinyGPS and SoftwareSerial libraries are the work of Mikal Hart
-+
-+SoftwareSerial SerialGPS = SoftwareSerial(10, 11); // receive on pin 10
-+TinyGPS gps;
-+
-+// To use a hardware serial port, which is far more efficient than
-+// SoftwareSerial, uncomment this line and remove SoftwareSerial
-+//#define SerialGPS Serial1
-+
-+// Offset hours from gps time (UTC)
-+const int offset = 1; // Central European Time
-+//const int offset = -5; // Eastern Standard Time (USA)
-+//const int offset = -4; // Eastern Daylight Time (USA)
-+//const int offset = -8; // Pacific Standard Time (USA)
-+//const int offset = -7; // Pacific Daylight Time (USA)
-+
-+// Ideally, it should be possible to learn the time zone
-+// based on the GPS position data. However, that would
-+// require a complex library, probably incorporating some
-+// sort of database using Eric Muller's time zone shape
-+// maps, at http://efele.net/maps/tz/
-+
-+time_t prevDisplay = 0; // when the digital clock was displayed
-+
-+void setup()
-+{
-+ Serial.begin(9600);
-+ while (!Serial) ; // Needed for Leonardo only
-+ SerialGPS.begin(4800);
-+ Serial.println("Waiting for GPS time ... ");
-+}
-+
-+void loop()
-+{
-+ while (SerialGPS.available()) {
-+ if (gps.encode(SerialGPS.read())) { // process gps messages
-+ // when TinyGPS reports new data...
-+ unsigned long age;
-+ int Year;
-+ byte Month, Day, Hour, Minute, Second;
-+ gps.crack_datetime(&Year, &Month, &Day, &Hour, &Minute, &Second, NULL, &age);
-+ if (age < 500) {
-+ // set the Time to the latest GPS reading
-+ setTime(Hour, Minute, Second, Day, Month, Year);
-+ adjustTime(offset * SECS_PER_HOUR);
-+ }
-+ }
-+ }
-+ if (timeStatus()!= timeNotSet) {
-+ if (now() != prevDisplay) { //update the display only if the time has changed
-+ prevDisplay = now();
-+ digitalClockDisplay();
-+ }
-+ }
-+}
-+
-+void digitalClockDisplay(){
-+ // digital clock display of the time
-+ Serial.print(hour());
-+ printDigits(minute());
-+ printDigits(second());
-+ Serial.print(" ");
-+ Serial.print(day());
-+ Serial.print(" ");
-+ Serial.print(month());
-+ Serial.print(" ");
-+ Serial.print(year());
-+ Serial.println();
-+}
-+
-+void printDigits(int digits) {
-+ // utility function for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-diff -rupN ./Time/Time/examples/TimeNTP/TimeNTP.ino ../../arduino-1.5.8/libraries/Time/Time/examples/TimeNTP/TimeNTP.ino
---- ./Time/Time/examples/TimeNTP/TimeNTP.ino 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeNTP/TimeNTP.ino 2013-03-31 01:19:07.000000000 +0530
-@@ -0,0 +1,135 @@
-+/*
-+ * Time_NTP.pde
-+ * Example showing time sync to NTP time source
-+ *
-+ * This sketch uses the Ethernet library
-+ */
-+
-+#include <Time.h>
-+#include <Ethernet.h>
-+#include <EthernetUdp.h>
-+#include <SPI.h>
-+
-+byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-+// NTP Servers:
-+IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
-+// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
-+// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov
-+
-+
-+const int timeZone = 1; // Central European Time
-+//const int timeZone = -5; // Eastern Standard Time (USA)
-+//const int timeZone = -4; // Eastern Daylight Time (USA)
-+//const int timeZone = -8; // Pacific Standard Time (USA)
-+//const int timeZone = -7; // Pacific Daylight Time (USA)
-+
-+
-+EthernetUDP Udp;
-+unsigned int localPort = 8888; // local port to listen for UDP packets
-+
-+void setup()
-+{
-+ Serial.begin(9600);
-+ while (!Serial) ; // Needed for Leonardo only
-+ delay(250);
-+ Serial.println("TimeNTP Example");
-+ if (Ethernet.begin(mac) == 0) {
-+ // no point in carrying on, so do nothing forevermore:
-+ while (1) {
-+ Serial.println("Failed to configure Ethernet using DHCP");
-+ delay(10000);
-+ }
-+ }
-+ Serial.print("IP number assigned by DHCP is ");
-+ Serial.println(Ethernet.localIP());
-+ Udp.begin(localPort);
-+ Serial.println("waiting for sync");
-+ setSyncProvider(getNtpTime);
-+}
-+
-+time_t prevDisplay = 0; // when the digital clock was displayed
-+
-+void loop()
-+{
-+ if (timeStatus() != timeNotSet) {
-+ if (now() != prevDisplay) { //update the display only if time has changed
-+ prevDisplay = now();
-+ digitalClockDisplay();
-+ }
-+ }
-+}
-+
-+void digitalClockDisplay(){
-+ // digital clock display of the time
-+ Serial.print(hour());
-+ printDigits(minute());
-+ printDigits(second());
-+ Serial.print(" ");
-+ Serial.print(day());
-+ Serial.print(" ");
-+ Serial.print(month());
-+ Serial.print(" ");
-+ Serial.print(year());
-+ Serial.println();
-+}
-+
-+void printDigits(int digits){
-+ // utility for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-+/*-------- NTP code ----------*/
-+
-+const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
-+byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
-+
-+time_t getNtpTime()
-+{
-+ while (Udp.parsePacket() > 0) ; // discard any previously received packets
-+ Serial.println("Transmit NTP Request");
-+ sendNTPpacket(timeServer);
-+ uint32_t beginWait = millis();
-+ while (millis() - beginWait < 1500) {
-+ int size = Udp.parsePacket();
-+ if (size >= NTP_PACKET_SIZE) {
-+ Serial.println("Receive NTP Response");
-+ Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
-+ unsigned long secsSince1900;
-+ // convert four bytes starting at location 40 to a long integer
-+ secsSince1900 = (unsigned long)packetBuffer[40] << 24;
-+ secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
-+ secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
-+ secsSince1900 |= (unsigned long)packetBuffer[43];
-+ return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
-+ }
-+ }
-+ Serial.println("No NTP Response :-(");
-+ return 0; // return 0 if unable to get the time
-+}
-+
-+// send an NTP request to the time server at the given address
-+void sendNTPpacket(IPAddress &address)
-+{
-+ // set all bytes in the buffer to 0
-+ memset(packetBuffer, 0, NTP_PACKET_SIZE);
-+ // Initialize values needed to form NTP request
-+ // (see URL above for details on the packets)
-+ packetBuffer[0] = 0b11100011; // LI, Version, Mode
-+ packetBuffer[1] = 0; // Stratum, or type of clock
-+ packetBuffer[2] = 6; // Polling Interval
-+ packetBuffer[3] = 0xEC; // Peer Clock Precision
-+ // 8 bytes of zero for Root Delay & Root Dispersion
-+ packetBuffer[12] = 49;
-+ packetBuffer[13] = 0x4E;
-+ packetBuffer[14] = 49;
-+ packetBuffer[15] = 52;
-+ // all NTP fields have been given values, now
-+ // you can send a packet requesting a timestamp:
-+ Udp.beginPacket(address, 123); //NTP requests are to port 123
-+ Udp.write(packetBuffer, NTP_PACKET_SIZE);
-+ Udp.endPacket();
-+}
-+
-diff -rupN ./Time/Time/examples/TimeRTC/TimeRTC.pde ../../arduino-1.5.8/libraries/Time/Time/examples/TimeRTC/TimeRTC.pde
---- ./Time/Time/examples/TimeRTC/TimeRTC.pde 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeRTC/TimeRTC.pde 2013-03-24 10:27:58.000000000 +0530
-@@ -0,0 +1,55 @@
-+/*
-+ * TimeRTC.pde
-+ * example code illustrating Time library with Real Time Clock.
-+ *
-+ */
-+
-+#include <Time.h>
-+#include <Wire.h>
-+#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
-+
-+void setup() {
-+ Serial.begin(9600);
-+ while (!Serial) ; // wait until Arduino Serial Monitor opens
-+ setSyncProvider(RTC.get); // the function to get the time from the RTC
-+ if(timeStatus()!= timeSet)
-+ Serial.println("Unable to sync with the RTC");
-+ else
-+ Serial.println("RTC has set the system time");
-+}
-+
-+void loop()
-+{
-+ if (timeStatus() == timeSet) {
-+ digitalClockDisplay();
-+ } else {
-+ Serial.println("The time has not been set. Please run the Time");
-+ Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
-+ Serial.println();
-+ delay(4000);
-+ }
-+ delay(1000);
-+}
-+
-+void digitalClockDisplay(){
-+ // digital clock display of the time
-+ Serial.print(hour());
-+ printDigits(minute());
-+ printDigits(second());
-+ Serial.print(" ");
-+ Serial.print(day());
-+ Serial.print(" ");
-+ Serial.print(month());
-+ Serial.print(" ");
-+ Serial.print(year());
-+ Serial.println();
-+}
-+
-+void printDigits(int digits){
-+ // utility function for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-diff -rupN ./Time/Time/examples/TimeRTCLog/TimeRTCLog.pde ../../arduino-1.5.8/libraries/Time/Time/examples/TimeRTCLog/TimeRTCLog.pde
---- ./Time/Time/examples/TimeRTCLog/TimeRTCLog.pde 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeRTCLog/TimeRTCLog.pde 2013-03-24 14:52:52.000000000 +0530
-@@ -0,0 +1,107 @@
-+/*
-+ * TimeRTCLogger.pde
-+ * example code illustrating adding and subtracting Time.
-+ *
-+ * this sketch logs pin state change events
-+ * the time of the event and time since the previous event is calculated and sent to the serial port.
-+ */
-+
-+#include <Time.h>
-+#include <Wire.h>
-+#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
-+
-+const int nbrInputPins = 6; // monitor 6 digital pins
-+const int inputPins[nbrInputPins] = {2,3,4,5,6,7}; // pins to monitor
-+boolean state[nbrInputPins] ; // the state of the monitored pins
-+time_t prevEventTime[nbrInputPins] ; // the time of the previous event
-+
-+void setup() {
-+ Serial.begin(9600);
-+ setSyncProvider(RTC.get); // the function to sync the time from the RTC
-+ for(int i=0; i < nbrInputPins; i++){
-+ pinMode( inputPins[i], INPUT);
-+ // uncomment these lines if pull-up resistors are wanted
-+ // pinMode( inputPins[i], INPUT_PULLUP);
-+ // state[i] = HIGH;
-+ }
-+}
-+
-+void loop()
-+{
-+ for(int i=0; i < nbrInputPins; i++)
-+ {
-+ boolean val = digitalRead(inputPins[i]);
-+ if(val != state[i])
-+ {
-+ time_t duration = 0; // the time since the previous event
-+ state[i] = val;
-+ time_t timeNow = now();
-+ if(prevEventTime[i] > 0)
-+ // if this was not the first state change, calculate the time from the previous change
-+ duration = duration = timeNow - prevEventTime[i];
-+ logEvent(inputPins[i], val, timeNow, duration ); // log the event
-+ prevEventTime[i] = timeNow; // store the time for this event
-+ }
-+ }
-+}
-+
-+void logEvent( int pin, boolean state, time_t timeNow, time_t duration)
-+{
-+ Serial.print("Pin ");
-+ Serial.print(pin);
-+ if( state == HIGH)
-+ Serial.print(" went High at ");
-+ else
-+ Serial.print(" went Low at ");
-+ showTime(timeNow);
-+ if(duration > 0){
-+ // only display duration if greater than 0
-+ Serial.print(", Duration was ");
-+ showDuration(duration);
-+ }
-+ Serial.println();
-+}
-+
-+
-+void showTime(time_t t){
-+ // display the given time
-+ Serial.print(hour(t));
-+ printDigits(minute(t));
-+ printDigits(second(t));
-+ Serial.print(" ");
-+ Serial.print(day(t));
-+ Serial.print(" ");
-+ Serial.print(month(t));
-+ Serial.print(" ");
-+ Serial.print(year(t));
-+}
-+
-+void printDigits(int digits){
-+ // utility function for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-+void showDuration(time_t duration){
-+// prints the duration in days, hours, minutes and seconds
-+ if(duration >= SECS_PER_DAY){
-+ Serial.print(duration / SECS_PER_DAY);
-+ Serial.print(" day(s) ");
-+ duration = duration % SECS_PER_DAY;
-+ }
-+ if(duration >= SECS_PER_HOUR){
-+ Serial.print(duration / SECS_PER_HOUR);
-+ Serial.print(" hour(s) ");
-+ duration = duration % SECS_PER_HOUR;
-+ }
-+ if(duration >= SECS_PER_MIN){
-+ Serial.print(duration / SECS_PER_MIN);
-+ Serial.print(" minute(s) ");
-+ duration = duration % SECS_PER_MIN;
-+ }
-+ Serial.print(duration);
-+ Serial.print(" second(s) ");
-+}
-+
-diff -rupN ./Time/Time/examples/TimeRTCSet/TimeRTCSet.ino ../../arduino-1.5.8/libraries/Time/Time/examples/TimeRTCSet/TimeRTCSet.ino
---- ./Time/Time/examples/TimeRTCSet/TimeRTCSet.ino 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeRTCSet/TimeRTCSet.ino 2013-03-31 01:19:58.000000000 +0530
-@@ -0,0 +1,80 @@
-+/*
-+ * TimeRTCSet.pde
-+ * example code illustrating Time library with Real Time Clock.
-+ *
-+ * RTC clock is set in response to serial port time message
-+ * A Processing example sketch to set the time is included in the download
-+ * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
-+ */
-+
-+#include <Time.h>
-+#include <Wire.h>
-+#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
-+
-+
-+void setup() {
-+ Serial.begin(9600);
-+ while (!Serial) ; // Needed for Leonardo only
-+ setSyncProvider(RTC.get); // the function to get the time from the RTC
-+ if (timeStatus() != timeSet)
-+ Serial.println("Unable to sync with the RTC");
-+ else
-+ Serial.println("RTC has set the system time");
-+}
-+
-+void loop()
-+{
-+ if (Serial.available()) {
-+ time_t t = processSyncMessage();
-+ if (t != 0) {
-+ RTC.set(t); // set the RTC and the system time to the received value
-+ setTime(t);
-+ }
-+ }
-+ digitalClockDisplay();
-+ delay(1000);
-+}
-+
-+void digitalClockDisplay(){
-+ // digital clock display of the time
-+ Serial.print(hour());
-+ printDigits(minute());
-+ printDigits(second());
-+ Serial.print(" ");
-+ Serial.print(day());
-+ Serial.print(" ");
-+ Serial.print(month());
-+ Serial.print(" ");
-+ Serial.print(year());
-+ Serial.println();
-+}
-+
-+void printDigits(int digits){
-+ // utility function for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-+/* code to process time sync messages from the serial port */
-+#define TIME_HEADER "T" // Header tag for serial time sync message
-+
-+unsigned long processSyncMessage() {
-+ unsigned long pctime = 0L;
-+ const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
-+
-+ if(Serial.find(TIME_HEADER)) {
-+ pctime = Serial.parseInt();
-+ return pctime;
-+ if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
-+ pctime = 0L; // return 0 to indicate that the time is not valid
-+ }
-+ }
-+ return pctime;
-+}
-+
-+
-+
-+
-+
-diff -rupN ./Time/Time/examples/TimeSerial/TimeSerial.ino ../../arduino-1.5.8/libraries/Time/Time/examples/TimeSerial/TimeSerial.ino
---- ./Time/Time/examples/TimeSerial/TimeSerial.ino 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeSerial/TimeSerial.ino 2013-03-31 01:20:31.000000000 +0530
-@@ -0,0 +1,81 @@
-+/*
-+ * TimeSerial.pde
-+ * example code illustrating Time library set through serial port messages.
-+ *
-+ * Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970)
-+ * you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2013
-+ T1357041600
-+ *
-+ * A Processing example sketch to automatically send the messages is inclided in the download
-+ * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
-+ */
-+
-+#include <Time.h>
-+
-+#define TIME_HEADER "T" // Header tag for serial time sync message
-+#define TIME_REQUEST 7 // ASCII bell character requests a time sync message
-+
-+void setup() {
-+ Serial.begin(9600);
-+ while (!Serial) ; // Needed for Leonardo only
-+ pinMode(13, OUTPUT);
-+ setSyncProvider( requestSync); //set function to call when sync required
-+ Serial.println("Waiting for sync message");
-+}
-+
-+void loop(){
-+ if (Serial.available()) {
-+ processSyncMessage();
-+ }
-+ if (timeStatus()!= timeNotSet) {
-+ digitalClockDisplay();
-+ }
-+ if (timeStatus() == timeSet) {
-+ digitalWrite(13, HIGH); // LED on if synced
-+ } else {
-+ digitalWrite(13, LOW); // LED off if needs refresh
-+ }
-+ delay(1000);
-+}
-+
-+void digitalClockDisplay(){
-+ // digital clock display of the time
-+ Serial.print(hour());
-+ printDigits(minute());
-+ printDigits(second());
-+ Serial.print(" ");
-+ Serial.print(day());
-+ Serial.print(" ");
-+ Serial.print(month());
-+ Serial.print(" ");
-+ Serial.print(year());
-+ Serial.println();
-+}
-+
-+void printDigits(int digits){
-+ // utility function for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-+
-+void processSyncMessage() {
-+ unsigned long pctime;
-+ const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
-+
-+ if(Serial.find(TIME_HEADER)) {
-+ pctime = Serial.parseInt();
-+ if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
-+ setTime(pctime); // Sync Arduino clock to the time received on the serial port
-+ }
-+ }
-+}
-+
-+time_t requestSync()
-+{
-+ Serial.write(TIME_REQUEST);
-+ return 0; // the time will be sent later in response to serial mesg
-+}
-+
-diff -rupN ./Time/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino ../../arduino-1.5.8/libraries/Time/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino
---- ./Time/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino 2013-03-31 01:21:31.000000000 +0530
-@@ -0,0 +1,110 @@
-+/*
-+ * TimeSerialDateStrings.pde
-+ * example code illustrating Time library date strings
-+ *
-+ * This sketch adds date string functionality to TimeSerial sketch
-+ * Also shows how to handle different messages
-+ *
-+ * A message starting with a time header sets the time
-+ * A Processing example sketch to automatically send the messages is inclided in the download
-+ * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
-+ *
-+ * A message starting with a format header sets the date format
-+ *
-+ * send: Fs\n for short date format
-+ * send: Fl\n for long date format
-+ */
-+
-+#include <Time.h>
-+
-+// single character message tags
-+#define TIME_HEADER 'T' // Header tag for serial time sync message
-+#define FORMAT_HEADER 'F' // Header tag indicating a date format message
-+#define FORMAT_SHORT 's' // short month and day strings
-+#define FORMAT_LONG 'l' // (lower case l) long month and day strings
-+
-+#define TIME_REQUEST 7 // ASCII bell character requests a time sync message
-+
-+static boolean isLongFormat = true;
-+
-+void setup() {
-+ Serial.begin(9600);
-+ while (!Serial) ; // Needed for Leonardo only
-+ setSyncProvider( requestSync); //set function to call when sync required
-+ Serial.println("Waiting for sync message");
-+}
-+
-+void loop(){
-+ if (Serial.available()) {
-+ char c = Serial.read();
-+ if( c == TIME_HEADER) {
-+ processSyncMessage();
-+ }
-+ else if( c== FORMAT_HEADER) {
-+ processFormatMessage();
-+ }
-+ }
-+ if (timeStatus()!= timeNotSet) {
-+ digitalClockDisplay();
-+ }
-+ delay(1000);
-+}
-+
-+void digitalClockDisplay(){
-+ // digital clock display of the time
-+ Serial.print(hour());
-+ printDigits(minute());
-+ printDigits(second());
-+ Serial.print(" ");
-+ if(isLongFormat)
-+ Serial.print(dayStr(weekday()));
-+ else
-+ Serial.print(dayShortStr(weekday()));
-+ Serial.print(" ");
-+ Serial.print(day());
-+ Serial.print(" ");
-+ if(isLongFormat)
-+ Serial.print(monthStr(month()));
-+ else
-+ Serial.print(monthShortStr(month()));
-+ Serial.print(" ");
-+ Serial.print(year());
-+ Serial.println();
-+}
-+
-+void printDigits(int digits){
-+ // utility function for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-+void processFormatMessage() {
-+ char c = Serial.read();
-+ if( c == FORMAT_LONG){
-+ isLongFormat = true;
-+ Serial.println("Setting long format");
-+ }
-+ else if( c == FORMAT_SHORT){
-+ isLongFormat = false;
-+ Serial.println("Setting short format");
-+ }
-+}
-+
-+void processSyncMessage() {
-+ unsigned long pctime;
-+ const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 - paul, perhaps we define in time.h?
-+
-+ pctime = Serial.parseInt();
-+ if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
-+ setTime(pctime); // Sync Arduino clock to the time received on the serial port
-+ }
-+}
-+
-+time_t requestSync()
-+{
-+ Serial.write(TIME_REQUEST);
-+ return 0; // the time will be sent later in response to serial mesg
-+}
-+
-diff -rupN ./Time/Time/examples/TimeTeensy3/TimeTeensy3.ino ../../arduino-1.5.8/libraries/Time/Time/examples/TimeTeensy3/TimeTeensy3.ino
---- ./Time/Time/examples/TimeTeensy3/TimeTeensy3.ino 1970-01-01 05:30:00.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/examples/TimeTeensy3/TimeTeensy3.ino 2013-03-28 13:53:21.000000000 +0530
-@@ -0,0 +1,78 @@
-+/*
-+ * TimeRTC.pde
-+ * example code illustrating Time library with Real Time Clock.
-+ *
-+ */
-+
-+#include <Time.h>
-+
-+void setup() {
-+ // set the Time library to use Teensy 3.0's RTC to keep time
-+ setSyncProvider(getTeensy3Time);
-+
-+ Serial.begin(115200);
-+ while (!Serial); // Wait for Arduino Serial Monitor to open
-+ delay(100);
-+ if (timeStatus()!= timeSet) {
-+ Serial.println("Unable to sync with the RTC");
-+ } else {
-+ Serial.println("RTC has set the system time");
-+ }
-+}
-+
-+void loop() {
-+ if (Serial.available()) {
-+ time_t t = processSyncMessage();
-+ if (t != 0) {
-+ Teensy3Clock.set(t); // set the RTC
-+ setTime(t);
-+ }
-+ }
-+ digitalClockDisplay();
-+ delay(1000);
-+}
-+
-+void digitalClockDisplay() {
-+ // digital clock display of the time
-+ Serial.print(hour());
-+ printDigits(minute());
-+ printDigits(second());
-+ Serial.print(" ");
-+ Serial.print(day());
-+ Serial.print(" ");
-+ Serial.print(month());
-+ Serial.print(" ");
-+ Serial.print(year());
-+ Serial.println();
-+}
-+
-+time_t getTeensy3Time()
-+{
-+ return Teensy3Clock.get();
-+}
-+
-+/* code to process time sync messages from the serial port */
-+#define TIME_HEADER "T" // Header tag for serial time sync message
-+
-+unsigned long processSyncMessage() {
-+ unsigned long pctime = 0L;
-+ const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
-+
-+ if(Serial.find(TIME_HEADER)) {
-+ pctime = Serial.parseInt();
-+ return pctime;
-+ if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
-+ pctime = 0L; // return 0 to indicate that the time is not valid
-+ }
-+ }
-+ return pctime;
-+}
-+
-+void printDigits(int digits){
-+ // utility function for digital clock display: prints preceding colon and leading 0
-+ Serial.print(":");
-+ if(digits < 10)
-+ Serial.print('0');
-+ Serial.print(digits);
-+}
-+
-diff -rupN ./Time/Time/Examples/Processing/SyncArduinoClock/readme.txt ../../arduino-1.5.8/libraries/Time/Time/Examples/Processing/SyncArduinoClock/readme.txt
---- ./Time/Time/Examples/Processing/SyncArduinoClock/readme.txt 2009-12-29 17:24:28.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/Processing/SyncArduinoClock/readme.txt 1970-01-01 05:30:00.000000000 +0530
-@@ -1,9 +0,0 @@
--SyncArduinoClock is a Processing sketch that responds to Arduino requests for
--time synchronization messages.
--
--The portIndex must be set the Serial port connected to Arduino.
--
--Download TimeSerial.pde onto Arduino and you should see the time
--message displayed when you run SyncArduinoClock in Processing.
--The Arduino time is set from the time on your computer through the
--Processing sketch.
-\ No newline at end of file
-diff -rupN ./Time/Time/Examples/Processing/SyncArduinoClock/SyncArduinoClock.pde ../../arduino-1.5.8/libraries/Time/Time/Examples/Processing/SyncArduinoClock/SyncArduinoClock.pde
---- ./Time/Time/Examples/Processing/SyncArduinoClock/SyncArduinoClock.pde 2009-12-30 18:02:06.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/Processing/SyncArduinoClock/SyncArduinoClock.pde 1970-01-01 05:30:00.000000000 +0530
-@@ -1,70 +0,0 @@
--/**
-- * SyncArduinoClock.
-- *
-- * portIndex must be set to the port connected to the Arduino
-- *
-- * The current time is sent in response to request message from Arduino
-- * or by clicking the display window
-- *
-- * The time message is 11 ASCII text characters; a header (the letter 'T')
-- * followed by the ten digit system time (unix time)
-- */
--
--
--import processing.serial.*;
--
--public static final short portIndex = 1; // select the com port, 0 is the first port
--public static final char TIME_HEADER = 'T'; //header byte for arduino serial time message
--public static final char TIME_REQUEST = 7; // ASCII bell character
--public static final char LF = 10; // ASCII linefeed
--public static final char CR = 13; // ASCII linefeed
--Serial myPort; // Create object from Serial class
--
--void setup() {
-- size(200, 200);
-- println(Serial.list());
-- println(" Connecting to -> " + Serial.list()[portIndex]);
-- myPort = new Serial(this,Serial.list()[portIndex], 9600);
--}
--
--void draw()
--{
-- if ( myPort.available() > 0) { // If data is available,
-- char val = char(myPort.read()); // read it and store it in val
-- if(val == TIME_REQUEST){
-- long t = getTimeNow();
-- sendTimeMessage(TIME_HEADER, t);
-- }
-- else
-- {
-- if(val == LF)
-- ; //igonore
-- else if(val == CR)
-- println();
-- else
-- print(val); // echo everying but time request
-- }
-- }
--}
--
--void mousePressed() {
-- sendTimeMessage( TIME_HEADER, getTimeNow());
--}
--
--
--void sendTimeMessage(char header, long time) {
-- String timeStr = String.valueOf(time);
-- myPort.write(header); // send header and time to arduino
-- myPort.write(timeStr);
--}
--
--long getTimeNow(){
-- // java time is in ms, we want secs
-- GregorianCalendar cal = new GregorianCalendar();
-- cal.setTime(new Date());
-- int tzo = cal.get(Calendar.ZONE_OFFSET);
-- int dst = cal.get(Calendar.DST_OFFSET);
-- long now = (cal.getTimeInMillis() / 1000) ;
-- now = now + (tzo/1000) + (dst/1000);
-- return now;
--}
-diff -rupN ./Time/Time/Examples/TimeGPS/TimeGPS.pde ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeGPS/TimeGPS.pde
---- ./Time/Time/Examples/TimeGPS/TimeGPS.pde 2010-01-06 09:45:10.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeGPS/TimeGPS.pde 1970-01-01 05:30:00.000000000 +0530
-@@ -1,82 +0,0 @@
--/*
-- * TimeGPS.pde
-- * example code illustrating time synced from a GPS
-- *
-- */
--
--#include <Time.h>
--#include <TinyGPS.h> //http://arduiniana.org/libraries/TinyGPS/
--#include <NewSoftSerial.h> //http://arduiniana.org/libraries/newsoftserial/
--// GPS and NewSoftSerial libraries are the work of Mikal Hart
--
--TinyGPS gps;
--NewSoftSerial serial_gps = NewSoftSerial(3, 2); // receive on pin 3
--
--const int offset = 1; // offset hours from gps time (UTC)
--time_t prevDisplay = 0; // when the digital clock was displayed
--
--void setup()
--{
-- Serial.begin(9600);
-- serial_gps.begin(4800);
-- Serial.println("Waiting for GPS time ... ");
-- setSyncProvider(gpsTimeSync);
--}
--
--void loop()
--{
-- while (serial_gps.available())
-- {
-- gps.encode(serial_gps.read()); // process gps messages
-- }
-- if(timeStatus()!= timeNotSet)
-- {
-- if( now() != prevDisplay) //update the display only if the time has changed
-- {
-- prevDisplay = now();
-- digitalClockDisplay();
-- }
-- }
--}
--
--void digitalClockDisplay(){
-- // digital clock display of the time
-- Serial.print(hour());
-- printDigits(minute());
-- printDigits(second());
-- Serial.print(" ");
-- Serial.print(day());
-- Serial.print(" ");
-- Serial.print(month());
-- Serial.print(" ");
-- Serial.print(year());
-- Serial.println();
--}
--
--void printDigits(int digits){
-- // utility function for digital clock display: prints preceding colon and leading 0
-- Serial.print(":");
-- if(digits < 10)
-- Serial.print('0');
-- Serial.print(digits);
--}
--
--time_t gpsTimeSync(){
-- // returns time if avail from gps, else returns 0
-- unsigned long fix_age = 0 ;
-- gps.get_datetime(NULL,NULL, &fix_age);
-- unsigned long time_since_last_fix;
-- if(fix_age < 1000)
-- return gpsTimeToArduinoTime(); // return time only if updated recently by gps
-- return 0;
--}
--
--time_t gpsTimeToArduinoTime(){
-- // returns time_t from gps date and time with the given offset hours
-- tmElements_t tm;
-- int year;
-- gps.crack_datetime(&year, &tm.Month, &tm.Day, &tm.Hour, &tm.Minute, &tm.Second, NULL, NULL);
-- tm.Year = year - 1970;
-- time_t time = makeTime(tm);
-- return time + (offset * SECS_PER_HOUR);
--}
-diff -rupN ./Time/Time/Examples/TimeNTP/TimeNTP.pde ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeNTP/TimeNTP.pde
---- ./Time/Time/Examples/TimeNTP/TimeNTP.pde 2010-03-06 19:20:14.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeNTP/TimeNTP.pde 1970-01-01 05:30:00.000000000 +0530
-@@ -1,120 +0,0 @@
--/*
-- * Time_NTP.pde
-- * Example showing time sync to NTP time source
-- *
-- * This sketch uses the Ethenet library with the user contributed UdpBytewise extension
-- */
--
--#include <Time.h>
--#include <Ethernet.h>
--#include <UdpBytewise.h> // UDP library from: bjoern@cs.stanford.edu 12/30/2008
--#if UDP_TX_PACKET_MAX_SIZE <64 || UDP_RX_PACKET_MAX_SIZE < 64
--#error : UDP packet size to small - modify UdpBytewise.h to set buffers to 64 bytes
--#endif
--/*
-- *
-- * You may need to modify the UdpBytewise.h library to allow enough space in the buffers for the NTP packets.
-- * Open up UdpBytewse.h and set the following buffers to 64 bytes:
-- * #define UDP_TX_PACKET_MAX_SIZE 64
-- * #define UDP_RX_PACKET_MAX_SIZE 64
-- */
--
--
--byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
--byte ip[] = { 192, 168, 1, 44 }; // set the IP address to an unused address on your network
--
--byte SNTP_server_IP[] = { 192, 43, 244, 18}; // time.nist.gov
--//byte SNTP_server_IP[] = { 130,149,17,21}; // ntps1-0.cs.tu-berlin.de
--//byte SNTP_server_IP[] = { 192,53,103,108}; // ptbtime1.ptb.de
--
--
--time_t prevDisplay = 0; // when the digital clock was displayed
--const long timeZoneOffset = 0L; // set this to the offset in seconds to your local time;
--
--void setup()
--{
-- Serial.begin(9600);
-- Ethernet.begin(mac,ip);
-- Serial.println("waiting for sync");
-- setSyncProvider(getNtpTime);
-- while(timeStatus()== timeNotSet)
-- ; // wait until the time is set by the sync provider
--}
--
--void loop()
--{
-- if( now() != prevDisplay) //update the display only if the time has changed
-- {
-- prevDisplay = now();
-- digitalClockDisplay();
-- }
--}
--
--void digitalClockDisplay(){
-- // digital clock display of the time
-- Serial.print(hour());
-- printDigits(minute());
-- printDigits(second());
-- Serial.print(" ");
-- Serial.print(day());
-- Serial.print(" ");
-- Serial.print(month());
-- Serial.print(" ");
-- Serial.print(year());
-- Serial.println();
--}
--
--void printDigits(int digits){
-- // utility function for digital clock display: prints preceding colon and leading 0
-- Serial.print(":");
-- if(digits < 10)
-- Serial.print('0');
-- Serial.print(digits);
--}
--
--/*-------- NTP code ----------*/
--
--unsigned long getNtpTime()
--{
-- sendNTPpacket(SNTP_server_IP);
-- delay(1000);
-- if ( UdpBytewise.available() ) {
-- for(int i=0; i < 40; i++)
-- UdpBytewise.read(); // ignore every field except the time
-- const unsigned long seventy_years = 2208988800UL + timeZoneOffset;
-- return getUlong() - seventy_years;
-- }
-- return 0; // return 0 if unable to get the time
--}
--
--unsigned long sendNTPpacket(byte *address)
--{
-- UdpBytewise.begin(123);
-- UdpBytewise.beginPacket(address, 123);
-- UdpBytewise.write(B11100011); // LI, Version, Mode
-- UdpBytewise.write(0); // Stratum
-- UdpBytewise.write(6); // Polling Interval
-- UdpBytewise.write(0xEC); // Peer Clock Precision
-- write_n(0, 8); // Root Delay & Root Dispersion
-- UdpBytewise.write(49);
-- UdpBytewise.write(0x4E);
-- UdpBytewise.write(49);
-- UdpBytewise.write(52);
-- write_n(0, 32); //Reference and time stamps
-- UdpBytewise.endPacket();
--}
--
--unsigned long getUlong()
--{
-- unsigned long ulong = (unsigned long)UdpBytewise.read() << 24;
-- ulong |= (unsigned long)UdpBytewise.read() << 16;
-- ulong |= (unsigned long)UdpBytewise.read() << 8;
-- ulong |= (unsigned long)UdpBytewise.read();
-- return ulong;
--}
--
--void write_n(int what, int how_many)
--{
-- for( int i = 0; i < how_many; i++ )
-- UdpBytewise.write(what);
--}
-diff -rupN ./Time/Time/Examples/TimeRTC/TimeRTC.pde ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeRTC/TimeRTC.pde
---- ./Time/Time/Examples/TimeRTC/TimeRTC.pde 2010-01-05 14:13:46.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeRTC/TimeRTC.pde 1970-01-01 05:30:00.000000000 +0530
-@@ -1,47 +0,0 @@
--/*
-- * TimeRTC.pde
-- * example code illustrating Time library with Real Time Clock.
-- *
-- */
--
--#include <Time.h>
--#include <Wire.h>
--#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
--
--void setup() {
-- Serial.begin(9600);
-- setSyncProvider(RTC.get); // the function to get the time from the RTC
-- if(timeStatus()!= timeSet)
-- Serial.println("Unable to sync with the RTC");
-- else
-- Serial.println("RTC has set the system time");
--}
--
--void loop()
--{
-- digitalClockDisplay();
-- delay(1000);
--}
--
--void digitalClockDisplay(){
-- // digital clock display of the time
-- Serial.print(hour());
-- printDigits(minute());
-- printDigits(second());
-- Serial.print(" ");
-- Serial.print(day());
-- Serial.print(" ");
-- Serial.print(month());
-- Serial.print(" ");
-- Serial.print(year());
-- Serial.println();
--}
--
--void printDigits(int digits){
-- // utility function for digital clock display: prints preceding colon and leading 0
-- Serial.print(":");
-- if(digits < 10)
-- Serial.print('0');
-- Serial.print(digits);
--}
--
-diff -rupN ./Time/Time/Examples/TimeRTCLog/TimeRTCLog.pde ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeRTCLog/TimeRTCLog.pde
---- ./Time/Time/Examples/TimeRTCLog/TimeRTCLog.pde 2010-01-06 10:30:36.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeRTCLog/TimeRTCLog.pde 1970-01-01 05:30:00.000000000 +0530
-@@ -1,106 +0,0 @@
--/*
-- * TimeRTCLogger.pde
-- * example code illustrating adding and subtracting Time.
-- *
-- * this sketch logs pin state change events
-- * the time of the event and time since the previous event is calculated and sent to the serial port.
-- */
--
--#include <Time.h>
--#include <Wire.h>
--#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
--
--const int nbrInputPins = 6; // monitor 6 digital pins
--const int inputPins[nbrInputPins] = {2,3,4,5,6,7}; // pins to monitor
--boolean state[nbrInputPins] ; // the state of the monitored pins
--time_t prevEventTime[nbrInputPins] ; // the time of the previous event
--
--void setup() {
-- Serial.begin(9600);
-- setSyncProvider(RTC.get); // the function to sync the time from the RTC
-- for(int i=0; i < nbrInputPins; i++){
-- pinMode( inputPins[i], INPUT);
-- // digitalWrite( inputPins[i], HIGH); // uncomment these lines if
-- // state[i] = HIGH; // pull-up resistors are wanted
-- }
--}
--
--void loop()
--{
-- for(int i=0; i < nbrInputPins; i++)
-- {
-- boolean val = digitalRead(inputPins[i]);
-- if(val != state[i])
-- {
-- time_t duration = 0; // the time since the previous event
-- state[i] = val;
-- time_t timeNow = now();
-- if(prevEventTime[i] > 0)
-- // if this was not the first state change, calculate the time from the previous change
-- duration = duration = timeNow - prevEventTime[i];
-- logEvent(inputPins[i], val, timeNow, duration ); // log the event
-- prevEventTime[i] = timeNow; // store the time for this event
-- }
-- }
--}
--
--void logEvent( int pin, boolean state, time_t timeNow, time_t duration)
--{
-- Serial.print("Pin ");
-- Serial.print(pin);
-- if( state == HIGH)
-- Serial.print(" went High at ");
-- else
-- Serial.print(" went Low at ");
-- showTime(timeNow);
-- if(duration > 0){
-- // only display duration if greater than 0
-- Serial.print(", Duration was ");
-- showDuration(duration);
-- }
-- Serial.println();
--}
--
--
--void showTime(time_t t){
-- // display the given time
-- Serial.print(hour(t));
-- printDigits(minute(t));
-- printDigits(second(t));
-- Serial.print(" ");
-- Serial.print(day(t));
-- Serial.print(" ");
-- Serial.print(month(t));
-- Serial.print(" ");
-- Serial.print(year(t));
--}
--
--void printDigits(int digits){
-- // utility function for digital clock display: prints preceding colon and leading 0
-- Serial.print(":");
-- if(digits < 10)
-- Serial.print('0');
-- Serial.print(digits);
--}
--
--void showDuration(time_t duration){
--// prints the duration in days, hours, minutes and seconds
-- if(duration >= SECS_PER_DAY){
-- Serial.print(duration / SECS_PER_DAY);
-- Serial.print(" day(s) ");
-- duration = duration % SECS_PER_DAY;
-- }
-- if(duration >= SECS_PER_HOUR){
-- Serial.print(duration / SECS_PER_HOUR);
-- Serial.print(" hour(s) ");
-- duration = duration % SECS_PER_HOUR;
-- }
-- if(duration >= SECS_PER_MIN){
-- Serial.print(duration / SECS_PER_MIN);
-- Serial.print(" minute(s) ");
-- duration = duration % SECS_PER_MIN;
-- }
-- Serial.print(duration);
-- Serial.print(" second(s) ");
--}
--
-diff -rupN ./Time/Time/Examples/TimeRTCSet/TimeRTCSet.pde ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeRTCSet/TimeRTCSet.pde
---- ./Time/Time/Examples/TimeRTCSet/TimeRTCSet.pde 2010-01-06 09:53:08.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeRTCSet/TimeRTCSet.pde 1970-01-01 05:30:00.000000000 +0530
-@@ -1,82 +0,0 @@
--/*
-- * TimeRTCSet.pde
-- * example code illustrating Time library with Real Time Clock.
-- *
-- * RTC clock is set in response to serial port time message
-- * A Processing example sketch to set the time is inclided in the download
-- */
--
--#include <Time.h>
--#include <Wire.h>
--#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
--
--
--void setup() {
-- Serial.begin(9600);
-- setSyncProvider(RTC.get); // the function to get the time from the RTC
-- if(timeStatus()!= timeSet)
-- Serial.println("Unable to sync with the RTC");
-- else
-- Serial.println("RTC has set the system time");
--}
--
--void loop()
--{
-- if(Serial.available())
-- {
-- time_t t = processSyncMessage();
-- if(t >0)
-- {
-- RTC.set(t); // set the RTC and the system time to the received value
-- setTime(t);
-- }
-- }
-- digitalClockDisplay();
-- delay(1000);
--}
--
--void digitalClockDisplay(){
-- // digital clock display of the time
-- Serial.print(hour());
-- printDigits(minute());
-- printDigits(second());
-- Serial.print(" ");
-- Serial.print(day());
-- Serial.print(" ");
-- Serial.print(month());
-- Serial.print(" ");
-- Serial.print(year());
-- Serial.println();
--}
--
--void printDigits(int digits){
-- // utility function for digital clock display: prints preceding colon and leading 0
-- Serial.print(":");
-- if(digits < 10)
-- Serial.print('0');
-- Serial.print(digits);
--}
--
--/* code to process time sync messages from the serial port */
--#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by unix time_t as ten ascii digits
--#define TIME_HEADER 'T' // Header tag for serial time sync message
--
--time_t processSyncMessage() {
-- // return the time if a valid sync message is received on the serial port.
-- while(Serial.available() >= TIME_MSG_LEN ){ // time message consists of a header and ten ascii digits
-- char c = Serial.read() ;
-- Serial.print(c);
-- if( c == TIME_HEADER ) {
-- time_t pctime = 0;
-- for(int i=0; i < TIME_MSG_LEN -1; i++){
-- c = Serial.read();
-- if( c >= '0' && c <= '9'){
-- pctime = (10 * pctime) + (c - '0') ; // convert digits to a number
-- }
-- }
-- return pctime;
-- }
-- }
-- return 0;
--}
--
-diff -rupN ./Time/Time/Examples/TimeSerial/TimeSerial.pde ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeSerial/TimeSerial.pde
---- ./Time/Time/Examples/TimeSerial/TimeSerial.pde 2010-01-06 10:55:18.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeSerial/TimeSerial.pde 1970-01-01 05:30:00.000000000 +0530
-@@ -1,82 +0,0 @@
--/*
-- * TimeSerial.pde
-- * example code illustrating Time library set through serial port messages.
-- *
-- * Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970)
-- * you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2010
-- T1262347200
-- *
-- * A Processing example sketch to automatically send the messages is inclided in the download
-- */
--
--#include <Time.h>
--
--#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by unix time_t as ten ascii digits
--#define TIME_HEADER 'T' // Header tag for serial time sync message
--#define TIME_REQUEST 7 // ASCII bell character requests a time sync message
--
--void setup() {
-- Serial.begin(9600);
-- setSyncProvider( requestSync); //set function to call when sync required
-- Serial.println("Waiting for sync message");
--}
--
--void loop(){
-- if(Serial.available() )
-- {
-- processSyncMessage();
-- }
-- if(timeStatus()!= timeNotSet)
-- {
-- digitalWrite(13,timeStatus() == timeSet); // on if synced, off if needs refresh
-- digitalClockDisplay();
-- }
-- delay(1000);
--}
--
--void digitalClockDisplay(){
-- // digital clock display of the time
-- Serial.print(hour());
-- printDigits(minute());
-- printDigits(second());
-- Serial.print(" ");
-- Serial.print(day());
-- Serial.print(" ");
-- Serial.print(month());
-- Serial.print(" ");
-- Serial.print(year());
-- Serial.println();
--}
--
--void printDigits(int digits){
-- // utility function for digital clock display: prints preceding colon and leading 0
-- Serial.print(":");
-- if(digits < 10)
-- Serial.print('0');
-- Serial.print(digits);
--}
--
--void processSyncMessage() {
-- // if time sync available from serial port, update time and return true
-- while(Serial.available() >= TIME_MSG_LEN ){ // time message consists of a header and ten ascii digits
-- char c = Serial.read() ;
-- Serial.print(c);
-- if( c == TIME_HEADER ) {
-- time_t pctime = 0;
-- for(int i=0; i < TIME_MSG_LEN -1; i++){
-- c = Serial.read();
-- if( c >= '0' && c <= '9'){
-- pctime = (10 * pctime) + (c - '0') ; // convert digits to a number
-- }
-- }
-- setTime(pctime); // Sync Arduino clock to the time received on the serial port
-- }
-- }
--}
--
--time_t requestSync()
--{
-- Serial.print(TIME_REQUEST,BYTE);
-- return 0; // the time will be sent later in response to serial mesg
--}
--
-diff -rupN ./Time/Time/Examples/TimeSerialDateStrings/TimeSerialDateStrings.pde ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeSerialDateStrings/TimeSerialDateStrings.pde
---- ./Time/Time/Examples/TimeSerialDateStrings/TimeSerialDateStrings.pde 2010-01-06 10:55:48.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Examples/TimeSerialDateStrings/TimeSerialDateStrings.pde 1970-01-01 05:30:00.000000000 +0530
-@@ -1,80 +0,0 @@
--/*
-- * TimeSerialDateStrings.pde
-- * example code illustrating Time library date strings
-- *
-- * This sketch adds date string functionality to TimeSerial.pde
-- *
-- */
--
--#include <Time.h>
--
--#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by unix time_t as ten ascii digits
--#define TIME_HEADER 'T' // Header tag for serial time sync message
--#define TIME_REQUEST 7 // ASCII bell character requests a time sync message
--
--void setup() {
-- Serial.begin(9600);
-- setSyncProvider( requestSync); //set function to call when sync required
-- Serial.println("Waiting for sync message");
--}
--
--void loop(){
-- if(Serial.available() )
-- {
-- processSyncMessage();
-- }
-- if(timeStatus()!= timeNotSet)
-- {
-- digitalClockDisplay();
-- }
-- delay(1000);
--}
--
--void digitalClockDisplay(){
-- // digital clock display of the time
-- Serial.print(hour());
-- printDigits(minute());
-- printDigits(second());
-- Serial.print(" ");
-- Serial.print(dayStr(weekday()));
-- Serial.print(" ");
-- Serial.print(day());
-- Serial.print(" ");
-- Serial.print(monthShortStr(month()));
-- Serial.print(" ");
-- Serial.print(year());
-- Serial.println();
--}
--
--void printDigits(int digits){
-- // utility function for digital clock display: prints preceding colon and leading 0
-- Serial.print(":");
-- if(digits < 10)
-- Serial.print('0');
-- Serial.print(digits);
--}
--
--void processSyncMessage() {
-- // if time sync available from serial port, update time and return true
-- while(Serial.available() >= TIME_MSG_LEN ){ // time message consists of a header and ten ascii digits
-- char c = Serial.read() ;
-- Serial.print(c);
-- if( c == TIME_HEADER ) {
-- time_t pctime = 0;
-- for(int i=0; i < TIME_MSG_LEN -1; i++){
-- c = Serial.read();
-- if( c >= '0' && c <= '9'){
-- pctime = (10 * pctime) + (c - '0') ; // convert digits to a number
-- }
-- }
-- setTime(pctime); // Sync Arduino clock to the time received on the serial port
-- }
-- }
--}
--
--time_t requestSync()
--{
-- Serial.print(TIME_REQUEST,BYTE);
-- return 0; // the time will be sent later in response to serial mesg
--}
--
-diff -rupN ./Time/Time/keywords.txt ../../arduino-1.5.8/libraries/Time/Time/keywords.txt
---- ./Time/Time/keywords.txt 2010-01-05 12:02:50.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/keywords.txt 2013-03-23 22:36:10.000000000 +0530
-@@ -5,25 +5,25 @@
- #######################################
- # Datatypes (KEYWORD1)
- #######################################
--time_t KEYWORD1
-+time_t KEYWORD1
- #######################################
- # Methods and Functions (KEYWORD2)
- #######################################
- now KEYWORD2
--second KEYWORD2
-+second KEYWORD2
- minute KEYWORD2
--hour KEYWORD2
--day KEYWORD2
--month KEYWORD2
--year KEYWORD2
--isAM KEYWORD2
--isPM KEYWORD2
--weekday KEYWORD2
--setTime KEYWORD2
--adjustTime KEYWORD2
--setSyncProvider KEYWORD2
+
+-PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
+-char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
++PGM_P const dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
++const char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
+
+ /* functions to return date strings */
+
+diff -rupN ./libraries/Time/Time/keywords.txt ./arduino-1.5.8/libraries/Time/Time/keywords.txt
+--- ./libraries/Time/Time/keywords.txt 2010-01-05 12:02:50.000000000 +0530
++++ ./arduino-1.5.8/libraries/Time/Time/keywords.txt 2015-02-05 16:35:47.000000000 +0530
+@@ -22,7 +22,7 @@ weekday KEYWORD2
+ setTime KEYWORD2
+ adjustTime KEYWORD2
+ setSyncProvider KEYWORD2
-setSyncInteval KEYWORD2
--timeStatus KEYWORD2
-+hour KEYWORD2
-+day KEYWORD2
-+month KEYWORD2
-+year KEYWORD2
-+isAM KEYWORD2
-+isPM KEYWORD2
-+weekday KEYWORD2
-+setTime KEYWORD2
-+adjustTime KEYWORD2
-+setSyncProvider KEYWORD2
-+setSyncInterval KEYWORD2
-+timeStatus KEYWORD2
++setSyncInterval KEYWORD2
+ timeStatus KEYWORD2
#######################################
# Instances (KEYWORD2)
- #######################################
-diff -rupN ./Time/Time/Readme.txt ../../arduino-1.5.8/libraries/Time/Time/Readme.txt
---- ./Time/Time/Readme.txt 2010-01-11 21:36:24.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Readme.txt 2013-03-23 21:37:54.000000000 +0530
-@@ -1,131 +1,131 @@
--Readme file for Arduino Time Library
--
--Time is a library that provides timekeeping functionality for Arduino.
--
--The code is derived from the Playground DateTime library but is updated
--to provide an API that is more flexable and easier to use.
--
--A primary goal was to enable date and time functionality that can be used with
--a variety of external time sources with minimum differences required in sketch logic.
--
--Example sketches illustrate how similar sketch code can be used with: a Real Time Clock,
--internet NTP time service, GPS time data, and Serial time messages from a computer
--for time synchronization.
--
--The functions available in the library include:
--
--hour(); // the hour now (0-23)
--minute(); // the minute now (0-59)
--second(); // the second now (0-59)
--day(); // the day now (1-31)
--weekday(); // day of the week, Sunday is day 0
--month(); // the month now (1-12)
--year(); // the full four digit year: (2009, 2010 etc)
--
--there are also functions to return the hour in 12 hour format
--hourFormat12(); // the hour now in 12 hour format
--isAM(); // returns true if time now is AM
--isPM(); // returns true if time now is PM
--
--now(); // returns the current time as seconds since Jan 1 1970
--
--The time and date functions can take an optional parameter for the time. This prevents
--errors if the time rolls over between elements. For example, if a new minute begins
--between getting the minute and second, the values will be inconsistent. Using the
--following functions eliminates this probglem
-- time_t t = now(); // store the current time in time variable t
-- hour(t); // returns the hour for the given time t
-- minute(t); // returns the minute for the given time t
-- second(t); // returns the second for the given time t
-- day(t); // the day for the given time t
-- weekday(t); // day of the week for the given time t
-- month(t); // the month for the given time t
-- year(t); // the year for the given time t
--
--
--Functions for managing the timer services are:
--setTime(t); // set the system time to the give time t
--setTime(hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr (2010 or 10 sets year to 2010)
--adjustTime(adjustment); // adjust system time by adding the adjustment value
--
--timeStatus(); // indicates if time has been set and recently synchronized
-- // returns one of the following enumerations:
-- timeNotSet // the time has never been set, the clock started at Jan 1 1970
-- timeNeedsSync // the time had been set but a sync attempt did not succeed
-- timeSet // the time is set and is synced
--Time and Date values are not valid if the status is timeNotSet. Otherwise values can be used but
--the returned time may have drifted if the status is timeNeedsSync.
--
--setSyncProvider(getTimeFunction); // set the external time provider
--setSyncInterval(interval); // set the number of seconds between re-sync
--
--
--There are many convenience macros in the time.h file for time constants and conversion of time units.
--
--To use the library, copy the download to the Library directory.
--
--The Time directory contains the Time library and some example sketches
--illustrating how the library can be used with various time sources:
--
--- TimeSerial.pde shows Arduino as a clock without external hardware.
-- It is synchronized by time messages sent over the serial port.
-- A companion Processing sketch will automatically provide these messages
-- if it is running and connected to the Arduino serial port.
--
--- TimeSerialDateStrings.pde adds day and month name strings to the sketch above
-- Short (3 character) and long strings are available to print the days of
-- the week and names of the months.
--
--- TimeRTC uses a DS1307 real time clock to provide time synchronization.
-- A basic RTC library named DS1307RTC is included in the download.
-- To run this sketch the DS1307RTC library must be installed.
--
--- TimeRTCSet is similar to the above and adds the ability to set the Real Time Clock
--
--- TimeRTCLog demonstrates how to calculate the difference between times.
-- It is a vary simple logger application that monitors events on digtial pins
-- and prints (to the serial port) the time of an event and the time period since the previous event.
--
--- TimeNTP uses the Arduino Ethernet shield to access time using the internet NTP time service.
-- The NTP protocol uses UDP and the UdpBytewise library is required, see:
-- http://bitbucket.org/bjoern/arduino_osc/src/14667490521f/libraries/Ethernet/
--
---TimeGPS gets time from a GPS
-- This requires the TinyGPS and NewSoftSerial libraries from Mikal Hart:
-- http://arduiniana.org/libraries/TinyGPS and http://arduiniana.org/libraries/newsoftserial/
--
--Differences between this code and the playground DateTime library
--although the Time library is based on the DateTime codebase, the API has changed.
--Changes in the Time library API:
--- time elements are functions returning int (they are variables in DateTime)
--- Years start from 1970
--- days of the week and months start from 1 (they start from 0 in DateTime)
--- DateStrings do not require a seperate library
--- time elements can be accessed non-atomically (in DateTime they are always atomic)
--- function added to automatically sync time with extrnal source
--- localTime and maketime parameters changed, localTime renamed to breakTime
--
--Technical notes:
--
--Internal system time is based on the standard Unix time_t.
--The value is the number of seconds since Jan 1 1970.
--System time begins at zero when the sketch starts.
--
--The internal time can be automatically synchronized at regular intervals to an external time source.
--This is enabled by calling the setSyncProvider(provider) function - the provider argument is
--the address of a function that returns the current time as a time_t.
--See the sketches in the examples directory for usage.
--
--The default interval for re-syncing the time is 5 minutes but can be changed by calling the
--setSyncInterval( interval) method to set the number of seconds between re-sync attempts.
--
--The Time library defines a structure for holding time elements that is a compact version of the C tm structure.
--All the members of the Arduino tm structure are bytes and the year is offset from 1970.
--Convenience macros provide conversion to and from the Arduino format.
--
--Low level functions to convert between system time and individual time elements are provided:
-- breakTime( time, &tm); // break time_t into elements stored in tm struct
-- makeTime( &tm); // return time_t from elements stored in tm struct
--
--The DS1307RTC library included in the download provides an example of how a time provider
--can use the low level functions to interface with the Time library.
-\ No newline at end of file
-+Readme file for Arduino Time Library
-+
-+Time is a library that provides timekeeping functionality for Arduino.
-+
-+The code is derived from the Playground DateTime library but is updated
-+to provide an API that is more flexable and easier to use.
-+
-+A primary goal was to enable date and time functionality that can be used with
-+a variety of external time sources with minimum differences required in sketch logic.
-+
-+Example sketches illustrate how similar sketch code can be used with: a Real Time Clock,
-+internet NTP time service, GPS time data, and Serial time messages from a computer
-+for time synchronization.
-+
-+The functions available in the library include:
-+
-+hour(); // the hour now (0-23)
-+minute(); // the minute now (0-59)
-+second(); // the second now (0-59)
-+day(); // the day now (1-31)
-+weekday(); // day of the week, Sunday is day 0
-+month(); // the month now (1-12)
-+year(); // the full four digit year: (2009, 2010 etc)
-+
-+there are also functions to return the hour in 12 hour format
-+hourFormat12(); // the hour now in 12 hour format
-+isAM(); // returns true if time now is AM
-+isPM(); // returns true if time now is PM
-+
-+now(); // returns the current time as seconds since Jan 1 1970
-+
-+The time and date functions can take an optional parameter for the time. This prevents
-+errors if the time rolls over between elements. For example, if a new minute begins
-+between getting the minute and second, the values will be inconsistent. Using the
-+following functions eliminates this probglem
-+ time_t t = now(); // store the current time in time variable t
-+ hour(t); // returns the hour for the given time t
-+ minute(t); // returns the minute for the given time t
-+ second(t); // returns the second for the given time t
-+ day(t); // the day for the given time t
-+ weekday(t); // day of the week for the given time t
-+ month(t); // the month for the given time t
-+ year(t); // the year for the given time t
-+
-+
-+Functions for managing the timer services are:
-+setTime(t); // set the system time to the give time t
-+setTime(hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr (2010 or 10 sets year to 2010)
-+adjustTime(adjustment); // adjust system time by adding the adjustment value
-+
-+timeStatus(); // indicates if time has been set and recently synchronized
-+ // returns one of the following enumerations:
-+ timeNotSet // the time has never been set, the clock started at Jan 1 1970
-+ timeNeedsSync // the time had been set but a sync attempt did not succeed
-+ timeSet // the time is set and is synced
-+Time and Date values are not valid if the status is timeNotSet. Otherwise values can be used but
-+the returned time may have drifted if the status is timeNeedsSync.
-+
-+setSyncProvider(getTimeFunction); // set the external time provider
-+setSyncInterval(interval); // set the number of seconds between re-sync
-+
-+
-+There are many convenience macros in the time.h file for time constants and conversion of time units.
-+
-+To use the library, copy the download to the Library directory.
-+
-+The Time directory contains the Time library and some example sketches
-+illustrating how the library can be used with various time sources:
-+
-+- TimeSerial.pde shows Arduino as a clock without external hardware.
-+ It is synchronized by time messages sent over the serial port.
-+ A companion Processing sketch will automatically provide these messages
-+ if it is running and connected to the Arduino serial port.
-+
-+- TimeSerialDateStrings.pde adds day and month name strings to the sketch above
-+ Short (3 character) and long strings are available to print the days of
-+ the week and names of the months.
-+
-+- TimeRTC uses a DS1307 real time clock to provide time synchronization.
-+ A basic RTC library named DS1307RTC is included in the download.
-+ To run this sketch the DS1307RTC library must be installed.
-+
-+- TimeRTCSet is similar to the above and adds the ability to set the Real Time Clock
-+
-+- TimeRTCLog demonstrates how to calculate the difference between times.
-+ It is a vary simple logger application that monitors events on digtial pins
-+ and prints (to the serial port) the time of an event and the time period since the previous event.
-+
-+- TimeNTP uses the Arduino Ethernet shield to access time using the internet NTP time service.
-+ The NTP protocol uses UDP and the UdpBytewise library is required, see:
-+ http://bitbucket.org/bjoern/arduino_osc/src/14667490521f/libraries/Ethernet/
-+
-+- TimeGPS gets time from a GPS
-+ This requires the TinyGPS library from Mikal Hart:
-+ http://arduiniana.org/libraries/TinyGPS
-+
-+Differences between this code and the playground DateTime library
-+although the Time library is based on the DateTime codebase, the API has changed.
-+Changes in the Time library API:
-+- time elements are functions returning int (they are variables in DateTime)
-+- Years start from 1970
-+- days of the week and months start from 1 (they start from 0 in DateTime)
-+- DateStrings do not require a seperate library
-+- time elements can be accessed non-atomically (in DateTime they are always atomic)
-+- function added to automatically sync time with extrnal source
-+- localTime and maketime parameters changed, localTime renamed to breakTime
-+
-+Technical notes:
-+
-+Internal system time is based on the standard Unix time_t.
-+The value is the number of seconds since Jan 1 1970.
-+System time begins at zero when the sketch starts.
-+
-+The internal time can be automatically synchronized at regular intervals to an external time source.
-+This is enabled by calling the setSyncProvider(provider) function - the provider argument is
-+the address of a function that returns the current time as a time_t.
-+See the sketches in the examples directory for usage.
-+
-+The default interval for re-syncing the time is 5 minutes but can be changed by calling the
-+setSyncInterval( interval) method to set the number of seconds between re-sync attempts.
-+
-+The Time library defines a structure for holding time elements that is a compact version of the C tm structure.
-+All the members of the Arduino tm structure are bytes and the year is offset from 1970.
-+Convenience macros provide conversion to and from the Arduino format.
-+
-+Low level functions to convert between system time and individual time elements are provided:
-+ breakTime( time, &tm); // break time_t into elements stored in tm struct
-+ makeTime( &tm); // return time_t from elements stored in tm struct
-+
-+The DS1307RTC library included in the download provides an example of how a time provider
-+can use the low level functions to interface with the Time library.
-diff -rupN ./Time/Time/Time.cpp ../../arduino-1.5.8/libraries/Time/Time/Time.cpp
---- ./Time/Time/Time.cpp 2010-11-01 18:02:50.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Time.cpp 2013-03-28 03:19:40.000000000 +0530
-@@ -19,6 +19,11 @@
- 6 Jan 2010 - initial release
- 12 Feb 2010 - fixed leap year calculation error
- 1 Nov 2010 - fixed setTime bug (thanks to Korman for this)
-+ 24 Mar 2012 - many edits by Paul Stoffregen: fixed timeStatus() to update
-+ status, updated examples for Arduino 1.0, fixed ARM
-+ compatibility issues, added TimeArduinoDue and TimeTeensy3
-+ examples, add error checking and messages to RTC examples,
-+ add examples to DS1307RTC library.
- */
-
- #if ARDUINO >= 100
-@@ -30,12 +35,11 @@
- #include "Time.h"
+diff -rupN ./libraries/Time/Time/Time.cpp ./arduino-1.5.8/libraries/Time/Time/Time.cpp
+--- ./libraries/Time/Time/Time.cpp 2010-11-01 18:02:50.000000000 +0530
++++ ./arduino-1.5.8/libraries/Time/Time/Time.cpp 2015-02-05 16:32:08.000000000 +0530
+@@ -31,7 +31,7 @@
static tmElements_t tm; // a cache of time elements
--static time_t cacheTime; // the time the cache was updated
+ static time_t cacheTime; // the time the cache was updated
-static time_t syncInterval = 300; // time sync will be attempted after this many seconds
-+static time_t cacheTime; // the time the cache was updated
-+static uint32_t syncInterval = 300; // time sync will be attempted after this many seconds
++static uint32_t syncInterval = 300; // time sync will be attempted after this many seconds
--void refreshCache( time_t t){
-- if( t != cacheTime)
-- {
-+void refreshCache(time_t t) {
-+ if (t != cacheTime) {
- breakTime(t, tm);
- cacheTime = t;
- }
-@@ -143,15 +147,17 @@ int year(time_t t) { // the year for the
+ void refreshCache( time_t t){
+ if( t != cacheTime)
+@@ -143,15 +143,17 @@ int year(time_t t) { // the year for the
static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0
tm.Second = time % 60;
time /= 60; // now it is minutes
tm.Minute = time % 60;
-@@ -200,7 +206,7 @@ time_t makeTime(tmElements_t &tm){
+@@ -200,7 +202,7 @@ time_t makeTime(tmElements_t &tm){
// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9
int i;
// seconds from 1970 till 1 jan 00:00:00 of the given year
seconds= tm.Year*(SECS_PER_DAY * 365);
-@@ -222,14 +228,14 @@ time_t makeTime(tmElements_t &tm){
+@@ -222,14 +224,14 @@ time_t makeTime(tmElements_t &tm){
seconds+= tm.Hour * SECS_PER_HOUR;
seconds+= tm.Minute * SECS_PER_MIN;
seconds+= tm.Second;
static timeStatus_t Status = timeNotSet;
getExternalTime getTimePtr; // pointer to external sync function
-@@ -240,39 +246,41 @@ time_t sysUnsyncedTime = 0; // the time
- #endif
-
-
--time_t now(){
-- while( millis() - prevMillis >= 1000){
-+time_t now() {
-+ while (millis() - prevMillis >= 1000){
- sysTime++;
- prevMillis += 1000;
- #ifdef TIME_DRIFT_INFO
- sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift
--#endif
-+#endif
- }
-- if(nextSyncTime <= sysTime){
-- if(getTimePtr != 0){
-- time_t t = getTimePtr();
+@@ -251,13 +253,15 @@ time_t now(){
+ if(nextSyncTime <= sysTime){
+ if(getTimePtr != 0){
+ time_t t = getTimePtr();
- if( t != 0)
-+ if (nextSyncTime <= sysTime) {
-+ if (getTimePtr != 0) {
-+ time_t t = getTimePtr();
-+ if (t != 0) {
++ if( t != 0) {
setTime(t);
- else
-- Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync;
+ } else {
+ nextSyncTime = sysTime + syncInterval;
-+ Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync;
+ Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync;
+ }
}
}
+ return (time_t)sysTime;
}
--void setTime(time_t t){
-+void setTime(time_t t) {
- #ifdef TIME_DRIFT_INFO
- if(sysUnsyncedTime == 0)
+ void setTime(time_t t){
+@@ -266,9 +270,9 @@ void setTime(time_t t){
sysUnsyncedTime = t; // store the time of the first call to set a valid Time
#endif
prevMillis = millis(); // restart counting from now (thanks to Korman for this fix)
}
--void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
-+void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
- // year can be given as full four digit year or two digts (2010 or 10 for 2010);
- //it is converted to years since 1970
- if( yr > 99)
-@@ -288,11 +296,13 @@ void setTime(int hr,int min,int sec,int
- setTime(makeTime(tm));
+@@ -293,6 +297,7 @@ void adjustTime(long adjustment){
}
--void adjustTime(long adjustment){
-+void adjustTime(long adjustment) {
- sysTime += adjustment;
- }
-
--timeStatus_t timeStatus(){ // indicates if time has been set and recently synchronized
-+// indicates if time has been set and recently synchronized
-+timeStatus_t timeStatus() {
+ timeStatus_t timeStatus(){ // indicates if time has been set and recently synchronized
+ now(); // required to actually update the status
return Status;
}
-@@ -303,5 +313,6 @@ void setSyncProvider( getExternalTime ge
+@@ -303,5 +308,6 @@ void setSyncProvider( getExternalTime ge
}
void setSyncInterval(time_t interval){ // set the number of seconds between re-sync
- syncInterval = interval;
--}
-\ No newline at end of file
+ syncInterval = (uint32_t)interval;
+ nextSyncTime = sysTime + syncInterval;
-+}
-diff -rupN ./Time/Time/Time.h ../../arduino-1.5.8/libraries/Time/Time/Time.h
---- ./Time/Time/Time.h 2011-07-22 17:30:06.000000000 +0530
-+++ ../../arduino-1.5.8/libraries/Time/Time/Time.h 2014-11-25 18:48:37.000000000 +0530
+ }
+\ No newline at end of file
+diff -rupN ./libraries/Time/Time/Time.h ./arduino-1.5.8/libraries/Time/Time/Time.h
+--- ./libraries/Time/Time/Time.h 2011-07-22 17:30:06.000000000 +0530
++++ ./arduino-1.5.8/libraries/Time/Time/Time.h 2015-02-05 16:22:27.000000000 +0530
@@ -8,12 +8,29 @@
*/
typedef enum {timeNotSet, timeNeedsSync, timeSet
} timeStatus_t ;
-@@ -121,6 +138,7 @@ void setSyncInterval(time_t interval)
+@@ -100,7 +117,11 @@ int month(time_t t); // the month
+ int year(); // the full four digit year: (2009, 2010 etc)
+ int year(time_t t); // the year for the given time
+
++extern "C"
++{
+ time_t now(); // return the current time as seconds since Jan 1 1970
++}
++
+ void setTime(time_t t);
+ void setTime(int hr,int min,int sec,int day, int month, int yr);
+ void adjustTime(long adjustment);
+@@ -121,6 +142,7 @@ void setSyncInterval(time_t interval)
void breakTime(time_t time, tmElements_t &tm); // break time_t into elements
time_t makeTime(tmElements_t &tm); // convert time elements into time_t
+#endif // __cplusplus
#endif /* _Time_h */
-Binary files ./Time/Time/.Time.h.swp and ../../arduino-1.5.8/libraries/Time/Time/.Time.h.swp differ
CC=$(ARDUINO_TOOLS_DIR)/avr-gcc
AR=$(ARDUINO_TOOLS_DIR)/avr-ar
RANLIB=$(ARDUINO_TOOLS_DIR)/avr-ranlib
+
ARDUINO_DIR = /usr/share/arduino
-ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
\ No newline at end of file
+ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
--- /dev/null
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_H__
+#define __TIZEN_NETWORK_BLUETOOTH_H__
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdbool.h>
+#include <tizen_error.h>
+
+#include "bluetooth_type.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * @file bluetooth.h
+ * @brief API to control the Bluetooth adapter and devices and communications.
+ * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
+ */
+
+
+/**
+ * @addtogroup CAPI_NETWORK_BLUETOOTH_MODULE
+ * @{
+ */
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
+ * @brief Initializes the Bluetooth API.
+ * @since_tizen 2.3
+ *
+ * @remarks This function must be called before Bluetooth API starts. \n
+ * You must free all resources of the Bluetooth service by calling bt_deinitialize() if Bluetooth service is no longer needed.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @see bt_deinitialize()
+ */
+int bt_initialize(void);
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
+ * @brief Releases all resources of the Bluetooth API.
+ * @since_tizen 2.3
+ *
+ * @remarks This function must be called if Bluetooth API is no longer needed.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre Bluetooth API must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ */
+int bt_deinitialize(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Enables the local Bluetooth adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function enables Bluetooth protocol stack and hardware.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_ALREADY_DONE Already enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_DISABLED
+ * @post This function invokes bt_adapter_state_changed_cb().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_get_state()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb()
+ * @see bt_adapter_state_changed_cb()
+ *
+ */
+int bt_adapter_enable(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Disables the local Bluetooth adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function disables Bluetooth protocol stack and hardware.
+ *
+ * @remarks You should disable Bluetooth adapter, which is helpful for saving power.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
+ * @post This function invokes bt_adapter_state_changed_cb().
+ *
+ * @see bt_adapter_get_state()
+ * @see bt_adapter_state_changed_cb()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb ()
+ *
+ */
+int bt_adapter_disable(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Recover the local Bluetooth adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function does recovery logic, disables Bluetooth protocol stack and hardware, then enables after a few seconds.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
+ * @post This function invokes bt_adapter_state_changed_cb().
+ *
+ * @see bt_adapter_get_state()
+ * @see bt_adapter_state_changed_cb()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb ()
+ *
+ */
+int bt_adapter_recover(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Reset the local Bluetooth adapter, synchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function resets Bluetooth protocol and values.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_state_changed_cb() will be invoked if The state of local Bluetooth was #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_get_state()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb()
+ * @see bt_adapter_state_changed_cb()
+ *
+ */
+int bt_adapter_reset(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the current state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @param[out] adapter_state The current adapter state
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ */
+int bt_adapter_get_state(bt_adapter_state_e *adapter_state);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the address of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @remarks The @a local_address must be released with free() by you.
+ *
+ * @param[out] local_address The device address of local Bluetooth adapter
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_get_name()
+ */
+int bt_adapter_get_address(char **local_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the version of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @remarks The @a local_version must be released with free() by you.
+ *
+ * @param[out] local_version The version of local Bluetooth adapter
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_adapter_get_version(char **local_version);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the information regarding local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @remarks The @a all parameters must be released with free() by you.
+ *
+ * @param[out] chipset Chipset name of local Bluetooth adapter
+ * @param[out] firmware Firmware info. of local Bluetooth adapter
+ * @param[out] stack_version Bluetooth stack version
+ * @param[out] profiles The profile list of local Bluetooth adapter
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_adapter_get_local_info(char **chipset, char **firmware, char **stack_version, char **profiles);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the name of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @details Use this function to get the friendly name associated with Bluetooth
+ * device, retrieved by the remote Bluetooth devices.
+ *
+ * @remarks The @a local_name must be released with free() by you.
+ *
+ * @param[out] local_name The local device name
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_set_name()
+ */
+int bt_adapter_get_name(char **local_name);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the name of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] local_name The name of the Bluetooth device. \n
+ * The maximum length is 248 characters.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_adapter_name_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
+ *
+ * @see bt_adapter_get_name()
+ * @see bt_adapter_name_changed_cb()
+ * @see bt_adapter_set_name_changed_cb()
+ * @see bt_adapter_unset_name_changed_cb()
+ */
+int bt_adapter_set_name(const char *local_name);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the visibility mode of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @param[out] mode The visibility mode of the Bluetooth device
+ * @param[out] duration The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds).
+ * @a duration is valid only if @a mode is #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE. This value can be NULL.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_adapter_get_visibility(bt_adapter_visibility_mode_e *mode, int *duration);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the visibility mode.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE will change to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE
+ * after the given @a duration goes.
+ *
+ * @param[in] discoverable_mode The Bluetooth visibility mode to set
+ * @param[in] duration The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds).
+ * @a duration is used only for #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE mode.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_adapter_visibility_mode_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
+ *
+ * @see bt_adapter_get_visibility()
+ * @see bt_adapter_visibility_mode_changed_cb()
+ * @see bt_adapter_set_visibility_mode_changed_cb()
+ * @see bt_adapter_unset_visibility_mode_changed_cb()
+ */
+int bt_adapter_set_visibility(bt_adapter_visibility_mode_e discoverable_mode, int duration);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Starts the device discovery, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @details If a device is discovered, bt_adapter_device_discovery_state_changed_cb() will be invoked
+ * with #BT_ADAPTER_DEVICE_DISCOVERY_FOUND, and then bt_adapter_device_discovery_state_changed_cb()
+ * will be called with #BT_ADAPTER_DEVICE_DISCOVERY_FINISHED in case of the completion or cancellation of the discovery.
+ *
+ * @remarks To connect to peer Bluetooth device, you need to know its Bluetooth address. \n
+ * The device discovery can be stopped by bt_adapter_stop_device_discovery().
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation is now in progress
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post This function invokes bt_adapter_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_is_discovering()
+ * @see bt_adapter_stop_device_discovery()
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_unset_device_discovery_state_changed_cb()
+ */
+int bt_adapter_start_device_discovery(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Stops the device discovery, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks The device discovery process will take 10 ~ 20 seconds to get all the devices in vicinity.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOT_IN_PROGRESS Operation is not in progress
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The device discovery must be in progress with bt_adapter_start_device_discovery().
+ * @post This function invokes bt_adapter_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_is_discovering()
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_unset_device_discovery_state_changed_cb()
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ */
+int bt_adapter_stop_device_discovery(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Checks for the device discovery is in progress or not.
+ * @since_tizen 2.3
+ *
+ * @remarks If Bluetooth discovery is in progress, other operations are not allowed and
+ * you have to either stop the discovery operation, or wait for it to be finished,
+ * before performing other operations.
+
+ * @param[out] is_discovering The discovering status: (@c true = in progress , @c false = not in progress )
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_adapter_stop_device_discovery()
+ */
+int bt_adapter_is_discovering(bool *is_discovering);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Get the service mask from the uuid list.
+ * @since_tizen 2.3
+ *
+ * @param[in] uuids The UUID list of the device.
+ * @param[in] no_of_service The number of the UUID list count.
+ * @param[out] service_mask_list Service mask list converted from the given UUID list.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @see bt_service_class_t
+ */
+int bt_device_get_service_mask_from_uuid_list(char **uuids,
+ int no_of_service,
+ bt_service_class_t *service_mask_list);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Retrieves the device information of all bonded devices.
+ * @since_tizen 2.3
+ *
+ * @param [in] callback The callback function to invoke
+ * @param [in] user_data The user data passed from the foreach function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post This function invokes bt_adapter_bonded_device_cb().
+ *
+ * @see bt_adapter_bonded_device_cb()
+ */
+int bt_adapter_foreach_bonded_device(bt_adapter_bonded_device_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the device information of a bonded device.
+ * @since_tizen 2.3
+ * @remarks The @a device_info must be released with bt_adapter_free_device_info() by you .
+ *
+ * @param [in] remote_address The address of remote device
+ * @param [out] device_info The bonded device information
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device not bonded
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post This function invokes bt_adapter_bonded_device_cb().
+ *
+ * @see bt_adapter_bonded_device_cb()
+ */
+int bt_adapter_get_bonded_device_info(const char *remote_address, bt_device_info_s **device_info);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Frees device info.
+ * @since_tizen 2.3
+ *
+ * @param [in] device_info The bonded device information
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @see bt_adapter_get_bonded_device_info()
+ */
+int bt_adapter_free_device_info(bt_device_info_s *device_info);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Checks whether the UUID of service is used or not
+ * @since_tizen 2.3
+ * @param[in] service_uuid The UUID of service
+ * @param[out] used Indicates whether the service is used or not
+ * @return true on success, otherwise false.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ */
+int bt_adapter_is_service_used(const char *service_uuid, bool *used);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Registers a callback function to be invoked when the Bluetooth adapter state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_state_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_state_changed_cb()
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb()
+ */
+int bt_adapter_set_state_changed_cb(bt_adapter_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_state_changed_cb()
+ */
+int bt_adapter_unset_state_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Registers a callback function to be invoked when the name of Bluetooth adapter changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_name_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_name_changed_cb()
+ * @see bt_adapter_unset_name_changed_cb()
+ */
+int bt_adapter_set_name_changed_cb(bt_adapter_name_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_name_changed_cb()
+ */
+int bt_adapter_unset_name_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Registers a callback function to be invoked when the visibility mode changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_visibility_mode_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_visibility_mode_changed_cb()
+ * @see bt_adapter_unset_visibility_mode_changed_cb()
+ */
+int bt_adapter_set_visibility_mode_changed_cb(bt_adapter_visibility_mode_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_visibility_mode_changed_cb()
+ */
+int bt_adapter_unset_visibility_mode_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Registers a callback function to be invoked every second
+ * @since_tizen 2.3
+ * until the visibility mode is changed from #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE
+ * to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
+ * @details When you set visibility mode as #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE,
+ * @a callback will be called every second until visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @post bt_adapter_visibility_duration_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_adapter_visibility_duration_changed_cb()
+ * @see bt_adapter_unset_visibility_duration_changed_cb()
+ */
+int bt_adapter_set_visibility_duration_changed_cb(bt_adapter_visibility_duration_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_adapter_set_visibility_duration_changed_cb()
+ */
+int bt_adapter_unset_visibility_duration_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Registers a callback function to be invoked when the device discovery state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_device_discovery_state_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_unset_device_discovery_state_changed_cb()
+ */
+int bt_adapter_set_device_discovery_state_changed_cb(bt_adapter_device_discovery_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ */
+int bt_adapter_unset_device_discovery_state_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Get the Hash and Randmoizer value, synchronously.
+ * @since_tizen 2.3
+ *
+ * @param[out] hash The hash value recieved from the controller
+ * @param[out] randomizer The hash value recieved from the controller
+ * @param[out] hash_len The length of the hash value
+ * @param[out] randomizer_len The length of the randomizer value
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ */
+int bt_adapter_get_local_oob_data(unsigned char **hash, unsigned char **randomizer,
+ int *hash_len, int *randomizer_len);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the Hash and Randmoizer value, synchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] remote_address Remote device address
+ * @param[in] hash The hash value recieved from the controller
+ * @param[in] randomizer The hash value recieved from the controller
+ * @param[in] hash_len The length of the hash value. Allowed value is 16
+ * @param[in] randomizer_len The length of the randomizer value. Allowed value is 16
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ */
+int bt_adapter_set_remote_oob_data(const char *remote_address,
+ unsigned char *hash, unsigned char *randomizer,
+ int hash_len, int randomizer_len);
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Deletes the Hash and Randomizer value, synchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] remote_address Remote device address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ */
+int bt_adapter_remove_remote_oob_data(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Registers a callback function to be invoked when the connectable state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_connectable_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_connectable_changed_cb()
+ * @see bt_adapter_unset_connectable_changed_cb()
+ */
+int bt_adapter_set_connectable_changed_cb(bt_adapter_connectable_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_connectable_changed_cb()
+ */
+int bt_adapter_unset_connectable_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Gets the connectable state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @remarks When connectable state is false, no device can connect to this device and visibility mode cannot be changed.
+ *
+ * @param[out] connectable The connectable state of local Bluetooth adapter
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_set_connectable()
+ */
+int bt_adapter_get_connectable(bool *connectable);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the connectable state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks When connectable state is false, no device can connect to this device and visibility mode cannot be changed.
+ *
+ * @param[in] connectable The connectable state to set
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_adapter_connectable_changed_cb() will be invoked if this function returns #BT_ERROR_NONE.
+ *
+ * @see bt_adapter_get_connectable()
+ * @see bt_adapter_connectable_changed_cb()
+ * @see bt_adapter_set_connectable_changed_cb()
+ * @see bt_adapter_unset_connectable_changed_cb()
+ */
+int bt_adapter_set_connectable(bool connectable);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enables the local Bluetooth le adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function enables Bluetooth protocol stack and hardware.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_ALREADY_DONE Already enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ * @post This function invokes bt_adapter_le_state_changed_cb().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_get_state()
+ * @see bt_adapter_le_set_state_changed_cb()
+ * @see bt_adapter_le_unset_state_changed_cb()
+ * @see bt_adapter_le_state_changed_cb()
+ *
+ */
+int bt_adapter_le_enable(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Disables the local Bluetooth le adapter, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @details This function disables Bluetooth le protocol stack and hardware.
+ *
+ * @remarks
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_LE_ENABLED
+ * @post This function invokes bt_adapter_le_state_changed_cb().
+ *
+ * @see bt_adapter_le_get_state()
+ * @see bt_adapter_le_state_changed_cb()
+ * @see bt_adapter_le_set_state_changed_cb()
+ * @see bt_adapter_le_unset_state_changed_cb ()
+ *
+ */
+int bt_adapter_le_disable(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Gets the current state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ *
+ * @param[out] adapter_le_state The current adapter le state
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ */
+int bt_adapter_le_get_state(bt_adapter_le_state_e *adapter_le_state);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Starts the LE device discovery for a BT_ADAPTER_DEVICE_DISCOVERY_LE type.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @details If a LE device is discovered, bt_adapter_le_device_discovery_state_changed_cb()
+* will be invoked with #BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND, and then bt_adapter_le_device_discovery_state_changed_cb()
+ * will be called with #BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED in case of the completion or cancellation of the discovery.
+ *
+ * @remarks To connect to peer Bluetooth device, you need to know its Bluetooth address. \n
+ * The device discovery can be stopped by bt_adapter_le_stop_device_discovery().
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation is now in progress
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * or must be #BT_ADAPTER_LE_ENABLED.
+ * @post This function invokes bt_adapter_le_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_le_is_discovering()
+ * @see bt_adapter_le_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
+ */
+int bt_adapter_le_start_device_discovery(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Stops the LE device discovery, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOT_IN_PROGRESS Operation is not in progress
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The device discovery must be in progress with bt_adapter_le_start_device_discovery().
+ * @post This function invokes bt_adapter_le_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_le_is_discovering()
+ * @see bt_adapter_le_start_device_discovery()
+ * @see bt_adapter_le_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_device_discovery_state_changed_cb()
+ */
+int bt_adapter_le_stop_device_discovery(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Checks for the LE device discovery is in progress or not.
+ * @since_tizen 2.3
+ *
+ * @remarks If Bluetooth LE discovery is in progress, other operations are not allowed and
+ * you have to either stop the LE discovery operation, or wait for it to be finished,
+ * before performing other operations.
+
+ * @param[out] is_discovering The discovering status: (@c true = in progress , @c false = not in progress )
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * or must be #BT_ADAPTER_LE_ENABLED.
+ *
+ * @see bt_adapter_le_start_device_discovery()
+ * @see bt_adapter_le_stop_device_discovery()
+ */
+int bt_adapter_le_is_discovering(bool *is_discovering);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Registers a callback function to be invoked when the LE device discovery state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_le_device_discovery_state_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
+ */
+int bt_adapter_le_set_device_discovery_state_changed_cb(bt_adapter_le_device_discovery_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_set_device_discovery_state_changed_cb()
+ */
+int bt_adapter_le_unset_device_discovery_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Registers a callback function to be invoked when the Bluetooth adapter le state changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_le_state_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_state_changed_cb()
+ * @see bt_adapter_le_unset_state_changed_cb()
+ */
+int bt_adapter_le_set_state_changed_cb(bt_adapter_le_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_le_set_state_changed_cb()
+ */
+int bt_adapter_le_unset_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief add address to whitelist for accepting scanning request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks If the adress is in the whitelist then other LE devices are able to
+ * search this device. Before calling this API, make sure that the adapter is
+ * enabled. There is no callback event for this API.
+
+ * @param[in] address The other device's address
+ * @param[in] address_type The other device's address type
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Adapter is not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_le_start_advertising()
+ * @see bt_adapter_le_stop_advertising()
+ */
+int bt_adapter_le_add_white_list(const char *address, bt_device_address_type_e address_type);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief remove address from the whitelist for not accepting scanning request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks If the adress is in the whitelist then other LE devices are able to
+ * search this device. Before calling this API, make sure that the adapter is
+ * enabled. There is no callback event for this API.
+ *
+ * @param[in] address The other device's address
+ * @param[in] address_type The other device's address type
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Adapter is not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_le_start_advertising()
+ * @see bt_adapter_le_stop_advertising()
+ */
+int bt_adapter_le_remove_white_list(const char *address, bt_device_address_type_e address_type);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief clear address from the whitelist for not accepting scanning request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks If the adress is in the whitelist then other LE devices are able to
+ * search this device. Before calling this API, make sure that the adapter is
+ * enabled. There is no callback event for this API.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Adapter is not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_adapter_le_start_advertising()
+ * @see bt_adapter_le_stop_advertising()
+ */
+int bt_adapter_le_clear_white_list(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Create advertiser to advertise device's existence or respond to LE scanning reqeust.
+ * @since_tizen 2.3
+ *
+ * @param[out] advertiser The handle of advertiser
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_destroy_advertiser()
+ */
+int bt_adapter_le_create_advertiser(bt_advertiser_h *advertiser);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Destroy advertiser.
+ * @since_tizen 2.3
+ *
+ * @param[out] advertiser The handle of advertiser
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_create_advertiser()
+ */
+int bt_adapter_le_destroy_advertiser(bt_advertiser_h advertiser);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Set the data to be advertised or responded to scan request from LE scanning device.
+ * The maximum advertised or responded data size is 31 bytes
+ * including data type and system wide data.
+ * @since_tizen 2.3
+ *
+ * @param[in] advertiser The handle of advertiser
+ * @param[in] pkt_type The packet type
+ * @param[in] data_type The data type that is included in packet
+ * @param[in] data The data to be advertised or be responded to scan request from LE scanning device
+ * @param[in] data_size The size of data to be set.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_QUOTA_EXCEEDED Quota exceeded
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_remove_advertising_data()
+ * @see bt_adapter_le_clear_advertising_data()
+ */
+int bt_adapter_le_add_advertising_data(bt_advertiser_h advertiser,
+ bt_adapter_le_packet_type_e pkt_type, bt_adapter_le_packet_data_type_e data_type,
+ void *data, unsigned int data_size);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Unset the data to be advertised or responded to scan request from LE scanning device.
+ * @since_tizen 2.3
+ *
+ * @param[in] advertiser The handle of advertiser
+ * @param[in] pkt_type The packet type
+ * @param[in] data_type The data type to be removed from selected packet
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_add_advertising_data()
+ * @see bt_adapter_le_clear_advertising_data()
+ */
+int bt_adapter_le_remove_advertising_data(bt_advertiser_h advertiser,
+ bt_adapter_le_packet_type_e pkt_type, bt_adapter_le_packet_data_type_e data_type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Clear all data to be advertised or responded to scan request from LE scanning device.
+ * @since_tizen 2.3
+ *
+ * @param[in] advertiser The handle of advertiser
+ * @param[in] pkt_type The packet type to be cleared
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_adapter_le_add_advertising_data()
+ * @see bt_adapter_le_remove_advertising_data()
+ */
+int bt_adapter_le_clear_advertising_data(bt_advertiser_h advertiser, bt_adapter_le_packet_type_e pkt_type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Start advertising with passed advertiser and advertising parameters.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @details Once Bluetooth advertising is started, nearby Bluetooth LE(Low Energy) supported
+ * devices can know this device's existence. And one of them can make a connection reqeust,
+ * if it is allowed.
+ *
+ * @param[in] advertiser The handle of advertiser
+ * @param[in] adv_params The parameters of advertising \n
+ * If NULL is passed, default values which are defined in driver / controller are used.
+ * @param[in] cb The callback to report the result of this function
+ * @param[in] user_data The user data to be passed when callback is called
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation is now in progress
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post This function invokes bt_adapter_le_advertising_state_changed_cb().
+ *
+ * @see bt_adapter_le_stop_advertising()
+ * @see bt_adapter_le_advertising_state_changed_cb()
+ */
+int bt_adapter_le_start_advertising(bt_advertiser_h advertiser, bt_adapter_le_advertising_params_s *adv_params,
+ bt_adapter_le_advertising_state_changed_cb cb, void *user_data);
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Stops the advertising.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] advertiser The handle of advertiser
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOT_IN_PROGRESS Operation is not in progress
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The advertising must be going on with bt_adapter_le_start_advertising().
+ * @post This function invokes bt_adapter_le_advertising_state_changed_cb().
+ *
+ * @see bt_adapter_le_start_advertising()
+ * @see bt_adapter_le_advertising_state_changed_cb()
+ */
+int bt_adapter_le_stop_advertising(bt_advertiser_h advertiser);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the Privacy feature state of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] enable_privacy The privacy feature to set/unset.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_LE_ENABLED.
+ *
+ */
+int bt_adapter_le_enable_privacy(bool enable_privacy);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Creates a bond with a remote Bluetooth device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks A bond can be destroyed by bt_device_destroy_bond().\n
+ * The bonding request can be cancelled by bt_device_cancel_bonding().
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device with which the bond should be created
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
+ * @post This function invokes bt_device_bond_created_cb().
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_cancel_bonding()
+ * @see bt_device_destroy_bond()
+ * @see bt_device_set_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+int bt_device_create_bond(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Creates a bond with a remote Bluetooth device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @remarks A bond can be destroyed by bt_device_destroy_bond().\n
+ * The bonding request can be cancelled by bt_device_cancel_bonding().
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device with which the bond should be created
+ * @param[in] conn_type The connection type(LE or BREDR) to create bond with remote device
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
+ * @post This function invokes bt_device_bond_created_cb().
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_device_create_bond()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_cancel_bonding()
+ * @see bt_device_destroy_bond()
+ * @see bt_device_set_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+int bt_device_create_bond_by_type(const char *remote_address,
+ bt_device_connection_link_type_e conn_type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Cancels the bonding process.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks Use this function when the remote Bluetooth device is not responding to the
+ * bond request or you wish to cancel the bonding request.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOT_IN_PROGRESS Operation not in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The creating a bond must be in progress by bt_device_create_bond().
+ *
+ * @see bt_device_create_bond()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_set_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+int bt_device_cancel_bonding(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Destroys the bond, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device to remove bonding
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ * @post This function invokes bt_device_bond_destroyed_cb().
+ *
+ * @see bt_device_create_bond()
+ * @see bt_device_bond_destroyed_cb()
+ * @see bt_device_set_bond_destroyed_cb()
+ * @see bt_device_unset_bond_destroyed_cb()
+ */
+int bt_device_destroy_bond(const char *remote_address);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Sets an alias for the bonded device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device
+ * @param[in] alias The alias of the remote Bluetooth device
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ *
+ * @see bt_device_create_bond()
+ */
+int bt_device_set_alias(const char *remote_address, const char *alias);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Sets the authorization of a bonded device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks Once a device is authorized, you don't need to receive a confirmation.
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device to authorize
+ * @param[in] authorization_state The Bluetooth authorization state
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ * @post bt_device_authorization_changed_cb() will be invoked.
+ *
+ * @see bt_device_create_bond()
+ * @see bt_device_authorization_changed_cb()
+ * @see bt_device_set_authorization_changed_cb()
+ * @see bt_device_unset_authorization_changed_cb()
+ */
+int bt_device_set_authorization(const char *remote_address, bt_device_authorization_e authorization_state);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Starts the search for services supported by the specified device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks If creating a bond succeeds, which means bt_device_bond_created_cb() is called with result #BT_ERROR_NONE,
+ * then you don't need to run this function.\n
+ * The service search takes a couple of seconds to complete normally. \n
+ * The service search can be canceled by bt_device_cancel_service_search().
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device whose services need to be checked
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device not bonded
+ * @retval #BT_ERROR_SERVICE_SEARCH_FAILED Service search failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ * @post This function invokes bt_device_service_searched_cb().
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_device_create_bond()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_service_searched_cb()
+ * @see bt_device_cancel_service_search()
+ * @see bt_device_set_service_searched_cb()
+ * @see bt_device_unset_service_searched_cb()
+ */
+int bt_device_start_service_search(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Cancels service search process.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device not bonded
+ * @retval #BT_ERROR_NOT_IN_PROGRESS Operation not in progress
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The service search must be in progress by bt_device_start_service_search().
+ *
+ * @see bt_device_start_service_search()
+ * @see bt_device_service_searched_cb()
+ * @see bt_device_set_service_searched_cb()
+ * @see bt_device_unset_service_searched_cb()
+ */
+int bt_device_cancel_service_search(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Gets the connected profiles.
+ * @since_tizen 2.3
+ * @param[in] remote_address The address of the remote device
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_device_connected_profile() will be invoked.
+ * @see bt_device_connected_profile()
+ */
+int bt_device_foreach_connected_profiles(const char *remote_address, bt_device_connected_profile callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Gets the profile connected status.
+ * @since_tizen 2.3
+ * @param[in] remote_address The address of the remote device
+ * @param[in] bt_profile wish to know bt_profile
+ * @param[out] connected_status the connected status
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_device_is_profile_connected(const char *remote_address, bt_profile_e bt_profile,
+ bool *connected_status);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Registers a callback function to be invoked when the bond creates.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_device_bond_created_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+int bt_device_set_bond_created_cb(bt_device_bond_created_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_bond_created_cb()
+ */
+int bt_device_unset_bond_created_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Registers a callback function to be invoked when the bond destroys.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_device_bond_destroyed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_bond_destroyed_cb()
+ * @see bt_device_unset_bond_destroyed_cb()
+ */
+int bt_device_set_bond_destroyed_cb(bt_device_bond_destroyed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_bond_destroyed_cb()
+ */
+int bt_device_unset_bond_destroyed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Registers a callback function to be invoked when the authorization of device changes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_device_authorization_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_authorization_changed_cb()
+ * @see bt_device_set_authorization_changed_cb()
+ * @see bt_device_unset_authorization_changed_cb()
+ */
+int bt_device_set_authorization_changed_cb(bt_device_authorization_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_authorization_changed_cb()
+ */
+int bt_device_unset_authorization_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Registers a callback function to be invoked when the process of service search finishes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_device_service_searched_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_service_searched_cb()
+ * @see bt_device_unset_service_searched_cb()
+ */
+int bt_device_set_service_searched_cb(bt_device_service_searched_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_service_searched_cb()
+ */
+int bt_device_unset_service_searched_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Registers a callback function to be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_device_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_device_connection_state_changed_cb()
+ * @see bt_device_unset_connection_state_changed_cb()
+ */
+int bt_device_set_connection_state_changed_cb(bt_device_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Unregisters the callback function to be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_device_set_connection_state_changed_cb()
+ */
+int bt_device_unset_connection_state_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Registers a rfcomm server socket with a specific UUID.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks A socket can be destroyed by bt_socket_destroy_rfcomm().
+ *
+ * @param[in] service_uuid The UUID of service to provide
+ * @param[out] socket_fd The file descriptor of socket to listen
+ * @return 0 on success, otherwise a negative error value.
+ *
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ *
+ * @see bt_socket_listen_and_accept_rfcomm()
+ * @see bt_socket_destroy_rfcomm()
+ */
+int bt_socket_create_rfcomm(const char *service_uuid, int *socket_fd);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Removes the rfcomm server socket which was created using bt_socket_create_rfcomm().
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks If callback function bt_socket_connection_state_changed_cb() is set and the remote Bluetooth device is connected,
+ * then bt_socket_connection_state_changed_cb() will be called when this function is finished successfully.
+ *
+ * @param[in] socket_fd The file descriptor of socket (which was created using bt_socket_create_rfcomm()) to destroy
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The socket must be created with bt_socket_create_rfcomm().
+ * @post If callback function bt_socket_connection_state_changed_cb() is set and the remote Bluetooth device is connected,
+ * then bt_socket_connection_state_changed_cb() will be called.
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_destroy_rfcomm(int socket_fd);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Starts listening on passed rfcomm socket and accepts connection requests.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @details Pop-up is shown automatically when a RFCOMM connection is requested.
+ * bt_socket_connection_state_changed_cb() will be called with
+ * #BT_SOCKET_CONNECTED if you click "yes" and connection is finished successfully.
+ * @param[in] socket_fd The file descriptor of socket on which start to listen
+ * @param[in] max_pending_connections The maximum number of pending connections
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The socket must be created with bt_socket_create_rfcomm().
+ * @post If callback function bt_socket_connection_state_changed_cb() is set,
+ * then bt_socket_connection_state_changed_cb() will be called when the remote Bluetooth device is connected.
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_listen_and_accept_rfcomm(int socket_fd, int max_pending_connections);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Starts listening on passed rfcomm socket.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @details bt_socket_connection_requested_cb() will be called when a RFCOMM connection is requested.
+ *
+ * @param[in] socket_fd The file descriptor socket on which start to listen
+ * @param[in] max_pending_connections The number of pending connections
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The socket must be created with bt_socket_create_rfcomm().
+ * @post This function invokes bt_socket_connection_state_changed_cb().
+ *
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_set_connection_requested_cb()
+ * @see bt_socket_unset_connection_requested_cb()
+ * @see bt_socket_connection_requested_cb()
+ */
+int bt_socket_listen(int socket_fd, int max_pending_connections);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Accepts a connection request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] requested_socket_fd The file descriptor of socket on which a connection is requested
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The connection is requested by bt_socket_connection_requested_cb().
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_connection_requested_cb()
+ * @see bt_socket_listen()
+ * @see bt_socket_reject()
+*/
+int bt_socket_accept(int requested_socket_fd);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Rejects a connection request.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] socket_fd The file descriptor of socket on which a connection is requested
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The connection is requested by bt_socket_connection_requested_cb().
+ * @see bt_socket_create_rfcomm()
+ * @see bt_socket_connection_requested_cb()
+ * @see bt_socket_listen()
+ * @see bt_socket_accept()
+ */
+int bt_socket_reject(int socket_fd);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Connects to a specific RFCOMM based service on a remote Bluetooth device UUID, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks A connection can be disconnected by bt_socket_disconnect_rfcomm().
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device
+ * @param[in] service_uuid The UUID of service provided by the remote Bluetooth device
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The remote device must be discoverable with bt_adapter_start_device_discovery().
+ * @pre The bond with the remote device must be created with bt_device_create_bond().
+ * @post This function invokes bt_socket_connection_state_changed_cb().
+ *
+ * @see bt_device_create_bond()
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_device_start_service_search()
+ * @see bt_socket_disconnect_rfcomm()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_connect_rfcomm(const char *remote_address, const char *service_uuid);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Disconnects the RFCOMM connection with the given file descriptor of conneted socket.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] socket_fd The file descriptor of socket to close which was received using bt_socket_connection_state_changed_cb().
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The connection must be established.
+ *
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_disconnect_rfcomm(int socket_fd);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Sends data to the connected device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remark The specific error code can be obtained using the get_last_result() method. Error codes are described in Exception section.
+ *
+ * @param[in] socket_fd The file descriptor of connected socket which was received using bt_socket_connection_state_changed_cb()
+ * @param[in] data The data to be sent
+ * @param[in] length The length of data to be sent
+ *
+ * @return the number of bytes written (zero indicates nothing was written).
+ * @retval On error, -1 is returned, and errno is set appropriately. See write 2 man page.
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @exception BT_ERROR_NOT_INITIALIZED Not initialized
+ * @exception BT_ERROR_PERMISSION_DENIED Permission denied
+ * @exception BT_ERROR_AGAIN Resource temporarily unavailable
+ *
+ * @pre The connection must be established.
+ *
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_send_data(int socket_fd, const char *data, int length);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Register a callback function that will be invoked when you receive data.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_socket_data_received_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_socket_data_received_cb()
+ * @see bt_socket_set_data_received_cb()
+ * @see bt_socket_unset_data_received_cb()
+ */
+int bt_socket_set_data_received_cb(bt_socket_data_received_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_socket_data_received_cb()
+ * @see bt_socket_set_data_received_cb()
+ */
+int bt_socket_unset_data_received_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Register a callback function that will be invoked when a RFCOMM connection is requested.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post If you listen a socket by bt_socket_listen(), bt_socket_connection_requested_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_socket_unset_connection_requested_cb()
+ */
+int bt_socket_set_connection_requested_cb(bt_socket_connection_requested_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_socket_set_connection_requested_cb()
+ * @see bt_socket_connection_requested_cb()
+ */
+int bt_socket_unset_connection_requested_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Register a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_socket_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+int bt_socket_set_connection_state_changed_cb(bt_socket_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_socket_connection_state_changed_cb()
+ * @see bt_socket_set_connection_state_changed_cb()
+ */
+int bt_socket_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Initializes the Bluetooth OPP server requested by bt_opp_server_push_requested_cb().
+ * @since_tizen 2.3
+ * @details The popup appears when an OPP connection is requested from a remote device.
+ * If you accept the request, then connection will be established and bt_opp_server_push_requested_cb() will be called.
+ * At that time, you can call either bt_opp_server_accept() or bt_opp_server_reject().
+ * @remarks This function must be called to start Bluetooth OPP server. You must free all resources of the Bluetooth service
+ * by calling bt_opp_server_deinitialize() if Bluetooth OPP service is no longer needed.
+ * @param[in] destination The destination path
+ * @param[in] push_requested_cb The callback called when a push is requested
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @see bt_opp_server_push_requested_cb()
+ * @see bt_opp_server_deinitialize()
+ * @see bt_opp_server_accept()
+ * @see bt_opp_server_reject()
+ */
+int bt_opp_server_initialize(const char *destination, bt_opp_server_push_requested_cb push_requested_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Initializes the Bluetooth OPP server requested by bt_opp_server_connection_requested_cb().
+ * @since_tizen 2.3
+ * @details No popup appears when an OPP connection is requested from a remote device.
+ * Instead, @a connection_requested_cb() will be called.
+ * At that time, you can call either bt_opp_server_accept() or bt_opp_server_reject().
+ * @remarks This function must be called to start Bluetooth OPP server. \n
+ * You must free all resources of the Bluetooth service by calling bt_opp_server_deinitialize() if Bluetooth OPP service is no longer needed.
+ * @param[in] destination The destination path
+ * @param[in] connection_requested_cb The callback called when an OPP connection is requested
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @see bt_opp_server_connection_requested_cb()
+ * @see bt_opp_server_deinitialize()
+ * @see bt_opp_server_accept_connection()
+ * @see bt_opp_server_reject_connection()
+ */
+int bt_opp_server_initialize_by_connection_request(const char *destination, bt_opp_server_connection_requested_cb connection_requested_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Denitializes the Bluetooth OPP server.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @see bt_opp_server_initialize()
+ * @see bt_opp_server_deinitialize()
+ */
+int bt_opp_server_deinitialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Accepts the push request from the remote device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks If you initialize OPP server by bt_opp_server_initialize_by_connection_request(), then name is ignored.
+ * You can cancel the pushes by bt_opp_server_cancel_transfer() with transfer_id.
+ * @param[in] progress_cb The callback called when a file is being transfered
+ * @param[in] finished_cb The callback called when a transfer is finished
+ * @param[in] name The name to store. This can be NULL if you initialize OPP server by bt_opp_server_initialize_by_connection_request().
+ * @param[in] user_data The user data to be passed to the callback function
+ * @param[out] transfer_id The ID of transfer
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @see bt_opp_server_reject()
+ */
+int bt_opp_server_accept(bt_opp_server_transfer_progress_cb progress_cb, bt_opp_server_transfer_finished_cb finished_cb, const char *name,
+ void *user_data, int *transfer_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Rejects the push request from the remote device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @see bt_opp_server_accept()
+ */
+int bt_opp_server_reject(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Cancels the transfer.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] transfer_id The ID of transfer
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @see bt_opp_server_accept_connection()
+ * @see bt_opp_server_accept()
+ */
+int bt_opp_server_cancel_transfer(int transfer_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Sets the destination path of file to be pushed.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] destination The destination path of file to be pushed
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @see bt_opp_server_initialize()
+ */
+int bt_opp_server_set_destination(const char *destination);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Initializes the Bluetooth OPP client.
+ * @since_tizen 2.3
+ * @remarks This function must be called before Bluetooth OPP client starts. \n
+ * You must free all resources of the Bluetooth service by calling bt_opp_client_deinitialize()
+ * if Bluetooth OPP service is no longer needed.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @see bt_opp_client_deinitialize()
+ */
+int bt_opp_client_initialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Denitializes the Bluetooth OPP client.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @see bt_opp_client_initialize()
+ */
+int bt_opp_client_deinitialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Adds file to be pushed.
+ * @since_tizen 2.3
+ * @param[in] file The path of file to be pushed
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @see bt_opp_client_clear_files()
+ * @see bt_opp_client_push_files()
+ */
+int bt_opp_client_add_file(const char *file);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Adds file to be pushed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @see bt_opp_client_add_file()
+ * @see bt_opp_client_push_files()
+ */
+int bt_opp_client_clear_files(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Pushes the file to the remote device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @details At first, bt_opp_client_push_responded_cb() will be called when OPP server responds to the push request.
+ * After connection is established, bt_opp_client_push_progress_cb() will be called repeatedly until a file is tranfered completely.
+ * If you send several files, then bt_opp_client_push_progress_cb() with another file will be called repeatedly until the file is tranfered completely.
+ * bt_opp_client_push_finished_cb() will be called when the push request is finished.
+ * @param[in] remote_address The remote address
+ * @param[in] responded_cb The callback called when OPP server responds to the push request
+ * @param[in] progress_cb The callback called when each file is being transfered
+ * @param[in] finished_cb The callback called when the push request is finished
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_NOW_IN_PROGRESS Operation now in progress
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @see bt_opp_client_initialize()
+ * @see bt_opp_client_cancel_push
+ */
+int bt_opp_client_push_files(const char *remote_address, bt_opp_client_push_responded_cb responded_cb,
+ bt_opp_client_push_progress_cb progress_cb, bt_opp_client_push_finished_cb finished_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Cancels the push request in progress, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre bt_opp_client_push_files() must be called.
+ * @post bt_opp_client_push_finished_cb() will be invoked with result #BT_ERROR_CANCELLED,
+ * which is a parameter of bt_opp_client_push_files().
+ * @see bt_opp_client_initialize()
+ * @see bt_opp_client_push_files()
+ */
+int bt_opp_client_cancel_push(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Initializes the Bluetooth HID(Human Interface Device) Host.
+ * @since_tizen 2.3
+ * @remarks This function must be called before Bluetooth HID Host starts. \n
+ * You must free all resources of the Bluetooth service by calling bt_hid_host_deinitialize()
+ * if Bluetooth HID Host service is no longer needed.
+ * @param[in] connection_cb The callback called when the connection state is changed
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_hid_host_deinitialize()
+ */
+int bt_hid_host_initialize(bt_hid_host_connection_state_changed_cb connection_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Deinitializes the Bluetooth HID(Human Interface Device) Host.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The Bluetooth HID service must be initialized with bt_hid_host_initialize().
+ * @see bt_hid_host_initialize()
+ */
+int bt_hid_host_deinitialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Connects the remote device with the HID(Human Interface Device) service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address The remote address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The local device must be bonded with the remote device by bt_device_create_bond().
+ * @pre The Bluetooth HID service must be initialized with bt_hid_host_initialize().
+ * @post bt_hid_host_connection_state_changed_cb() will be invoked.
+ * @see bt_hid_host_disconnect()
+ * @see bt_hid_host_connection_state_changed_cb()
+ */
+int bt_hid_host_connect(const char *remote_address);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Disconnects the remote device with the HID(Human Interface Device) service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address The remote address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected by bt_hid_host_connect().
+ * @post bt_hid_host_connection_state_changed_cb() will be invoked.
+ * @see bt_hid_host_connect()
+ * @see bt_hid_host_connection_state_changed_cb()
+ */
+int bt_hid_host_disconnect(const char *remote_address);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Initializes the Bluetooth profiles related with audio.
+ * @since_tizen 2.3
+ * @remarks This function must be called before Bluetooth profiles related with audio starts. \n
+ * You must free all resources of the this service by calling bt_audio_deinitialize()
+ * if Bluetooth profiles related with audio service is no longer needed.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_audio_deinitialize()
+ */
+int bt_audio_initialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Deinitializes the Bluetooth profiles related with audio.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ */
+int bt_audio_deinitialize(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Connects the remote device with the given audio profile, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @details If you input type as #BT_AUDIO_PROFILE_TYPE_ALL and connection request succeeds, then bt_audio_connection_state_changed_cb() will be called twice
+ * when #BT_AUDIO_PROFILE_TYPE_HSP_HFP is connected and #BT_AUDIO_PROFILE_TYPE_A2DP is connected.
+ * @param[in] remote_address The remote address
+ * @param[in] type The type of audio profile
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @pre The local device must be bonded with the remote device by bt_device_create_bond().
+ * @post bt_audio_connection_state_changed_cb() will be invoked.
+ * @see bt_audio_disconnect()
+ * @see bt_audio_connection_state_changed_cb()
+ */
+int bt_audio_connect(const char *remote_address, bt_audio_profile_type_e type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Disconnects the remote device with the given audio profile, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @details If you input type as #BT_AUDIO_PROFILE_TYPE_ALL and disconnection request succeeds, then bt_audio_connection_state_changed_cb() will be called twice
+ * when #BT_AUDIO_PROFILE_TYPE_HSP_HFP is disconnected and #BT_AUDIO_PROFILE_TYPE_A2DP is disconnected.
+ * @param[in] remote_address The remote address
+ * @param[in] type The type of audio profile
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The remote device must be connected by bt_audio_connect().
+ * @post bt_audio_connection_state_changed_cb() will be invoked.
+ * @see bt_audio_connect()
+ * @see bt_audio_connection_state_changed_cb()
+ */
+int bt_audio_disconnect(const char *remote_address, bt_audio_profile_type_e type);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Registers a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_audio_connection_state_changed_cb()
+ * @see bt_panu_unset_connection_state_changed_cb()
+ */
+int bt_audio_set_connection_state_changed_cb(bt_audio_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Unregisters a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_audio_connection_state_changed_cb()
+ * @see bt_audio_set_connection_state_changed_cb()
+ */
+int bt_audio_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Opens a SCO(Synchronous Connection Oriented link) to connected remote device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_ALREADY_DONE Operation is already done
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @post bt_ag_sco_state_changed_cb() will be invoked.
+ * @see bt_ag_close_sco()
+ * @see bt_ag_sco_state_changed_cb()
+ * @see bt_audio_connect()
+ */
+int bt_ag_open_sco(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Closes an opened SCO(Synchronous Connection Oriented link), asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The SCO must be opened with bt_ag_open_sco().
+ * @post bt_ag_sco_state_changed_cb() will be invoked.
+ * @see bt_ag_open_sco()
+ * @see bt_ag_sco_state_changed_cb()
+ */
+int bt_ag_close_sco(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Checks whether an opened SCO(Synchronous Connection Oriented link) exists or not.
+ * @since_tizen 2.3
+ * @param[out] opened The SCO status: (@c true = opened, @c false = not opened)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_ag_open_sco()
+ * @see bt_ag_close_sco()
+ */
+int bt_ag_is_sco_opened(bool *opened);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Registers a callback function that will be invoked when the SCO(Synchronous Connection Oriented link) state is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_sco_state_changed_cb()
+ * @see bt_ag_unset_sco_state_changed_cb()
+ */
+int bt_ag_set_sco_state_changed_cb(bt_ag_sco_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Unregisters a callback function that will be invoked when the SCO(Synchronous Connection Oriented link) state is changed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_sco_state_changed_cb()
+ * @see bt_ag_set_sco_state_changed_cb()
+ */
+int bt_ag_unset_sco_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the call event to the remote bluetooth device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @remarks Before notifying #BT_AG_CALL_EVENT_ANSWERED or #BT_AG_CALL_EVENT_DIALING, you should open SCO(Synchronous Connection Oriented link)
+ * if Bluetooth Hands-Free need SCO connection.
+ * @param[in] event The call event
+ * @param[in] call_id The call ID
+ * @param[in] phone_number The phone number. You must set this value in case of #BT_AG_CALL_EVENT_DIALING and #BT_AG_CALL_EVENT_INCOMING.
+ * In other cases, this value can be NULL.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @see bt_audio_connect()
+ */
+int bt_ag_notify_call_event(bt_ag_call_event_e event, unsigned int call_id, const char *phone_number);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the call list to the remote bluetooth device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] list The call list
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @see bt_audio_connect()
+ */
+int bt_ag_notify_call_list(bt_call_list_h list);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the state of voice recognition.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] state The state of voice recognition: (@c true = enabled, @c false = disabled)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @see bt_audio_connect()
+ */
+int bt_ag_notify_voice_recognition_state(bool state);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Registers a callback function that will be invoked when a call handling event happened from Hands-Free.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_call_handling_event_cb()
+ * @see bt_ag_unset_call_handling_event_cb()
+ */
+int bt_ag_set_call_handling_event_cb(bt_ag_call_handling_event_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Unregisters a callback function that will be invoked when a call handling event happened from Hands-Free.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_call_handling_event_cb()
+ * @see bt_ag_set_call_handling_event_cb()
+ */
+int bt_ag_unset_call_handling_event_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Registers a callback function that will be invoked when a multi call handling event happened from Hands-Free.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_multi_call_handling_event_cb()
+ * @see bt_ag_unset_multi_call_handling_event_cb()
+ */
+int bt_ag_set_multi_call_handling_event_cb(bt_ag_multi_call_handling_event_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Unregisters a callback function that will be invoked when a multi call handling event happened from Hands-Free.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_multi_call_handling_event_cb()
+ * @see bt_ag_set_multi_call_handling_event_cb()
+ */
+int bt_ag_unset_multi_call_handling_event_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Registers a callback function that will be invoked when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_dtmf_transmitted_cb()
+ * @see bt_ag_unset_dtmf_transmitted_cb()
+ */
+int bt_ag_set_dtmf_transmitted_cb(bt_ag_dtmf_transmitted_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Unregisters a callback function that will be invoked when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_dtmf_transmitted_cb()
+ * @see bt_ag_set_dtmf_transmitted_cb()
+ */
+int bt_ag_unset_dtmf_transmitted_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the speaker gain to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @details This function sends a signal to the remote device. This signal has the gain value.
+ * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
+ * When the speaker gain of remote device is changed to the requested gain, bt_audio_speaker_gain_changed_cb() will be called.
+ * @param[in] gain The gain of speaker (0 ~ 15)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
+ * @see bt_ag_get_speaker_gain()
+ * @see bt_ag_set_speaker_gain_changed_cb()
+ * @see bt_ag_unset_speaker_gain_changed_cb()
+ */
+int bt_ag_notify_speaker_gain(int gain);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Gets the current speaker gain of the remote device.
+ * @since_tizen 2.3
+ * @details This function gets the value of speaker gain of the remote device.
+ * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
+ * @param[out] gain The gain of speaker (0 ~ 15)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
+ * @see bt_ag_notify_speaker_gain()
+ * @see bt_ag_set_speaker_gain_changed_cb()
+ * @see bt_ag_unset_speaker_gain_changed_cb()
+ */
+int bt_ag_get_speaker_gain(int *gain);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Checks whether the remoted device enables NREC(Noise Reduction and Echo Canceling) or not.
+ * @since_tizen 2.3
+ * @param[out] enabled The NREC status: (@c true = enabled, @c false = not enabled)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
+ * @see bt_audio_connect()
+ */
+int bt_ag_is_nrec_enabled(bool *enabled);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Registers a callback function that will be invoked when the speaker gain of the remote device is changed.
+ * @since_tizen 2.3
+ * @details This function let you know the change of the speaker gain of the remote device.
+ * @a gain is represented on a scale from 0 to 15. This value is absolute value relating to a particular volume level.
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_unset_speaker_gain_changed_cb()
+ */
+int bt_ag_set_speaker_gain_changed_cb(bt_ag_speaker_gain_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Unregisters a callback function that will be invoked when the speaker gain of the remote device is changed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_set_speaker_gain_changed_cb()
+ */
+int bt_ag_unset_speaker_gain_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Registers a callback function that will be invoked when the microphone gain of the remote device is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_unset_microphone_gain_changed_cb()
+ */
+int bt_ag_set_microphone_gain_changed_cb(bt_ag_microphone_gain_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Unregisters a callback function that will be invoked when the microphone gain of the remote device is changed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_SUPPORTED Not supported
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_set_microphone_gain_changed_cb()
+ */
+int bt_ag_unset_microphone_gain_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
+ * @brief Creates a handle of call list.
+ * @since_tizen 2.3
+ * @param[out] list The handle of call list
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @see bt_call_list_destroy()
+ */
+int bt_call_list_create(bt_call_list_h *list);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
+ * @brief Destroys the handle of call list.
+ * @since_tizen 2.3
+ * @param[in] list The handle of call list
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @see bt_call_list_create()
+ */
+int bt_call_list_destroy(bt_call_list_h list);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
+ * @brief Resets the handle of call list.
+ * @since_tizen 2.3
+ * @param[in] list The handle of call list
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @see bt_call_list_create()
+ */
+int bt_call_list_reset(bt_call_list_h list);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_CALL_MODULE
+ * @brief Adds a call to the handle of call list.
+ * @since_tizen 2.3
+ * @param[in] list The handle of call list
+ * @param[in] call_id The call ID
+ * @param[in] state The state of audio gate call
+ * @param[in] phone_number The phone number. You must set this value in case of #BT_AG_CALL_EVENT_DIALING and #BT_AG_CALL_EVENT_INCOMING.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @see bt_call_list_create()
+ */
+int bt_call_list_add(bt_call_list_h list, unsigned int call_id, bt_ag_call_state_e state, const char *phone_number);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Initializes the Bluetooth AVRCP(Audio/Video Remote Control Profile) service.
+ * @since_tizen 2.3
+ * @remarks This function must be called before Bluetooth AVRCP service. \n
+ * You must free all resources of the this service by calling bt_avrcp_target_deinitialize()
+ * if Bluetooth AVRCP service is no longer needed.
+ * @param[in] callback The callback function called when the connection state is changed
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_target_deinitialize()
+ */
+int bt_avrcp_target_initialize(bt_avrcp_target_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Deinitializes the Bluetooth AVRCP(Audio/Video Remote Control Profile) service.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth audio service must be initialized with bt_avrcp_target_initialize().
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_deinitialize(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Notifies the equalize state to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] state The state of equalizer
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_equalizer_state(bt_avrcp_equalizer_state_e state);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Notifies the repeat mode to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] mode The repeat mode
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_repeat_mode(bt_avrcp_repeat_mode_e mode);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Notifies the shuffle mode to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] mode The repeat mode
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_shuffle_mode(bt_avrcp_shuffle_mode_e mode);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Notifies the scan mode to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] mode The scan mode
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_scan_mode(bt_avrcp_scan_mode_e mode);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Notifies the player state to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] state The player state
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_player_state(bt_avrcp_player_state_e state);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Notifies the current position of song to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] position The current position in milliseconds
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_position(unsigned int position);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Notifies the track to the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] title The title of track
+ * @param[in] artist The artist of track
+ * @param[in] album The album of track
+ * @param[in] genre The genre of track
+ * @param[in] track_num The track number
+ * @param[in] total_tracks The number of all tracks
+ * @param[in] duration The duration of track in milliseconds
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_avrcp_target_connection_state_changed_cb()
+ * @see bt_avrcp_target_initialize()
+ */
+int bt_avrcp_target_notify_track(const char *title, const char *artist, const char *album, const char *genre, unsigned int track_num, unsigned int total_tracks, unsigned int duration);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Registers a callback function that will be invoked when the equalizer state is changed by the remote control device.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_unset_equalizer_state_changed_cb()
+ */
+int bt_avrcp_set_equalizer_state_changed_cb(bt_avrcp_equalizer_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Unregisters a callback function that will be invoked when the equalizer state is changed by the remote control device.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_set_equalizer_state_changed_cb()
+ */
+int bt_avrcp_unset_equalizer_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Registers a callback function that will be invoked when the repeat mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_unset_repeat_mode_changed_cb()
+ */
+int bt_avrcp_set_repeat_mode_changed_cb(bt_avrcp_repeat_mode_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Unregisters a callback function that will be invoked when the repeat mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_set_repeat_mode_changed_cb()
+ */
+int bt_avrcp_unset_repeat_mode_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Registers a callback function that will be invoked when the shuffle mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_unset_shuffle_mode_changed_cb()
+ */
+int bt_avrcp_set_shuffle_mode_changed_cb(bt_avrcp_shuffle_mode_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Unregisters a callback function that will be invoked when the shuffle mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_set_shuffle_mode_changed_cb()
+ */
+int bt_avrcp_unset_shuffle_mode_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Registers a callback function that will be invoked when the scan mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_unset_scan_mode_changed_cb()
+ */
+int bt_avrcp_set_scan_mode_changed_cb(bt_avrcp_scan_mode_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Unregisters a callback function that will be invoked when the scan mode is changed by the remote control device.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @see bt_initialize()
+ * @see bt_avrcp_set_scan_mode_changed_cb()
+ */
+int bt_avrcp_unset_scan_mode_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Registers an application that acts as the @a Sink role of HDP(Health Device Profile).
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks The @a app_id must be released with free() by you.
+ * @param[in] data_type The data type of MDEP. This value is defined in ISO/IEEE 11073-20601 spec.
+ * For example, pulse oximeter is 0x1004 and blood pressure monitor is 0x1007.
+ * @param[out] app_id The ID of application
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_hdp_deactivate_sink()
+ */
+int bt_hdp_register_sink_app(unsigned short data_type, char **app_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Unregisters the given application that acts as the @a Sink role of HDP(Health Device Profile).
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] app_id The ID of application
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @see bt_hdp_register_sink_app()
+ */
+int bt_hdp_unregister_sink_app(const char *app_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Connects the remote device which acts as @a Source role, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address The remote address
+ * @param[in] app_id The ID of application
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Sink role of HDP must be registered with bt_hdp_register_sink_app().
+ * @pre The local device must be bonded with the remote device by bt_device_create_bond().
+ * @post bt_hdp_connected_cb() will be invoked.
+ * @see bt_hdp_disconnect()
+ * @see bt_hdp_set_connection_state_changed_cb()
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+int bt_hdp_connect_to_source(const char *remote_address, const char *app_id);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Disconnects the remote device, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address The remote address
+ * @param[in] channel The connected data channel
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @post bt_hdp_disconnected_cb() will be invoked.
+ * @see bt_hdp_set_connection_state_changed_cb()
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+int bt_hdp_disconnect(const char *remote_address, unsigned int channel);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Sends the data to the remote device.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] channel The connected data channel
+ * @param[in] data The data to send
+ * @param[in] size The size of data to send (byte)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected.
+ * @see bt_hdp_data_received_cb()
+ * @see bt_hdp_set_data_received_cb()
+ * @see bt_hdp_unset_data_received_cb()
+ */
+int bt_hdp_send_data(unsigned int channel, const char *data, unsigned int size);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Registers a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @param[in] connected_cb The callback function called when a connection is established
+ * @param[in] disconnected_cb The callback function called when a connection is disconnected
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+int bt_hdp_set_connection_state_changed_cb(bt_hdp_connected_cb connected_cb, bt_hdp_disconnected_cb disconnected_cb, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Unregisters a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_hdp_set_connection_state_changed_cb()
+ */
+int bt_hdp_unset_connection_state_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Registers a callback function that will be invoked when you receive the data.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_hdp_unset_data_received_cb()
+ */
+int bt_hdp_set_data_received_cb(bt_hdp_data_received_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Unregisters a callback function that will be invoked when you receive the data.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_hdp_set_data_received_cb()
+ */
+int bt_hdp_unset_data_received_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Gets the primary services of GATT(Generic Attribute Profile).
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] remote_address The address of the remote device
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post @a callback will be called if there are primary services.
+ * @see bt_gatt_primary_service_cb()
+ */
+int bt_gatt_foreach_primary_services(const char *remote_address, bt_gatt_primary_service_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Discovers the characteristics in service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] service The attribute handle of service
+ * @param[in] callback The result callback
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post @a callback will be called.
+ * @see bt_gatt_characteristics_discovered_cb()
+ */
+int bt_gatt_discover_characteristics(bt_gatt_attribute_h service, bt_gatt_characteristics_discovered_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Gets the UUID of service.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks @a uuid must be released with free() by you.
+ * @param[in] service The attribute handle of service
+ * @param[out] uuid The UUID of service
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ */
+int bt_gatt_get_service_uuid(bt_gatt_attribute_h service, char **uuid);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Gets the included services in service.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] service The attribute handle of service
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post @a callback will be called if there are included services.
+ * @see bt_gatt_included_service_cb()
+ */
+int bt_gatt_foreach_included_services(bt_gatt_attribute_h service, bt_gatt_included_service_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Registers a callback function that will be invoked when a characteristic value is changed.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_gatt_unset_characteristic_changed_cb()
+ */
+int bt_gatt_set_characteristic_changed_cb(bt_gatt_characteristic_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Unregisters a callback function that will be invoked when a characteristic is changed.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_gatt_set_characteristic_changed_cb()
+ */
+int bt_gatt_unset_characteristic_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Watches all the characteristic value changes of the service
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] service The attribute handle of service
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_gatt_unset_characteristic_changed_cb()
+ */
+int bt_gatt_watch_characteristic_changes(bt_gatt_attribute_h service);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Remove watching of all the characteristic value changes of the service
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] service The attribute handle of service
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_gatt_set_characteristic_changed_cb()
+ */
+int bt_gatt_unwatch_characteristic_changes(bt_gatt_attribute_h service);
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Gets the characteristic declaration.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @remarks @a uuid and @a value must be released with free() by you.
+ * @param[in] characteristic The attribute handle of characteristic
+ * @param[out] uuid The UUID of service
+ * @param[out] value The value of characteristic (byte array)
+ * @param[out] value_length The length of value
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_gatt_set_characteristic_value()
+ */
+int bt_gatt_get_characteristic_declaration(bt_gatt_attribute_h characteristic, char **uuid, unsigned char **value, int *value_length);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Sets the value of characteristic.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] characteristic The attribute handle of characteristic
+ * @param[in] value The value of characteristic (byte array)
+ * @param[in] value_length The length of value
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_gatt_get_characteristic_declaration()
+ */
+int bt_gatt_set_characteristic_value(bt_gatt_attribute_h characteristic, const unsigned char *value, int value_length);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Sets the value of characteristic request.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] characteristic The attribute handle of characteristic
+ * @param[in] value The value of characteristic (byte array)
+ * @param[in] value_length The length of value
+ * @param[in] callback The result callback
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_gatt_get_characteristic_declaration()
+ */
+int bt_gatt_set_characteristic_value_request(bt_gatt_attribute_h characteristic, const unsigned char *value,
+ int value_length, bt_gatt_characteristic_write_cb callback);
+
+/**
+* @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+* @brief Clones the attribute handle.
+* @since_tizen 2.3
+* @remarks @a clone must be released with bt_gatt_destroy_attribute_handle().
+* @param[out] clone The cloned attribute handle
+* @param[in] origin The origin attribute handle
+* @return 0 on success, otherwise negative error value.
+* @retval #BT_ERROR_NONE Successful
+* @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+* @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+* @see bt_gatt_destroy_attribute_handle()
+*/
+int bt_gatt_clone_attribute_handle(bt_gatt_attribute_h* clone, bt_gatt_attribute_h origin);
+
+/**
+* @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+* @brief Destroys the attribute handle.
+* @since_tizen 2.3
+* @param[in] handle The attribute handle
+* @return 0 on success, otherwise negative error value.
+* @retval #BT_ERROR_NONE Successful
+* @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+* @see bt_gatt_clone_attribute_handle()
+*/
+int bt_gatt_destroy_attribute_handle(bt_gatt_attribute_h handle);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Reads the value of characteristic from remote device
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] char_handle The attribute handle of characteristic
+ * @param[in] callback The result callback
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_gatt_get_characteristic_declaration()
+ */
+int bt_gatt_read_characteristic_value(bt_gatt_attribute_h char_handle,
+ bt_gatt_characteristic_read_cb callback);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Discovers the characteristic descriptors of a characteristic within its definition, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] characteristic_handle The attribute handle of characteristic
+ * @param[in] callback The result callback
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post @a callback will be called.
+ * @see bt_gatt_characteristic_descriptor_discovered_cb()
+ */
+int bt_gatt_discover_characteristic_descriptor(bt_gatt_attribute_h characteristic_handle,
+ bt_gatt_characteristic_descriptor_discovered_cb callback,
+ void *user_data);
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Sets the value of characteristic descriptor request.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ * @param[in] characteristic The attribute handle of characteristic
+ * @param[in] value The value of characteristic (byte array), desc handle, desc value
+ * @param[in] value_length The length of value
+ * @param[in] callback The result callback
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_gatt_get_characteristic_declaration()
+ */
+int bt_gatt_set_characteristic_desc_value_request(bt_gatt_attribute_h characteristic,
+ const unsigned char *value, int value_length,
+ bt_gatt_characteristic_write_cb callback);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Connect to a specific LE based service on a remote bluetooth dievice address, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @remarks A connection can be disconnected by bt_gatt_disconnect().
+ *
+ * @param[in] address The address of the remote Bluetooth device.
+ * @param[in] auto_connect The flag of the auto connection.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @pre The remote device must support le connection.
+ * @post This function invokes bt_gatt_connection_state_changed_cb().
+ *
+ * @see bt_initialize()
+ * @see bt_gatt_disconnect()
+ * @see bt_gatt_set_connection_state_changed_cb()
+ * @see bt_gatt_unset_connection_state_changed_cb()
+ * @see bt_gatt_connection_state_changed_cb()
+ */
+int bt_gatt_connect(const char *address, bool auto_connect);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Disconnect to LE connection with the given remote Bluetooth dievice address, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel public
+ * @privilege %http://tizen.org/privilege/bluetooth
+ *
+ * @param[in] address The address of the remote Bluetooth device
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The connection must be established.
+ * @post This function invokes bt_gatt_connection_state_changed_cb().
+ *
+ * @see bt_initialize()
+ * @see bt_gatt_connect()
+ * @see bt_gatt_set_connection_state_changed_cb()
+ * @see bt_gatt_unset_connection_state_changed_cb()
+ * @see bt_gatt_connection_state_changed_cb()
+ */
+int bt_gatt_disconnect(const char *address);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Registers a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to register.
+ * @param[in] user_data The user data to be passed to the callback function.
+ *
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid paramater
+ *
+ * @see bt_gatt_connect()
+ * @see bt_gatt_disconnect()
+ * @see bt_gatt_unset_connection_state_changed_cb()
+ */
+int bt_gatt_set_connection_state_changed_cb(bt_gatt_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Unregisters a callback function that will be invoked when the connection state is changed.
+ * @since_tizen 2.3
+ *
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @see bt_gatt_connect()
+ * @see bt_gatt_disconnect()
+ * @see bt_gatt_connection_state_changed_cb()
+ */
+int bt_gatt_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Initializes the Gatt Service.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_enable()
+ */
+int _bt_gatt_init_service(void);
+
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief DeInitializes the Gatt Service.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_enable()
+ * @see _bt_gatt_init_service(void)
+ */
+int _bt_gatt_deinit_service(void);
+
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Adds Gatt Service to the service interface.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] svc_uuid Gatt service uuid.
+ * @param[out] svc_path Object path of the GATT service.
+ * @remarks svc_path must be released with free() by you.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_enable()
+ */
+int bt_gatt_add_service(const char *svc_uuid,
+ char **svc_path);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Deletes a Gatt Service from the Gatt Server Database.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] svc_path Service path of the gatt service to remove.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_enable()
+ */
+int bt_gatt_remove_service(const char *svc_path);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Adds Gatt characteristic to the Characteristics interface.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] char_uuid Gatt characteristic uuid.
+ * @param[in] char_value Gatt characteristic value.
+ * @param[in] value_length Caracteristic value length.
+ * @param[in] char_flags Characteristic flags.
+ * @param[in] flags_length Caracteristic flags length.
+ * @param[in] svc_path service path to which this characteristic belongs to.
+ * @param[out] char_path characteristic path registered on the interface.
+ * @remarks char_path must be released with free() by you.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_enable()
+ */
+int bt_gatt_add_characteristic(const char *char_uuid,
+ const char *char_value, int value_length,
+ const char *char_flags[], int flags_length,
+ const char *svc_path, char **char_path);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Adds Gatt descriptor to the descriptor interface.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] desc_uuid Gatt descriptor uuid.
+ * @param[in] desc_value Gatt descriptor value.
+ * @param[in] desc_length Gatt descriptor value.
+ * @param[in] permissions Permissions for the descriptor.
+ * @param[in] char_path Characteristic path to which this descriptor should belong to.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_enable()
+ */
+int bt_gatt_add_descriptor(const char *desc_uuid,
+ const char *desc_value, int value_length,
+ const char *permissions, const char *char_path,
+ char **desc_path);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Registers the given service path (including characteristics and descriptor) with the Bluez.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] svc_path Gatt service path obtained from the add_service.
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre bt_gatt_add_service, bt_gatt_add_characteristic and bt_gatt_add_descriptor
+ * must be called before calling bt_gatt_register_service
+ *
+ * @see bt_adapter_enable()
+ * @see bt_gatt_add_service()
+ * @see bt_gatt_add_characteristic()
+ * @see bt_gatt_add_descriptor()
+ */
+int bt_gatt_register_service(const char *svc_path,
+ bt_gatt_remote_characteristic_write_cb callback,
+ void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Updates the existing characteristic value.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] char_path characteristic path registered on the interface.
+ * @param[in] char_value Gatt characteristic value.
+ * @param[in] value_length Characteristic value length.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @see bt_adapter_enable()
+ */
+int bt_gatt_update_characteristic(const char *char_path,
+ const char *char_value, int value_length);
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Delete Gatt Services from the Gatt Server Database.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege http://tizen.org/privilege/bluetooth.admin
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post @a callback will be called.
+ * @see bt_adapter_enable()
+ */
+int bt_gatt_delete_services(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Activates the NAP(Network Access Point).
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_ALREADY_DONE Operation is already done
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED
+ * @see bt_nap_deactivate()
+ */
+int bt_nap_activate(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Deactivates the NAP(Network Access Point).
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_ALREADY_DONE Operation is already done
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
+ * @see bt_nap_activate()
+ */
+int bt_nap_deactivate(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Disconnects the all PANUs(Personal Area Networking User) which are connected to you.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
+ * @see bt_nap_activate()
+ */
+int bt_nap_disconnect_all(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Disconnects the specified PANU(Personal Area Networking User) which is connected to you.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] remote_address The remote address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Bluetooth NAP service must be activated with bt_nap_activate().
+ * @see bt_nap_activate()
+ */
+int bt_nap_disconnect(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Registers a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_nap_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_nap_connection_state_changed_cb()
+ * @see bt_nap_unset_connection_state_changed_cb()
+ */
+int bt_nap_set_connection_state_changed_cb(bt_nap_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Unregisters a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_nap_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_nap_connection_state_changed_cb()
+ * @see bt_nap_set_connection_state_changed_cb()
+ */
+int bt_nap_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief Registers a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_nap_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_panu_connection_state_changed_cb()
+ * @see bt_panu_unset_connection_state_changed_cb()
+ */
+int bt_panu_set_connection_state_changed_cb(bt_panu_connection_state_changed_cb callback, void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief Unregisters a callback function that will be invoked when the connection state changes.
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_nap_connection_state_changed_cb() will be invoked.
+ * @see bt_initialize()
+ * @see bt_panu_connection_state_changed_cb()
+ * @see bt_panu_set_connection_state_changed_cb()
+ */
+int bt_panu_unset_connection_state_changed_cb(void);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief Connects the remote device with the PAN(Personal Area Networking) service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] remote_address The remote address
+ * @param[in] type The type of PAN service
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The local device must be bonded with the remote device by bt_device_create_bond().
+ * @post bt_panu_connection_state_changed_cb() will be invoked.
+ * @see bt_panu_disconnect()
+ * @see bt_panu_connection_state_changed_cb()
+ */
+int bt_panu_connect(const char *remote_address, bt_panu_service_type_e type);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief Disconnects the remote device with the PAN(Personal Area Networking) service, asynchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] remote_address The remote address
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_OUT_OF_MEMORY Out of memory
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The remote device must be connected by bt_panu_connect().
+ * @post bt_panu_connection_state_changed_cb() will be invoked.
+ * @see bt_panu_connect()
+ * @see bt_panu_connection_state_changed_cb()
+ */
+int bt_panu_disconnect(const char *remote_address);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief update LE connection.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_PERMISSION_DENIED Permission denied
+ * @pre The Bluetooth service must be initialized by bt_initialize().
+ * @pre The remote device must be connected with bt_gatt_connect().
+ */
+int bt_device_le_conn_update(const char *device_address,
+ const bt_le_conn_update_s *parameters);
+
+
+/**
+ * @}
+ */
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __TIZEN_NETWORK_BLUETOOTH_H__
--- /dev/null
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__
+#define __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__
+
+#include <dlog.h>
+#include <stdbool.h>
+#include <bluetooth-api.h>
+#include <bluetooth-audio-api.h>
+#include <bluetooth-telephony-api.h>
+#include <bluetooth-media-control.h>
+#include <bluetooth-hid-api.h>
+
+#include "bluetooth.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#undef LOG_TAG
+#define LOG_TAG "CAPI_NETWORK_BLUETOOTH"
+
+#define BT_INFO(fmt, args...) SLOGI(fmt, ##args)
+#define BT_DBG(fmt, args...) SLOGD(fmt, ##args)
+#define BT_ERR(fmt, args...) SLOGE(fmt, ##args)
+
+#define OPP_UUID "00001105-0000-1000-8000-00805f9b34fb"
+
+/**
+ * @internal
+ * @brief Bluetooth callback.
+ */
+typedef enum
+{
+ BT_EVENT_STATE_CHANGED = 0x00, /**< Adapter state is changed */
+ BT_EVENT_LE_STATE_CHANGED, /**< Adapter le state is changed */
+ BT_EVENT_NAME_CHANGED, /**< Adapter name is changed */
+ BT_EVENT_VISIBILITY_MODE_CHANGED, /**< Adapter visibility mode is changed */
+ BT_EVENT_VISIBILITY_DURATION_CHANGED, /**< Adapter visibility duration is changed */
+ BT_EVENT_DEVICE_DISCOVERY_STATE_CHANGED, /**< Device discovery state is changed */
+ BT_EVENT_LE_DEVICE_DISCOVERY_STATE_CHANGED, /**< LE Device discovery state is changed */
+ BT_EVENT_BOND_CREATED, /**< A bond is created */
+ BT_EVENT_BOND_DESTROYED, /**< A bond is destroyed */
+ BT_EVENT_AUTHORIZATION_CHANGED, /**< Authorization is changed */
+ BT_EVENT_SERVICE_SEARCHED, /**< Service search finish */
+ BT_EVENT_DATA_RECEIVED, /**< Data is received */
+ BT_EVENT_CONNECTION_STATE_CHANGED, /**< Connection state is changed */
+ BT_EVENT_RFCOMM_CONNECTION_REQUESTED, /**< RFCOMM connection is requested */
+ BT_EVENT_OPP_CONNECTION_REQUESTED, /**< OPP connection is requested */
+ BT_EVENT_OPP_PUSH_REQUESTED, /**< OPP push is requested */
+ BT_EVENT_OPP_SERVER_TRANSFER_PROGRESS, /**< OPP transfer progress */
+ BT_EVENT_OPP_SERVER_TRANSFER_FINISHED, /**< OPP transfer is completed */
+ BT_EVENT_OPP_CLIENT_PUSH_RESPONSED, /**< OPP client connection is reponsed */
+ BT_EVENT_OPP_CLIENT_PUSH_PROGRESS, /**< OPP client push progress */
+ BT_EVENT_OPP_CLIENT_PUSH_FINISHED, /**< OPP client push is finished */
+ BT_EVENT_PAN_CONNECTION_STATE_CHANGED, /**< PAN connection change */
+ BT_EVENT_NAP_CONNECTION_STATE_CHANGED, /**< NAP connection change */
+ BT_EVENT_HDP_CONNECTED, /**< HDP connection change */
+ BT_EVENT_HDP_DISCONNECTED, /**< HDP disconnection change */
+ BT_EVENT_HDP_DATA_RECEIVED, /**< HDP Data receive Callabck */
+ BT_EVENT_AUDIO_CONNECTION_STATUS, /**< Audio Connection change callback */
+ BT_EVENT_AG_SCO_CONNECTION_STATUS, /**< Audio - AG SCO Connection state change callback */
+ BT_EVENT_AG_CALL_HANDLING_EVENT, /**< Audio - AG call event callback */
+ BT_EVENT_AG_MULTI_CALL_HANDLING_EVENT, /**< Audio - AG 3-way call event callback */
+ BT_EVENT_AG_DTMF_TRANSMITTED, /**< Audio - DTMF tone sending request */
+ BT_EVENT_AG_MICROPHONE_GAIN_CHANGE, /**< Audio Microphone change callback */
+ BT_EVENT_AG_SPEAKER_GAIN_CHANGE, /**< Audio Speaker gain change callback */
+ BT_EVENT_AG_VENDOR_CMD, /**< Audio - XSAT Vendor cmd */
+ BT_EVENT_AVRCP_CONNECTION_STATUS, /**< AVRCP connection change callback */
+ BT_EVENT_AVRCP_EQUALIZER_STATE_CHANGED, /**< AVRCP equalizer state change callback */
+ BT_EVENT_AVRCP_REPEAT_MODE_CHANGED, /**< AVRCP repeat mode change callback */
+ BT_EVENT_AVRCP_SHUFFLE_MODE_CHANGED, /**< AVRCP equalizer mode change callback */
+ BT_EVENT_AVRCP_SCAN_MODE_CHANGED, /**< AVRCP scan mode change callback */
+ BT_EVENT_HID_CONNECTION_STATUS, /**< HID connection status callback */
+ BT_EVENT_DEVICE_CONNECTION_STATUS, /**< Device connection status callback */
+ BT_EVENT_GATT_CONNECTION_STATUS, /** < GATT connection status callback */
+ BT_EVENT_GATT_PRIM_SVC_DISCOVERED, /**< GATT Primary Service discovered callback */
+ BT_EVENT_GATT_CHARACTERISTIC_DISCOVERED, /**< GATT characteristic discovered callback */
+ BT_EVENT_GATT_CHARACTERISTIC_DESCRIPTOR_DISCOVERED, /**< GATT characteristic descriptor discovered callback */
+ BT_EVENT_GATT_VALUE_CHANGED, /**< GATT characteristic value changed callback */
+ BT_EVENT_GATT_READ_CHARACTERISTIC, /**< GATT characteristic value read callback */
+ BT_EVENT_GATT_WRITE_CHARACTERISTIC, /**< GATT characteristic value write callback */
+ BT_EVENT_GATT_SERVER_ON_WRITE_CHAR, /**< GATT characteristic value write callback */
+ BT_EVENT_ADVERTISING_STATE_CHANGED, /**< Advertising state changed callback */
+ BT_EVENT_MANUFACTURER_DATA_CHANGED, /**< Manufacturer data changed callback */
+ BT_EVENT_CONNECTABLE_CHANGED_EVENT, /**< Adapter connectable changed callback */
+ BT_EVENT_RSSI_ENABLED_EVENT, /**< RSSI Enabled callback */
+ BT_EVENT_RSSI_ALERT_EVENT, /**< RSSI Alert callback */
+ BT_EVENT_GET_RSSI_EVENT, /**< Get RSSI Strength callback */
+#ifdef TIZEN_WEARABLE
+ BT_EVENT_PBAP_CONNECTION_STATUS, /**< PBAP connection status callback */
+ BT_EVENT_PBAP_PHONEBOOK_SIZE, /**< PBAP Phonebook Size status callback */
+ BT_EVENT_PBAP_PHONEBOOK_PULL, /**< PBAP Phonebook Pull status callback */
+ BT_EVENT_PBAP_VCARD_LIST, /**< PBAP vCard List status callback */
+ BT_EVENT_PBAP_VCARD_PULL, /**< PBAP vCard Pull status callback */
+ BT_EVENT_PBAP_PHONEBOOK_SEARCH, /**< PBAP Phonebook Search status callback */
+ BT_EVENT_HF_SCO_CONNECTION_STATUS, /**< Audio - HF SCO Connection state change callback */
+ BT_EVENT_HF_SPEAKER_GAIN_CHANGE, /**< Audio - HF Speaker gain change callback */
+ BT_EVENT_HF_CALL_HANDLING_EVENT, /**< Audio - HF call event callback */
+ BT_EVENT_HF_VENDOR_DEP_CMD_EVENT, /**< Audio - HF Vendor Command callback */
+ BT_EVENT_HF_MULTI_CALL_HANDLING_EVENT, /**< Audio - HF 3-way call event callback */
+#endif
+} bt_event_e;
+
+/**
+ * @internal
+ */
+typedef struct {
+ int handle;
+
+ bt_adapter_le_advertising_state_changed_cb cb;
+ void *cb_data;
+
+ bt_adapter_le_advertising_params_s adv_params;
+
+ unsigned int adv_data_len;
+ char *adv_data;
+
+ unsigned int scan_rsp_data_len;
+ char *scan_rsp_data;
+
+ void *user_data;
+} bt_advertiser_s;
+
+/**
+ * @internal
+ */
+typedef struct bt_event_sig_event_slot_s
+{
+ int event_type;
+ const void *callback;
+ void *user_data;
+} bt_event_sig_event_slot_s;
+
+
+#define BT_CHECK_INPUT_PARAMETER(arg) \
+ if (arg == NULL) \
+ { \
+ LOGE("[%s] INVALID_PARAMETER(0x%08x)", __FUNCTION__, BT_ERROR_INVALID_PARAMETER); \
+ return BT_ERROR_INVALID_PARAMETER; \
+ }
+
+/**
+ * @internal
+ * @brief Check the initialzating status
+ */
+int _bt_check_init_status(void);
+
+#define BT_CHECK_INIT_STATUS() \
+ if (_bt_check_init_status() == BT_ERROR_NOT_INITIALIZED) \
+ { \
+ LOGE("[%s] NOT_INITIALIZED(0x%08x)", __FUNCTION__, BT_ERROR_NOT_INITIALIZED); \
+ return BT_ERROR_NOT_INITIALIZED; \
+ }
+
+/**
+ * @internal
+ * @brief Initialize Bluetooth LE adapter
+ */
+int _bt_le_adapter_init(void);
+
+/**
+ * @internal
+ * @brief Deinitialize Bluetooth LE adapter
+ */
+int _bt_le_adapter_deinit(void);
+
+/**
+ * @internal
+ * @brief Set the event callback.
+ */
+void _bt_set_cb(int events, void *callback, void *user_data);
+
+/**
+ * @internal
+ * @brief Unset the event callback.
+ */
+void _bt_unset_cb(int events);
+
+/**
+ * @internal
+ * @brief Check if the event callback exist or not.
+ */
+bool _bt_check_cb(int events);
+
+/**
+ * @internal
+ * @brief Convert Bluetooth F/W error codes to capi Bluetooth error codes.
+ */
+int _bt_get_error_code(int origin_error);
+
+
+/**
+ * @internal
+ * @brief Convert Bluetooth F/W bluetooth_device_info_t to capi bt_device_info_s.
+ */
+int _bt_get_bt_device_info_s(bt_device_info_s **dest_dev, bluetooth_device_info_t *source_dev);
+
+
+/**
+ * @internal
+ * @brief Free bt_device_info_s.
+ */
+void _bt_free_bt_device_info_s(bt_device_info_s *device_info);
+
+/**
+ * @internal
+ * @brief Convert Bluetooth F/W bluetooth_device_address_t to string.
+ */
+int _bt_convert_address_to_string(char **addr_str, bluetooth_device_address_t *addr_hex);
+
+
+/**
+ * @internal
+ * @brief Convert string to Bluetooth F/W bluetooth_device_address_t.
+ */
+void _bt_convert_address_to_hex(bluetooth_device_address_t *addr_hex, const char *addr_str);
+
+
+/**
+ * @internal
+ * @brief Convert error code to string.
+ */
+char* _bt_convert_error_to_string(int error);
+
+/**
+ * @internal
+ * @brief Convert the visibility mode
+ */
+bt_adapter_visibility_mode_e _bt_get_bt_visibility_mode_e(bluetooth_discoverable_mode_t mode);
+
+/**
+ * @internal
+ * @brief Since the Audio call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_audio_event_proxy(int event, bt_audio_event_param_t *param, void *user_data);
+
+#ifdef TIZEN_WEARABLE
+/**
+ * @internal
+ * @brief Since the HF call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_hf_event_proxy(int event, bt_hf_event_param_t *param, void *user_data);
+#endif
+
+/**
+ * @internal
+ * @brief Since the Telephony call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_telephony_event_proxy(int event, telephony_event_param_t *param, void *user_data);
+
+/**
+ * @internal
+ * @brief Since the AVRCP call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_avrcp_event_proxy(int event, media_event_param_t *param, void *user_data);
+
+/**
+ * @internal
+ * @brief Since the HID call back and event proxy call backs have different prototype it is wrapper function.
+ */
+void _bt_hid_event_proxy(int event, hid_event_param_t *param, void *user_data);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TIZEN_NETWORK_BLUETOOTH_PRIVATE_H__ */
--- /dev/null
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
+#define __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
+
+ #ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * @file bluetooth_type.h
+ * @brief API to control the Bluetooth adapter, devices and communications.
+ * @ingroup CAPI_NETWORK_BLUETOOTH_TYPE_MODULE
+ */
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_MODULE
+ * @brief Enumerations of Bluetooth error codes.
+ */
+typedef enum
+{
+ BT_ERROR_NONE = TIZEN_ERROR_NONE, /**< Successful*/
+ BT_ERROR_CANCELLED = TIZEN_ERROR_CANCELED, /**< Operation cancelled */
+ BT_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER, /**< Invalid parameter */
+ BT_ERROR_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY, /**< Out of memory */
+ BT_ERROR_RESOURCE_BUSY = TIZEN_ERROR_RESOURCE_BUSY, /**< Device or resource busy */
+ BT_ERROR_TIMED_OUT = TIZEN_ERROR_TIMED_OUT, /**< Timeout error */
+ BT_ERROR_NOW_IN_PROGRESS = TIZEN_ERROR_NOW_IN_PROGRESS, /**< Operation now in progress */
+ BT_ERROR_NOT_SUPPORTED = TIZEN_ERROR_NOT_SUPPORTED,
+ BT_ERROR_PERMISSION_DENIED = TIZEN_ERROR_PERMISSION_DENIED, /**< Permission denied */
+ BT_ERROR_QUOTA_EXCEEDED = TIZEN_ERROR_QUOTA_EXCEEDED, /**< Quota exceeded */
+ BT_ERROR_NOT_INITIALIZED = TIZEN_ERROR_BLUETOOTH|0x0101, /**< Local adapter not initialized */
+ BT_ERROR_NOT_ENABLED = TIZEN_ERROR_BLUETOOTH|0x0102, /**< Local adapter not enabled */
+ BT_ERROR_ALREADY_DONE = TIZEN_ERROR_BLUETOOTH|0x0103, /**< Operation already done */
+ BT_ERROR_OPERATION_FAILED = TIZEN_ERROR_BLUETOOTH|0x0104, /**< Operation failed */
+ BT_ERROR_NOT_IN_PROGRESS = TIZEN_ERROR_BLUETOOTH|0x0105, /**< Operation not in progress */
+ BT_ERROR_REMOTE_DEVICE_NOT_BONDED = TIZEN_ERROR_BLUETOOTH|0x0106, /**< Remote device not bonded */
+ BT_ERROR_AUTH_REJECTED = TIZEN_ERROR_BLUETOOTH|0x0107, /**< Authentication rejected */
+ BT_ERROR_AUTH_FAILED = TIZEN_ERROR_BLUETOOTH|0x0108, /**< Authentication failed */
+ BT_ERROR_REMOTE_DEVICE_NOT_FOUND = TIZEN_ERROR_BLUETOOTH|0x0109, /**< Remote device not found */
+ BT_ERROR_SERVICE_SEARCH_FAILED = TIZEN_ERROR_BLUETOOTH|0x010A, /**< Service search failed */
+ BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED = TIZEN_ERROR_BLUETOOTH|0x010B, /**< Remote device is not connected */
+ BT_ERROR_AGAIN = TIZEN_ERROR_BLUETOOTH|0x010C, /**< Resource temporarily unavailable */
+ BT_ERROR_SERVICE_NOT_FOUND = TIZEN_ERROR_BLUETOOTH|0x010D, /**< Service Not Found */
+} bt_error_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Enumerations of the Bluetooth adapter state.
+ */
+typedef enum
+{
+ BT_ADAPTER_DISABLED = 0x00, /**< Bluetooth adapter is disabled */
+ BT_ADAPTER_ENABLED, /**< Bluetooth adapter is enabled */
+} bt_adapter_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the Bluetooth adapter le state.
+ */
+typedef enum
+{
+ BT_ADAPTER_LE_DISABLED = 0x00, /**< Bluetooth le is disabled */
+ BT_ADAPTER_LE_ENABLED, /**< Bluetooth le is enabled */
+} bt_adapter_le_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Enumerations of the Bluetooth visibility mode.
+ */
+typedef enum
+{
+ BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE = 0x00, /**< Other devices cannot find your device via discovery */
+ BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, /**< Discoverable mode */
+ BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE, /**< Discoverable mode with time limit. After specific period,
+ it is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.*/
+} bt_adapter_visibility_mode_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Enumerations of the discovery state of Bluetooth device.
+ *
+ */
+typedef enum
+{
+ BT_ADAPTER_DEVICE_DISCOVERY_STARTED, /**< Device discovery is started */
+ BT_ADAPTER_DEVICE_DISCOVERY_FINISHED, /**< Device discovery is finished */
+ BT_ADAPTER_DEVICE_DISCOVERY_FOUND, /**< The remote Bluetooth device is found */
+} bt_adapter_device_discovery_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the discovery state of Bluetooth LE device.
+ *
+ */
+typedef enum
+{
+ BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED, /**< LE device discovery is started */
+ BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED, /**< LE device discovery is finished */
+ BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND, /**< The remote Bluetooth LE device is found */
+} bt_adapter_le_device_discovery_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the Bluetooth advertising state.
+ */
+typedef enum {
+ BT_ADAPTER_LE_ADVERTISING_STOPPED = 0x00, /**< Bluetooth advertising is stopped */
+ BT_ADAPTER_LE_ADVERTISING_STARTED, /**< Bluetooth advertising is started */
+} bt_adapter_le_advertising_state_e;
+
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the Bluetooth advertising filter policy.
+ */
+typedef enum {
+ BT_ADAPTER_LE_ADVERTISING_FILTER_DEFAULT = 0x00, /**< White list is not in use */
+ BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_SCAN_WL = 0x01, /**< Allow the scan
+ request that in the White list */
+ BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_CONN_WL = 0x02, /**< Allow the connectoin
+ request that in the White list */
+ BT_ADAPTER_LE_ADVERTISING_FILTER_ALLOW_SCAN_CONN_WL = 0x03, /**< Allow the
+ scan and connectoin request that in the White list */
+} bt_adapter_le_advertising_filter_policy_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the Bluetooth advertising type.
+ */
+typedef enum {
+ BT_ADAPTER_LE_ADVERTISING_CONNECTABLE = 0x00, /**< Connectable undirected advertising (ADV_IND) */
+ BT_ADAPTER_LE_ADVERTISING_CONNECTABLE_DIRECT_HIGH = 0x01, /**< Connectable high duty cycle directed advertising (ADV_DIRECT_IND) */
+ BT_ADAPTER_LE_ADVERTISING_SCANNABLE = 0x02, /**< Scannable undirected advertising (ADV_SCAN_IND) */
+ BT_ADAPTER_LE_ADVERTISING_NON_CONNECTABLE = 0x03, /**< Non connectable undirected advertising (ADV_NONCOND_IND) */
+ BT_ADAPTER_LE_ADVERTISING_CONNECTABLE_DIRECT_LOW = 0x04, /**< Connectable low duty cycle directed advertising (ADV_DIRECT_IND) */
+} bt_adapter_le_advertising_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the Bluetooth LE packet type.
+ */
+typedef enum {
+ BT_ADAPTER_LE_PACKET_ADVERTISING, /**< Advertising packet */
+ BT_ADAPTER_LE_PACKET_SCAN_RESPONSE, /**< Sacn response packet */
+} bt_adapter_le_packet_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the Bluetooth LE data type
+ * that can be included in LE packets.
+ */
+typedef enum {
+ BT_ADAPTER_LE_PACKET_DATA_COMP_LIST_16_BIT_SERVICE_CLASS_UUIDS = 0x03, /**< 16 bit UUID */
+ BT_ADAPTER_LE_PACKET_DATA_MANUFACTURER_SPECIFIC_DATA = 0xff, /**< Manufacturer data */
+} bt_adapter_le_packet_data_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of device disconnect reason.
+ */
+typedef enum
+{
+ BT_DEVICE_DISCONNECT_REASON_UNKNOWN, /**< Disconnected by unknown reason */
+ BT_DEVICE_DISCONNECT_REASON_TIMEOUT, /**< Disconnected by timeout */
+ BT_DEVICE_DISCONNECT_REASON_LOCAL_HOST, /**< Disconnected by local host */
+ BT_DEVICE_DISCONNECT_REASON_REMOTE, /**< Disconnected by remote */
+} bt_device_disconnect_reason_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of connection link type.
+ */
+typedef enum
+{
+ BT_DEVICE_CONNECTION_LINK_BREDR, /**< BR/EDR link */
+ BT_DEVICE_CONNECTION_LINK_LE, /**< LE link */
+ BT_DEVICE_CONNECTION_LINK_DEFAULT = 0xFF, /**< The connection type defualt */
+} bt_device_connection_link_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of device authorization state.
+ */
+typedef enum
+{
+ BT_DEVICE_AUTHORIZED, /**< The remote Bluetooth device is authorized */
+ BT_DEVICE_UNAUTHORIZED, /**< The remote Bluetooth device is unauthorized */
+} bt_device_authorization_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of Bluetooth profile.
+ */
+typedef enum
+{
+ BT_PROFILE_RFCOMM = 0x01, /**< RFCOMM Profile */
+ BT_PROFILE_A2DP = 0x02, /**< Advanced Audio Distribution Profile */
+ BT_PROFILE_HSP = 0x04, /**< Headset Profile */
+ BT_PROFILE_HID = 0x08, /**< Human Interface Device Profile */
+ BT_PROFILE_NAP = 0x10, /**< Network Access Point Profile */
+ BT_PROFILE_AG = 0x20, /**< Audio Gateway Profile */
+ BT_PROFILE_GATT = 0x40, /**< Generic Attribute Profile */
+ BT_PROFILE_NAP_SERVER = 0x80, /**< NAP server Profile */
+} bt_profile_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of device address type.
+ */
+typedef enum
+{
+ BT_DEVICE_PUBLIC_ADDRESS = 0x00, /**< Public address */
+ BT_DEVICE_RANDOM_ADDRESS, /**< Random address */
+} bt_device_address_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of service class.
+ */
+typedef enum {
+ BT_SC_NONE = 0, /**< No service class */
+ BT_SC_RES_SERVICE_MASK = 0x00000001, /**< RES service class */
+ BT_SC_SPP_SERVICE_MASK = 0x00000002, /**< SPP service class */
+ BT_SC_DUN_SERVICE_MASK = 0x00000004, /**< DUN service class */
+ BT_SC_FAX_SERVICE_MASK = 0x00000008, /**< FAX service class */
+ BT_SC_LAP_SERVICE_MASK = 0x00000010, /**< LAP service class */
+ BT_SC_HSP_SERVICE_MASK = 0x00000020, /**< HSP service class */
+ BT_SC_HFP_SERVICE_MASK = 0x00000040, /**< HFP service class */
+ BT_SC_OPP_SERVICE_MASK = 0x00000080, /**< OPP service class */
+ BT_SC_FTP_SERVICE_MASK = 0x00000100, /**< FTP service class */
+ BT_SC_CTP_SERVICE_MASK = 0x00000200, /**< CTP service class */
+ BT_SC_ICP_SERVICE_MASK = 0x00000400, /**< ICP service class */
+ BT_SC_SYNC_SERVICE_MASK = 0x00000800, /**< SYNC service class */
+ BT_SC_BPP_SERVICE_MASK = 0x00001000, /**< BPP service class */
+ BT_SC_BIP_SERVICE_MASK = 0x00002000, /**< BIP service class */
+ BT_SC_PANU_SERVICE_MASK = 0x00004000, /**< PANU service class */
+ BT_SC_NAP_SERVICE_MASK = 0x00008000, /**< NAP service class */
+ BT_SC_GN_SERVICE_MASK = 0x00010000, /**< GN service class */
+ BT_SC_SAP_SERVICE_MASK = 0x00020000, /**< SAP service class */
+ BT_SC_A2DP_SERVICE_MASK = 0x00040000, /**< A2DP service class */
+ BT_SC_AVRCP_SERVICE_MASK = 0x00080000, /**< AVRCP service class */
+ BT_SC_PBAP_SERVICE_MASK = 0x00100000, /**< PBAP service class */
+ BT_SC_HID_SERVICE_MASK = 0x00200000, /**< HID service class */
+ BT_SC_ALL_SERVICE_MASK = 0x00FFFFFF, /**< ALL service class */
+ BT_SC_MAX /**< MAX service class */
+} bt_service_class_t;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of major service class.
+ */
+typedef enum
+{
+ BT_MAJOR_SERVICE_CLASS_LIMITED_DISCOVERABLE_MODE = 0x002000, /**< Limited discoverable mode */
+ BT_MAJOR_SERVICE_CLASS_POSITIONING = 0x010000, /**< Positioning class */
+ BT_MAJOR_SERVICE_CLASS_NETWORKING = 0x020000, /**< Networking class */
+ BT_MAJOR_SERVICE_CLASS_RENDERING = 0x040000, /**< Rendering class */
+ BT_MAJOR_SERVICE_CLASS_CAPTURING = 0x080000, /**< Capturing class */
+ BT_MAJOR_SERVICE_CLASS_OBJECT_TRANSFER = 0x100000, /**< Object transferring class */
+ BT_MAJOR_SERVICE_CLASS_AUDIO = 0x200000, /**< Audio class*/
+ BT_MAJOR_SERVICE_CLASS_TELEPHONY = 0x400000, /**< Telephony class */
+ BT_MAJOR_SERVICE_CLASS_INFORMATION = 0x800000, /**< Information class */
+} bt_major_service_class_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of major device class.
+ */
+typedef enum
+{
+ BT_MAJOR_DEVICE_CLASS_MISC = 0x00, /**< Miscellaneous major device class*/
+ BT_MAJOR_DEVICE_CLASS_COMPUTER = 0x01, /**< Computer major device class */
+ BT_MAJOR_DEVICE_CLASS_PHONE = 0x02, /**< Phone major device class */
+ BT_MAJOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT = 0x03, /**< LAN/Network access point major device class */
+ BT_MAJOR_DEVICE_CLASS_AUDIO_VIDEO = 0x04, /**< Audio/Video major device class */
+ BT_MAJOR_DEVICE_CLASS_PERIPHERAL = 0x05, /**< Peripheral major device class */
+ BT_MAJOR_DEVICE_CLASS_IMAGING = 0x06, /**< Imaging major device class */
+ BT_MAJOR_DEVICE_CLASS_WEARABLE = 0x07, /**< Wearable device class */
+ BT_MAJOR_DEVICE_CLASS_TOY = 0x08, /**< Toy device class */
+ BT_MAJOR_DEVICE_CLASS_HEALTH = 0x09, /**< Health device class */
+ BT_MAJOR_DEVICE_CLASS_UNCATEGORIZED = 0x1F, /**< Uncategorized major device class */
+} bt_major_device_class_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of minor device class.
+ */
+typedef enum
+{
+ BT_MINOR_DEVICE_CLASS_COMPUTER_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of computer */
+ BT_MINOR_DEVICE_CLASS_COMPUTER_DESKTOP_WORKSTATION = 0x04, /**< Desktop workstation minor device class of computer */
+ BT_MINOR_DEVICE_CLASS_COMPUTER_SERVER_CLASS = 0x08, /**< Server minor device class of computer */
+ BT_MINOR_DEVICE_CLASS_COMPUTER_LAPTOP = 0x0C, /**< Laptop minor device class of computer */
+ BT_MINOR_DEVICE_CLASS_COMPUTER_HANDHELD_PC_OR_PDA = 0x10, /**< Handheld PC/PDA minor device class of computer */
+ BT_MINOR_DEVICE_CLASS_COMPUTER_PALM_SIZED_PC_OR_PDA = 0x14, /**< Palm sized PC/PDA minor device class of computer */
+ BT_MINOR_DEVICE_CLASS_COMPUTER_WEARABLE_COMPUTER = 0x18, /**< Wearable(watch sized) minor device class of computer */
+
+ BT_MINOR_DEVICE_CLASS_PHONE_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of phone */
+ BT_MINOR_DEVICE_CLASS_PHONE_CELLULAR = 0x04, /**< Cellular minor device class of phone */
+ BT_MINOR_DEVICE_CLASS_PHONE_CORDLESS = 0x08, /**< Cordless minor device class of phone */
+ BT_MINOR_DEVICE_CLASS_PHONE_SMART_PHONE = 0x0C, /**< Smart phone minor device class of phone */
+ BT_MINOR_DEVICE_CLASS_PHONE_WIRED_MODEM_OR_VOICE_GATEWAY = 0x10, /**< Wired modem or voice gateway minor device class of phone */
+ BT_MINOR_DEVICE_CLASS_PHONE_COMMON_ISDN_ACCESS = 0x14, /**< Common ISDN minor device class of phone */
+
+ BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_FULLY_AVAILABLE = 0x04, /**< Fully available minor device class of LAN/Network access point */
+ BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_1_TO_17_PERCENT_UTILIZED = 0x20, /**< 1-17% utilized minor device class of LAN/Network access point */
+ BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_17_TO_33_PERCENT_UTILIZED = 0x40, /**< 17-33% utilized minor device class of LAN/Network access point */
+ BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_33_TO_50_PERCENT_UTILIZED = 0x60, /**< 33-50% utilized minor device class of LAN/Network access point */
+ BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_50_to_67_PERCENT_UTILIZED = 0x80, /**< 50-67% utilized minor device class of LAN/Network access point */
+ BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_67_TO_83_PERCENT_UTILIZED = 0xA0, /**< 67-83% utilized minor device class of LAN/Network access point */
+ BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_83_TO_99_PERCENT_UTILIZED = 0xC0, /**< 83-99% utilized minor device class of LAN/Network access point */
+ BT_MINOR_DEVICE_CLASS_LAN_NETWORK_ACCESS_POINT_NO_SERVICE_AVAILABLE = 0xE0, /**< No service available minor device class of LAN/Network access point */
+
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_WEARABLE_HEADSET = 0x04, /**< Wearable headset minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HANDS_FREE = 0x08, /**< Hands-free minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_MICROPHONE = 0x10, /**< Microphone minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_LOUDSPEAKER = 0x14, /**< Loudspeaker minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HEADPHONES = 0x18, /**< Headphones minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_PORTABLE_AUDIO = 0x1C, /**< Portable audio minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAR_AUDIO = 0x20, /**< Car audio minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_SET_TOP_BOX = 0x24, /**< Set-top box minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_HIFI_AUDIO_DEVICE = 0x28, /**< Hifi audio minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VCR = 0x2C, /**< VCR minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CAMERA = 0x30, /**< Video camera minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_CAMCORDER = 0x34, /**< Camcorder minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_MONITOR = 0x38, /**< Video monitor minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_DISPLAY_LOUDSPEAKER = 0x3C, /**< Video display and loudspeaker minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_VIDEO_CONFERENCING = 0x40, /**< Video conferencing minor device class of audio/video */
+ BT_MINOR_DEVICE_CLASS_AUDIO_VIDEO_GAMING_TOY = 0x48, /**< Gaming/toy minor device class of audio/video */
+
+ BT_MINOR_DEVICE_CLASS_PERIPHERA_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_KEY_BOARD = 0x40, /**< Key board minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_POINTING_DEVICE = 0x80, /**< Pointing device minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_COMBO_KEYBOARD_POINTING_DEVICE = 0xC0, /**< Combo keyboard or pointing device minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_JOYSTICK = 0x04, /**< Joystick minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_GAME_PAD = 0x08, /**< Game pad minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_REMOTE_CONTROL = 0x0C, /**< Remote control minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_SENSING_DEVICE = 0x10, /**< Sensing device minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITIZER_TABLET = 0x14, /**< Digitizer minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_CARD_READER = 0x18, /**< Card reader minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_DIGITAL_PEN = 0x1C, /**< Digital pen minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_SCANNER = 0x20, /**< Handheld scanner minor device class of peripheral */
+ BT_MINOR_DEVICE_CLASS_PERIPHERAL_HANDHELD_GESTURAL_INPUT_DEVICE = 0x24, /**< Handheld gestural input device minor device class of peripheral */
+
+ BT_MINOR_DEVICE_CLASS_IMAGING_DISPLAY = 0x10, /**< Display minor device class of imaging */
+ BT_MINOR_DEVICE_CLASS_IMAGING_CAMERA = 0x20, /**< Camera minor device class of imaging */
+ BT_MINOR_DEVICE_CLASS_IMAGING_SCANNER = 0x40, /**< Scanner minor device class of imaging */
+ BT_MINOR_DEVICE_CLASS_IMAGING_PRINTER = 0x80, /**< Printer minor device class of imaging */
+
+ BT_MINOR_DEVICE_CLASS_WEARABLE_WRIST_WATCH = 0x04, /**< Wrist watch minor device class of wearable */
+ BT_MINOR_DEVICE_CLASS_WEARABLE_PAGER = 0x08, /**< Pager minor device class of wearable */
+ BT_MINOR_DEVICE_CLASS_WEARABLE_JACKET = 0x0C, /**< Jacket minor device class of wearable */
+ BT_MINOR_DEVICE_CLASS_WEARABLE_HELMET = 0x10, /**< Helmet minor device class of wearable */
+ BT_MINOR_DEVICE_CLASS_WEARABLE_GLASSES = 0x14, /**< Glasses minor device class of wearable */
+
+ BT_MINOR_DEVICE_CLASS_TOY_ROBOT = 0x04, /**< Robot minor device class of toy */
+ BT_MINOR_DEVICE_CLASS_TOY_VEHICLE = 0x08, /**< Vehicle minor device class of toy */
+ BT_MINOR_DEVICE_CLASS_TOY_DOLL_ACTION = 0x0C, /**< Doll/Action minor device class of toy */
+ BT_MINOR_DEVICE_CLASS_TOY_CONTROLLER = 0x10, /**< Controller minor device class of toy */
+ BT_MINOR_DEVICE_CLASS_TOY_GAME = 0x14, /**< Game minor device class of toy */
+
+ BT_MINOR_DEVICE_CLASS_HEALTH_UNCATEGORIZED = 0x00, /**< Uncategorized minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_BLOOD_PRESSURE_MONITOR = 0x04, /**< Blood pressure monitor minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_THERMOMETER = 0x08, /**< Thermometer minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_WEIGHING_SCALE = 0x0C, /**< Weighing scale minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_GLUCOSE_METER = 0x10, /**< Glucose minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_PULSE_OXIMETER = 0x14, /**< Pulse oximeter minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_HEART_PULSE_RATE_MONITOR = 0x18, /**< Heart/Pulse rate monitor minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_DATA_DISPLAY = 0x1C, /**< Health data display minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_STEP_COUNTER = 0x20, /**< Step counter minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_BODY_COMPOSITION_ANALYZER = 0x24, /**< Body composition analyzer minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_PEAK_FLOW_MONITOR = 0x28, /**< Peak flow monitor minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_MEDICATION_MONITOR = 0x2C, /**< Medication monitor minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_KNEE_PROSTHESIS = 0x30, /**< Knee prosthesis minor device class of health */
+ BT_MINOR_DEVICE_CLASS_HEALTH_ANKLE_PROSTHESIS = 0x34, /**< Ankle prosthesis minor device class of health */
+} bt_minor_device_class_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enumerations of gap appearance type.
+ */
+typedef enum
+{
+ BT_APPEARANCE_TYPE_UNKNOWN = 0x00, /**< Unknown appearance type */
+ BT_APPEARANCE_TYPE_GENERIC_PHONE = 0x40, /**< Generic Phone type - Generic category */
+ BT_APPEARANCE_TYPE_GENERIC_COMPUTER = 0x80, /**< Generic Computer type - Generic category */
+ BT_APPEARANCE_TYPE_GENERIC_WATCH = 0xC0, /**< Generic Watch type - Generic category */
+} bt_appearance_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Enumerations of connected Bluetooth device event role.
+ */
+typedef enum
+{
+ BT_SOCKET_UNKNOWN = 0x00, /**< Unknown role*/
+ BT_SOCKET_SERVER , /**< Server role*/
+ BT_SOCKET_CLIENT, /**< Client role*/
+} bt_socket_role_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Enumerations of Bluetooth socket connection state.
+ */
+typedef enum
+{
+ BT_SOCKET_CONNECTED, /**< RFCOMM is connected */
+ BT_SOCKET_DISCONNECTED, /**< RFCOMM is disconnected */
+} bt_socket_connection_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Enumerations for the types of profiles related with audio
+ */
+typedef enum {
+ BT_AUDIO_PROFILE_TYPE_ALL = 0, /**< All supported profiles related with audio */
+ BT_AUDIO_PROFILE_TYPE_HSP_HFP, /**< HSP(Headset Profile) and HFP(Hands-Free Profile) */
+ BT_AUDIO_PROFILE_TYPE_A2DP, /**< A2DP(Advanced Audio Distribution Profile) */
+ BT_AUDIO_PROFILE_TYPE_AG, /**< AG(Audio Gateway) */
+} bt_audio_profile_type_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Enumerations for the call handling event
+ */
+typedef enum {
+ BT_AG_CALL_HANDLING_EVENT_ANSWER = 0x00, /**< Request to answer an incoming call */
+ BT_AG_CALL_HANDLING_EVENT_RELEASE, /**< Request to release a call */
+ BT_AG_CALL_HANDLING_EVENT_REJECT, /**< Request to reject an incoming call */
+} bt_ag_call_handling_event_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Enumerations for the multi call handling event
+ */
+typedef enum {
+ BT_AG_MULTI_CALL_HANDLING_EVENT_RELEASE_HELD_CALLS = 0x00, /**< Request to release held calls */
+ BT_AG_MULTI_CALL_HANDLING_EVENT_RELEASE_ACTIVE_CALLS, /**< Request to release active calls */
+ BT_AG_MULTI_CALL_HANDLING_EVENT_ACTIVATE_HELD_CALL, /**< Request to put active calls into hold state and activate another (held or waiting) call */
+ BT_AG_MULTI_CALL_HANDLING_EVENT_MERGE_CALLS, /**< Request to add a held call to the conversation */
+ BT_AG_MULTI_CALL_HANDLING_EVENT_EXPLICIT_CALL_TRANSFER, /**< Request to let a user who has two calls to connect these two calls together and release its connections to both other parties */
+} bt_ag_multi_call_handling_event_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Enumerations for the call state
+ */
+typedef enum {
+ BT_AG_CALL_EVENT_IDLE = 0x00, /**< Idle */
+ BT_AG_CALL_EVENT_ANSWERED, /**< Answered */
+ BT_AG_CALL_EVENT_HELD, /**< Held */
+ BT_AG_CALL_EVENT_RETRIEVED, /**< Retrieved */
+ BT_AG_CALL_EVENT_DIALING, /**< Dialing */
+ BT_AG_CALL_EVENT_ALERTING, /**< Alerting */
+ BT_AG_CALL_EVENT_INCOMING, /**< Incoming */
+} bt_ag_call_event_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Enumerations for the call state
+ */
+typedef enum {
+ BT_AG_CALL_STATE_IDLE = 0x00, /**< Idle state */
+ BT_AG_CALL_STATE_ACTIVE, /**< Active state */
+ BT_AG_CALL_STATE_HELD, /**< Held state */
+ BT_AG_CALL_STATE_DIALING, /**< Dialing state */
+ BT_AG_CALL_STATE_ALERTING, /**< Alerting state */
+ BT_AG_CALL_STATE_INCOMING, /**< Incoming state */
+ BT_AG_CALL_STATE_WAITING, /**< Waiting for connected indication event after answering an incoming call*/
+} bt_ag_call_state_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Enumerations for the equalizer state
+ */
+typedef enum {
+ BT_AVRCP_EQUALIZER_STATE_OFF = 0x01, /**< Equalizer Off */
+ BT_AVRCP_EQUALIZER_STATE_ON, /**< Equalizer On */
+} bt_avrcp_equalizer_state_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Enumerations for the repeat mode
+ */
+typedef enum {
+ BT_AVRCP_REPEAT_MODE_OFF = 0x01, /**< Repeat Off */
+ BT_AVRCP_REPEAT_MODE_SINGLE_TRACK, /**< Single track repeat */
+ BT_AVRCP_REPEAT_MODE_ALL_TRACK, /**< All track repeat */
+ BT_AVRCP_REPEAT_MODE_GROUP, /**< Group repeat */
+} bt_avrcp_repeat_mode_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Enumerations for the shuffle mode
+ */
+typedef enum {
+ BT_AVRCP_SHUFFLE_MODE_OFF = 0x01, /**< Shuffle Off */
+ BT_AVRCP_SHUFFLE_MODE_ALL_TRACK, /**< All tracks shuffle */
+ BT_AVRCP_SHUFFLE_MODE_GROUP, /**< Group shuffle */
+} bt_avrcp_shuffle_mode_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Enumerations for the scan mode
+ */
+typedef enum {
+ BT_AVRCP_SCAN_MODE_OFF = 0x01, /**< Scan Off */
+ BT_AVRCP_SCAN_MODE_ALL_TRACK, /**< All tracks scan */
+ BT_AVRCP_SCAN_MODE_GROUP, /**< Group scan */
+} bt_avrcp_scan_mode_e;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Enumerations for the player state
+ */
+typedef enum {
+ BT_AVRCP_PLAYER_STATE_STOPPED = 0x00, /**< Stopped */
+ BT_AVRCP_PLAYER_STATE_PLAYING, /**< Playing */
+ BT_AVRCP_PLAYER_STATE_PAUSED, /**< Paused */
+ BT_AVRCP_PLAYER_STATE_FORWARD_SEEK, /**< Seek Forward */
+ BT_AVRCP_PLAYER_STATE_REWIND_SEEK, /**< Seek Rewind */
+} bt_avrcp_player_state_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Enumerations for the data channel type
+ */
+typedef enum {
+ BT_HDP_CHANNEL_TYPE_RELIABLE = 0x01, /**< Reliable Data Channel */
+ BT_HDP_CHANNEL_TYPE_STREAMING, /**< Streaming Data Channel */
+} bt_hdp_channel_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief Enumerations for the types of PAN(Personal Area Networking) service
+ */
+typedef enum {
+ BT_PANU_SERVICE_TYPE_NAP = 0, /**< Network Access Point */
+} bt_panu_service_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief The handle to control Bluetooth LE advertising
+ */
+typedef void* bt_advertiser_h;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief The attribute handle of GATT(Generic Attribute Profile)
+ */
+typedef void* bt_gatt_attribute_h;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief The handle of calls state
+ */
+typedef void* bt_call_list_h;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Class structure of device and service.
+ *
+ * @see #bt_device_info_s
+ * @see #bt_adapter_device_discovery_info_s
+ * @see bt_device_bond_created_cb()
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ */
+typedef struct
+{
+ bt_major_device_class_e major_device_class; /**< Major device class. */
+ bt_minor_device_class_e minor_device_class; /**< Minor device class. */
+ int major_service_class_mask; /**< Major service class mask.
+ This value can be a combination of #bt_major_service_class_e like #BT_MAJOR_SERVICE_CLASS_RENDERING | #BT_MAJOR_SERVICE_CLASS_AUDIO */
+} bt_class_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Structure of device discovery information.
+ *
+ * @see #bt_class_s
+ * @see bt_adapter_device_discovery_state_changed_cb()
+ */
+typedef struct
+{
+ char *remote_address; /**< The address of remote device */
+ char *remote_name; /**< The name of remote device */
+ bt_class_s bt_class; /**< The Bluetooth classes */
+ int rssi; /**< The strength indicator of received signal */
+ bool is_bonded; /**< The bonding state */
+ char **service_uuid; /**< The UUID list of service */
+ int service_count; /**< The number of services */
+ bt_appearance_type_e appearance; /**< The Bluetooth appearance */
+ int manufacturer_data_len; /**< manufacturer specific data length */
+ char *manufacturer_data; /**< manufacturer specific data */
+} bt_adapter_device_discovery_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Structure of le device discovery information.
+ *
+ * @see #bt_class_s
+ * @see bt_adapter_le_device_discovery_state_changed_cb()
+ */
+typedef struct
+{
+ char *remote_address; /**< The address of remote device */
+ int address_type; /**< The address type of remote device */
+ int rssi; /**< The strength indicator of received signal */
+ char **service_uuid; /**< The UUID list of service */
+ int service_count; /**< The number of services */
+ int adv_data_len; /**< advertising indication data length */
+ char *adv_data; /**< advertising indication data */
+ int scan_data_len; /**< scan response data length */
+ char *scan_data; /**< scan response data */
+} bt_adapter_le_device_discovery_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Structure of advertising parameters
+ *
+ * @see #bt_class_s
+ * @see bt_adapter_le_advertising_state_changed_cb()
+ * @see bt_adapter_le_start_advertising()
+ */
+typedef struct {
+ float interval_min; /**< Minimum advertising interval for non-directed advertising.
+ A multiple of 0.625ms is only allowed (Time range : 20ms to 10.24sec). */
+ float interval_max; /**< Maximum advertising interval for non-directed advertising.
+ A multiple of 0.625ms is only allowed (Time range : 20ms to 10.24sec). */
+ char filter_policy; /* Advertising filter policy */
+ char type; /* Advertising type */
+} bt_adapter_le_advertising_params_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Device information structure used for identifying pear device.
+ *
+ * @see #bt_class_s
+ * @see bt_device_bond_created_cb()
+ */
+typedef struct
+{
+ char *remote_address; /**< The address of remote device */
+ char *remote_name; /**< The name of remote device */
+ bt_class_s bt_class; /**< The Bluetooth classes */
+ char **service_uuid; /**< The UUID list of service */
+ int service_count; /**< The number of services */
+ bool is_bonded; /**< The bonding state */
+ bool is_connected; /**< The connection state */
+ bool is_authorized; /**< The authorization state */
+ int manufacturer_data_len; /**< manufacturer specific data length */
+ char *manufacturer_data; /**< manufacturer specific data */
+} bt_device_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Service Discovery Protocol (SDP) data structure.
+ *
+ * @details This protocol is used for discovering available services or pear device,
+ * and finding one to connect with.
+ *
+ * @see bt_device_service_searched_cb()
+ */
+typedef struct
+{
+ char *remote_address; /**< The address of remote device */
+ char **service_uuid; /**< The UUID list of service */
+ int service_count; /**< The number of services. */
+} bt_device_sdp_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Device connection information structure.
+ *
+ * @see bt_device_connection_state_changed_cb()
+ */
+typedef struct
+{
+ char *remote_address; /**< The address of remote device */
+ bt_device_connection_link_type_e link; /**< Link type */
+ bt_device_disconnect_reason_e disconn_reason; /**< Disconnection reason */
+} bt_device_connection_info_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Device LE connection update structure.
+ *
+ * @see bt_device_le_conn_update()
+ */
+typedef struct
+{
+ unsigned int interval_min; /**< Minimum value for the connection event interval (msec) */
+ unsigned int interval_max; /**< Maximum value for the connection event interval (msec) */
+ unsigned int latency; /**< Slave latency (msec) */
+ unsigned int time_out; /**< Supervision timeout (msec) */
+} bt_le_conn_update_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ *
+ * @brief Rfcomm connection data used for exchanging data between Bluetooth devices.
+ *
+ * @see bt_socket_connection_state_changed_cb()
+ */
+typedef struct
+{
+ int socket_fd; /**< The file descriptor of connected socket */
+ int server_fd; /**< The file descriptor of the server socket or -1 for client connection */
+ bt_socket_role_e local_role; /**< The local device role in this connection */
+ char *remote_address; /**< The remote device address */
+ char *service_uuid; /**< The service UUId */
+} bt_socket_connection_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ *
+ * @brief Structure of RFCOMM received data.
+ *
+ * @remarks User can use standard linux functions for reading/writing
+ * data from/to sockets.
+ *
+ * @see bt_socket_data_received_cb()
+ */
+typedef struct
+{
+ int socket_fd; /**< The socket fd */
+ int data_size; /**< The length of the received data */
+ char *data; /**< The received data */
+} bt_socket_received_data_s;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Called when the Bluetooth adapter state changes.
+ * @param[in] result The result of the adapter state changing
+ * @param[in] adapter_state The adapter state to be changed
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_adapter_set_state_changed_cb()
+ * @see bt_adapter_unset_state_changed_cb()
+ */
+typedef void (*bt_adapter_state_changed_cb)(int result, bt_adapter_state_e adapter_state, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Called when adapter name changes.
+ * @param[in] device_name The name of the Bluetooth device to be changed
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre This function will be invoked when the name of Bluetooth adapter changes
+ * if you register this callback using bt_adapter_set_name_changed_cb().
+ * @see bt_adapter_set_name()
+ * @see bt_adapter_set_name_changed_cb()
+ * @see bt_adapter_unset_name_changed_cb()
+ */
+typedef void (*bt_adapter_name_changed_cb)(char *device_name, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Called when the visibility mode changes.
+ * @param[in] result The result of the visibility mode changing
+ * @param[in] visibility_mode The visibility mode to be changed
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre This function will be invoked when the visibility of Bluetooth adapter changes
+ * if you register this callback using bt_adapter_set_visibility_mode_changed_cb().
+ *
+ * @see bt_adapter_set_visibility_mode_changed_cb()
+ * @see bt_adapter_unset_visibility_mode_changed_cb()
+ */
+typedef void (*bt_adapter_visibility_mode_changed_cb)
+ (int result, bt_adapter_visibility_mode_e visibility_mode, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Called every second until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE.
+ * @remarks This callback function is called only if visibility mode is #BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE.
+ * @param[in] duration The duration until the visibility mode is changed to #BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE (in seconds)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre This function will be invoked if you register this callback using bt_adapter_set_visibility_duration_changed_cb().
+ * @see bt_adapter_set_visibility_duration_changed_cb()
+ * @see bt_adapter_unset_visibility_duration_changed_cb()
+ */
+typedef void (*bt_adapter_visibility_duration_changed_cb)(int duration, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Called when the state of device discovery changes.
+ *
+ * @remarks If \a discovery_state is #BT_ADAPTER_DEVICE_DISCOVERY_FOUND,
+ * then you can get some information, such as remote device address, remote device name, rssi, and bonding state.
+ *
+ * @param[in] result The result of the device discovery
+ * @param[in] discovery_state The discovery state to be changed
+ * @param[in] discovery_info The information of the discovered device \n
+ * If \a discovery_state is #BT_ADAPTER_DEVICE_DISCOVERY_STARTED or
+ * #BT_ADAPTER_DEVICE_DISCOVERY_FINISHED, then \a discovery_info is NULL.
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre Either bt_adapter_start_device_discovery() or bt_adapter_stop_device_discovery() will invoke this function
+ * if you register this callback using bt_adapter_set_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_start_device_discovery()
+ * @see bt_adapter_stop_device_discovery()
+ * @see bt_adapter_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_unset_device_discovery_state_changed_cb()
+ *
+ */
+typedef void (*bt_adapter_device_discovery_state_changed_cb)
+ (int result, bt_adapter_device_discovery_state_e discovery_state, bt_adapter_device_discovery_info_s *discovery_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Called when you get bonded devices repeatedly.
+ *
+ * @param[in] device_info The bonded device information
+ * @param[in] user_data The user data passed from the foreach function
+ * @return @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre bt_adapter_foreach_bonded_device() will invoke this function.
+ *
+ * @see bt_adapter_foreach_bonded_device()
+ *
+ */
+typedef bool (*bt_adapter_bonded_device_cb)(bt_device_info_s *device_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Called when the connectable state changes.
+ * @param[in] result The result of the connectable state changing
+ * @param[in] connectable The connectable to be changed
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre This function will be invoked when the connectable state of local Bluetooth adapter changes
+ * if you register this callback using bt_adapter_set_connectable_changed_cb().
+ *
+ * @see bt_adapter_set_connectable()
+ * @see bt_adapter_set_connectable_changed_cb()
+ * @see bt_adapter_unset_connectable_changed_cb()
+ */
+typedef void (*bt_adapter_connectable_changed_cb)
+ (int result, bool connectable, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Called when the state of LE device discovery changes.
+ *
+ * @remarks If \a discovery_state is #BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND,
+ * then you can get some information, such as remote LE device address, remote device name, rssi, and bonding state.
+ *
+ * @param[in] result The result of the LE device discovery
+ * @param[in] discovery_state The discovery state to be changed
+ * @param[in] discovery_info The information of the discovered LE device \n
+ * If \a discovery_state is #BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED or
+ * #BT_ADAPTER_LE_DEVICE_DISCOVERY_FINISHED, then \a discovery_info is NULL.
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre Either bt_adapter_start_device_discovery() or bt_adapter_stop_device_discovery() will invoke this function
+ * if you register this callback using bt_adapter_set_device_discovery_state_changed_cb().
+ *
+ * @see bt_adapter_le_start_device_discovery()
+ * @see bt_adapter_le_stop_device_discovery()
+ * @see bt_adapter_le_set_device_discovery_state_changed_cb()
+ * @see bt_adapter_le_unset_device_discovery_state_changed_cb()
+ *
+ */
+typedef void (*bt_adapter_le_device_discovery_state_changed_cb)
+ (int result, bt_adapter_le_device_discovery_state_e discovery_state, bt_adapter_le_device_discovery_info_s *discovery_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Called when the state of advertiser changes.
+ *
+ * @param[out] result The result of the requested state change of advertiser
+ * @param[out] advertiser The handle of the state changed advertiser
+ * @param[out] adv_state The advertiser state to be changed
+ * @param[out] user_data The user data passed from the start function
+ *
+ * @see bt_adapter_le_start_advertiser()
+ * @see bt_adapter_le_stop_advertiser()
+ */
+typedef void (*bt_adapter_le_advertising_state_changed_cb)(int result,
+ bt_advertiser_h advertiser, bt_adapter_le_advertising_state_e adv_state, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Called when the Bluetooth adapter le state changes.
+ * @param[in] result The result of the adapter state changing
+ * @param[in] adapter_le_state The adapter le state to be changed
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre Either bt_adapter_le_enable() or bt_adapter_le_disable() will invoke this callback if you register this callback using bt_adapter_le_set_state_changed_cb().
+ * @see bt_adapter_le_enable()
+ * @see bt_adapter_le_disable()
+ * @see bt_adapter_le_set_state_changed_cb()
+ * @see bt_adapter_le_unset_state_changed_cb()
+ */
+typedef void (*bt_adapter_le_state_changed_cb)(int result, bt_adapter_le_state_e adapter_le_state, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when the process of creating bond finishes.
+ * @remarks If the remote user does not respond within 60 seconds, a time out will happen with #BT_ERROR_TIMED_OUT result code.\n
+ * If bt_device_cancel_bonding() is called and it returns #BT_ERROR_NONE, then this callback function will be called
+ * with #BT_ERROR_CANCELLED result. \n
+ * If creating a bond succeeds but service search fails, then this callback will be called with #BT_ERROR_SERVICE_SEARCH_FAILED.
+ * In this case, you should try service search again by bt_device_start_service_search() to get the supported service list.
+ *
+ * @param[in] result The result of the bonding device
+ * @param[in] device_info The device information which you creates bond with
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre Either bt_device_create_bond() will invoke this function
+ * if you register this callback using bt_device_set_bond_created_cb().
+ *
+ * @see bt_device_create_bond()
+ * @see bt_device_cancel_bonding()
+ * @see bt_device_set_bond_created_cb()
+ * @see bt_device_unset_bond_created_cb()
+ */
+typedef void (*bt_device_bond_created_cb)(int result, bt_device_info_s *device_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when you get connected profiles repeatedly.
+ * @param[in] profile The connected Bluetooth profile
+ * @param[in] user_data The user data passed from the foreach function
+ * @return @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre bt_device_foreach_connected_profiles() will invoke this function.
+ * @see bt_device_foreach_connected_profiles()
+ */
+typedef bool (*bt_device_connected_profile)(bt_profile_e profile, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when the bond destroys.
+ * @param[in] result The result that a bond is destroyed
+ * @param[in] remote_address The address of the remote Bluetooth device to destroy bond with
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre bt_device_destroy_bond() will invoke this function
+ * if you register this callback using bt_device_set_bond_destroyed_cb().
+ *
+ * @see bt_device_destroy_bond()
+ * @see bt_device_set_bond_destroyed_cb()
+ * @see bt_device_unset_bond_destroyed_cb()
+ */
+typedef void (*bt_device_bond_destroyed_cb)(int result, char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when the authorization of device changes.
+ * @param[in] authorization The authorization of device
+ * @param[in] remote_address The address of the remote Bluetooth device which is (un)authorized
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre bt_device_set_authorization() will invoke this function if you register this callback using bt_device_set_authorization_changed_cb().
+ *
+ * @see bt_device_set_authorization()
+ * @see #bt_device_set_authorization_changed_cb()
+ * @see #bt_device_unset_authorization_changed_cb()
+ */
+typedef void (*bt_device_authorization_changed_cb)
+ (bt_device_authorization_e authorization, char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when the process of service search finishes.
+ * @remark If bt_device_cancel_service_search() is called and it returns #BT_ERROR_NONE,
+ * then this callback function will be called with #BT_ERROR_CANCELLED result.
+ *
+ * @param[in] result The result of the service searching
+ * @param[in] sdp_info The structure of service lists found on a device
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre Either bt_device_start_service_search() will invoke this function
+ * if you register this callback using bt_device_set_service_searched_cb().
+ *
+ * @see bt_device_start_service_search()
+ * @see bt_device_cancel_service_search()
+ * @see bt_device_set_service_searched_cb()
+ * @see bt_device_unset_service_searched_cb()
+ *
+ */
+typedef void (*bt_device_service_searched_cb)(int result, bt_device_sdp_info_s *sdp_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when the connection state is changed.
+ * @param[in] connected The connection status: (@c true = connected, @c false = disconnected)
+ * @param[in] conn_info The connection information
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_device_set_connection_state_changed_cb()
+ * @see bt_device_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_device_connection_state_changed_cb)(bool connected, bt_device_connection_info_s *conn_info, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Called when you receive data.
+ *
+ * @param[in] data The received data from the remote device
+ * @param[in] user_data The user data passed from the callback registration function
+ *
+ * @pre When the connected remote Bluetooth device invokes bt_socket_send_data(),
+ * this function will be invoked if you register this function using bt_socket_set_data_received_cb().
+ *
+ * @see bt_socket_set_data_received_cb()
+ * @see bt_socket_unset_data_received_cb()
+ * @see bt_socket_send_data()
+ */
+typedef void (*bt_socket_data_received_cb)(bt_socket_received_data_s *data, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Called when the socket connection state changes.
+ * @param[in] result The result of connection state changing
+ * @param[in] connection_state The connection state
+ * @param[in] connection The connection information which is established or disconnected
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre Either bt_socket_connect_rfcomm() will invoke this function.
+ * In addtion, bt_socket_connection_state_changed_cb() will be invoked when the socket connection state is changed.
+ * @see bt_socket_listen_and_accept_rfcomm()
+ * @see bt_socket_connect_rfcomm()
+ * @see bt_socket_set_connection_state_changed_cb()
+ * @see bt_socket_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_socket_connection_state_changed_cb)
+ (int result, bt_socket_connection_state_e connection_state, bt_socket_connection_s *connection, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_SOCKET_MODULE
+ * @brief Called when a RFCOMM connection is requested.
+ * @details You must call bt_socket_accept() if you want to accept. Otherwise, you must call bt_socket_reject().
+ * @param[in] socket_fd The file descriptor of socket on which a connection is requested
+ * @param[in] remote_address The address of remote device
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre If you register this callback function by bt_socket_set_connection_requested_cb() and listen a socket by bt_socket_listen(),
+ * bt_socket_connection_requested_cb() will be invoked.
+ * @see bt_socket_listen()
+ * @see bt_socket_accept()
+ * @see bt_socket_reject()
+ */
+typedef void (*bt_socket_connection_requested_cb) (int socket_fd, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Called when the push is requested.
+ * @details You must call bt_opp_server_accept() if you want to accept.
+ * Otherwise, you must call bt_opp_server_reject().
+ * @param[in] file The path of file to be pushed
+ * @param[in] size The file size (bytes)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_server_initialize()
+ */
+typedef void (*bt_opp_server_push_requested_cb)(const char *file, int size, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Called when an OPP connection is requested.
+ * @details You must call bt_opp_server_accept_connection() if you want to accept.
+ * Otherwise, you must call bt_opp_server_reject_connection().
+ * @param[in] remote_address The address of remote device
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_server_initialize()
+ * @see bt_opp_server_accept_connection()
+ * @see bt_opp_server_reject_connection()
+ */
+typedef void (*bt_opp_server_connection_requested_cb)(const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Called when a file is being transfered.
+ * @param[in] file The path of file to be pushed
+ * @param[in] size The file size (bytes)
+ * @param[in] percent The progress in percentage (1 ~ 100)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_server_accept()
+ * @see bt_opp_server_accept_connection()
+ */
+typedef void (*bt_opp_server_transfer_progress_cb) (const char *file, long long size, int percent, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_SERVER_MODULE
+ * @brief Called when a transfer is finished.
+ * @param[in] error_code The result of push
+ * @param[in] file The path of file to be pushed
+ * @param[in] size The file size (bytes)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_server_accept()
+ * @see bt_opp_server_accept_connection()
+ */
+typedef void (*bt_opp_server_transfer_finished_cb) (int result, const char *file, long long size, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Called when OPP server responds to the push request.
+ * @param[in] result The result of OPP server response
+ * @param[in] remote_address The remote address
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre bt_opp_client_push_files() will invoke this function.
+ * @see bt_opp_client_push_files()
+ */
+typedef void (*bt_opp_client_push_responded_cb)(int result, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Called when each file is being transfered.
+ * @param[in] file The path of file to be pushed
+ * @param[in] size The file size (bytes)
+ * @param[in] percent The progress in percentage (1 ~ 100). 100 means that a file is transfered completely.
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre bt_opp_client_push_files() will invoke this function.
+ * @see bt_opp_client_push_files()
+ */
+typedef void (*bt_opp_client_push_progress_cb)(const char *file, long long size, int percent, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_OPP_CLIENT_MODULE
+ * @brief Called when the push request is finished.
+ * @param[in] result The result of the push request
+ * @param[in] remote_address The remote address
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_opp_client_push_files()
+ */
+typedef void (*bt_opp_client_push_finished_cb)(int result, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_MODULE
+ * @brief Called when the connection state is changed.
+ * @details This callback is called when the connection state is changed.
+ * When you call bt_audio_connect() or bt_audio_disconnect(), this callback is also called with error result even though these functions fail.
+ * @param[in] result The result of changing the connection state
+ * @param[in] connected The state to be changed. @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address The remote address
+ * @param[in] type The type of audio profile except #BT_AUDIO_PROFILE_TYPE_ALL
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_audio_set_connection_state_changed_cb()
+ * @see bt_audio_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_audio_connection_state_changed_cb) (int result, bool connected, const char *remote_address, bt_audio_profile_type_e type, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Called when the SCO(Synchronous Connection Oriented link) state is changed.
+ * @details This callback is called when the SCO state is changed.
+ * When you call bt_ag_open_sco() or bt_ag_close_sco(), this callback is also called with error result even though these functions failed.
+ * @param[in] result The result of changing the connection state
+ * @param[in] opened The state to be changed: (@c true = opened, @c false = not opened)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_sco_state_changed_cb()
+ * @see bt_ag_unset_sco_state_changed_cb()
+ * @see bt_ag_open_sco()
+ * @see bt_ag_close_sco()
+ */
+typedef void (*bt_ag_sco_state_changed_cb) (int result, bool opened, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Called when a call handling event happened from Hands-Free.
+ * @param[in] event The call handling event happened from Hands-Free
+ * @param[in] call_id The call ID
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_call_handling_event_cb()
+ * @see bt_ag_unset_call_handling_event_cb()
+ */
+typedef void (*bt_ag_call_handling_event_cb) (bt_ag_call_handling_event_e event, unsigned int call_id, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Called when a multi call handling event happened from Hands-Free.
+ * @param[in] event The call handling event happened from Hands-Free
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_multi_call_handling_event_cb()
+ * @see bt_ag_unset_multi_call_handling_event_cb()
+ */
+typedef void (*bt_ag_multi_call_handling_event_cb) (bt_ag_multi_call_handling_event_e event, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Called when a DTMF(Dual Tone Multi Frequency) is transmitted from Hands-Free.
+ * @param[in] dtmf The DTMF transmitted from Hands-Free
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_dtmf_transmitted_cb()
+ * @see bt_ag_unset_dtmf_transmitted_cb()
+ */
+typedef void (*bt_ag_dtmf_transmitted_cb) (const char *dtmf, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Called when the speaker gain of the remote device is changed.
+ * @param[in] gain The gain of speaker (0 ~ 15)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_speaker_gain_changed_cb()
+ * @see bt_ag_unset_speaker_gain_changed_cb()
+ */
+typedef void (*bt_ag_speaker_gain_changed_cb) (int gain, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Called when the microphone gain of the remote device is changed.
+ * @param[in] gain The gain of microphone (0 ~ 15)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_microphone_gain_changed_cb()
+ * @see bt_ag_unset_microphone_gain_changed_cb()
+ */
+typedef void (*bt_ag_microphone_gain_changed_cb) (int gain, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Called when the connection state is changed.
+ * @param[in] connected The state to be changed. @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address The remote address
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_target_initialize()
+ * @see bt_avrcp_target_deinitialize()
+ */
+typedef void (*bt_avrcp_target_connection_state_changed_cb) (bool connected, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Called when the equalizer state is changed by the remote control device.
+ * @param[in] equalizer The equalizer state
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_set_equalizer_state_changed_cb()
+ * @see bt_avrcp_unset_equalizer_state_changed_cb()
+ */
+typedef void (*bt_avrcp_equalizer_state_changed_cb) (bt_avrcp_equalizer_state_e equalizer, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Called when the repeat mode is changed by the remote control device.
+ * @param[in] repeat The repeat mode
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_set_repeat_mode_changed_cb()
+ * @see bt_avrcp_unset_repeat_mode_changed_cb()
+ */
+typedef void (*bt_avrcp_repeat_mode_changed_cb) (bt_avrcp_repeat_mode_e repeat, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Called when the shuffle mode is changed by the remote control device.
+ * @param[in] shuffle The shuffle mode
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_set_shuffle_mode_changed_cb()
+ * @see bt_avrcp_unset_shuffle_mode_changed_cb()
+ */
+typedef void (*bt_avrcp_shuffle_mode_changed_cb) (bt_avrcp_shuffle_mode_e shuffle, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AVRCP_MODULE
+ * @brief Called when the scan mode is changed by the remote control device.
+ * @param[in] shuffle The shuffle mode
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_avrcp_set_scan_mode_changed_cb()
+ * @see bt_avrcp_unset_scan_mode_changed_cb()
+ */
+typedef void (*bt_avrcp_scan_mode_changed_cb) (bt_avrcp_scan_mode_e scan, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HID_MODULE
+ * @brief Called when the connection state is changed.
+ * @details This callback is called when the connection state is changed.
+ * When you call bt_hid_host_connect() or bt_hid_host_disconnect(), this callback is also called with error result even though these functions fail.
+ * @param[in] result The result of changing the connection state
+ * @param[in] connected The state to be changed. @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address The remote address
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_hid_host_connect()
+ * @see bt_hid_host_disconnect()
+ */
+typedef void (*bt_hid_host_connection_state_changed_cb) (int result, bool connected, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Called when the connection is established.
+ * @param[in] result The result of connecting to the remote device
+ * @param[in] remote_address The address of connected remote device
+ * @param[in] app_id The ID of application
+ * @param[in] type The type of HDP(Health Device Profile) channel
+ * @param[in] channel The connected data channel
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_hdp_disconnected_cb
+ * @see bt_hdp_set_connection_state_changed_cb()
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_hdp_connected_cb) (int result, const char *remote_address, const char *app_id,
+ bt_hdp_channel_type_e type, unsigned int channel, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Called when the connection is disconnected.
+ * @param[in] result The result of disconnecting from the remote device
+ * @param[in] remote_address The address of disconnected remote device
+ * @param[in] channel The connected data channel
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_hdp_connected_cb
+ * @see bt_hdp_set_connection_state_changed_cb()
+ * @see bt_hdp_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_hdp_disconnected_cb) (int result, const char *remote_address, unsigned int channel, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_HDP_MODULE
+ * @brief Called when the you receive the data.
+ * @param[in] channel The connected data channel
+ * @param[in] data The received data
+ * @param[in] size The size of received data (byte)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_hdp_set_data_received_cb()
+ * @see bt_hdp_unset_data_received_cb()
+ */
+typedef void (*bt_hdp_data_received_cb) (unsigned int channel, const char *data, unsigned int size, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when you get the primary services repeatedly.
+ * @param[in] service The attribute handle of service
+ * @param[in] index The index of a service, starts from 0
+ * @param[in] total The total number of services
+ * @param[in] user_data The user data passed from the foreach function
+ * @return @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre bt_gatt_foreach_primary_services() will invoke this function.
+ * @see bt_gatt_foreach_primary_services()
+ */
+typedef bool (*bt_gatt_primary_service_cb) (bt_gatt_attribute_h service, int index, int total, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called after the characteristics are discovered by bt_gatt_discover_characteristics().
+ * @remarks If bt_gatt_discover_characteristics() failed, then this callback function is called only once with 0 totla and NULL characteristic_handle.
+ * @param[in] result The result of discovering
+ * @param[in] index The index of characteristics in a service, starts from 0
+ * @param[in] total The total number of characteristics in a service
+ * @param[in] characteristic The attribute handle of characteristic
+ * @param[in] user_data The user data passed from the request function
+ * @return @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre bt_gatt_discover_characteristics() will invoke this callback.
+ * @see bt_gatt_discover_characteristics()
+ */
+typedef bool (*bt_gatt_characteristics_discovered_cb) (int result, int index, int total, bt_gatt_attribute_h characteristic, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when you get the included services repeatedly.
+ * @param[in] service The attribute handle of service
+ * @param[in] user_data The user data passed from the foreach function
+ * @return @c true to continue with the next iteration of the loop,
+ * \n @c false to break out of the loop.
+ * @pre bt_gatt_foreach_included_services() will invoke this function.
+ * @see bt_gatt_foreach_included_services()
+ */
+typedef bool (*bt_gatt_included_service_cb) (bt_gatt_attribute_h service, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when a characteristic in service is changed.
+ * @param[in] characteristic The attribute handle of characteristic
+ * @param[in] value The value of characteristic (byte array)
+ * @param[in] value_length The length of value
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_gatt_set_characteristic_changed_cb()
+ * @see bt_gatt_unset_characteristic_changed_cb()
+ */
+typedef void (*bt_gatt_characteristic_changed_cb) (bt_gatt_attribute_h characteristic, unsigned char *value, int value_length, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when a characteristic value is written.
+ * @see bt_gatt_set_characteristic_value()
+ */
+typedef void (*bt_gatt_characteristic_write_cb) (int result, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when a characteristic value is read.
+ * @param[in] value The value of characteristic (byte array)
+ * @param[in] value_length The length of value
+ * @param[in] user_data The user data passed from the foreach function
+ * @see bt_gatt_read_characteristic_value()
+ */
+typedef void (*bt_gatt_characteristic_read_cb) (unsigned char *value,
+ int value_length, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called after the characteristics descriptors are discovered by bt_gatt_discover_characteristic_descriptor().
+ * @param[in] result The result of discovering
+ * @param[in] characteristic_format The format of the information data.
+ * characteristic_format = 0x01 indicates UUIDs are 16-bits
+ * characteristic_format = 0x02 indicates UUIDs are 128-bits
+ * @param[in] total The total number of elements in characteristic_descriptor
+ * @param[in] characteristic descriptor The attribute handle and the UUID of characteristic descriptor
+ * @param[in] characteristic The attribute handle and the UUID of characteristic
+ * @param[in] user_data The user data passed from the request function
+ * @see bt_gatt_discover_characteristic_descriptor()
+ */
+typedef void (*bt_gatt_characteristic_descriptor_discovered_cb) (int result,
+ unsigned char characteristic_format, int total,
+ bt_gatt_attribute_h characteristic_descriptor,
+ bt_gatt_attribute_h characteristic, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when the connection state is changed.
+ * @details This callback is called when the connection state is changed.
+ * When you called bt_gatt_connect() or bt_gatt_disconnect(), this callback is also called with error result even though these functions fail.
+ *
+ * @param[in] result The result of changing the connection state.
+ * @param[in] connected The state to be changed, @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address The remote_address
+ * @param[in] user_data The user data passed from the callback registration function.
+ *
+ * @see bt_gatt_connect()
+ * @see bt_gatt_disconnect()
+ * @see bt_gatt_set_connection_state_changed_cb()
+ * @see bt_gatt_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_gatt_connection_state_changed_cb)(int result, bool connected, const char *remote_address, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_GATT_MODULE
+ * @brief Called when the remote devices writes a characteristic to the server db.
+ * @details This callback is called when the remote client device writes a characteristics
+ * to the server attribute database.
+ *
+ * @param[in] char_path Characteristic path for which the value is writtten.
+ * @param[in] char_value The characteristic value
+ * @param[in] value_length The length of the characteristic value written.
+ *
+ * @see bt_gatt_connect()
+ */
+typedef void (*bt_gatt_remote_characteristic_write_cb) (char *char_path,
+ unsigned char* char_value, int value_length,
+ void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_NAP_MODULE
+ * @brief Called when the connection state is changed.
+ * @param[in] connected Indicates whether a client is connected or disconnected
+ * @param[in] remote_address The remote address
+ * @param[in] interface_name The interface name. For example, bnep0, bnep1.
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_nap_set_connection_state_changed_cb()
+ * @see bt_nap_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_nap_connection_state_changed_cb) (bool connected, const char *remote_address, const char *interface_name, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_PAN_PANU_MODULE
+ * @brief Called when the connection state is changed.
+ * @details This callback is called when the connection state is changed.
+ * When you call bt_panu_connect() or bt_panu_disconnect(), this callback is also called with error result even though these functions fail.
+ * @param[in] result The result of changing the connection state
+ * @param[in] connected The state to be changed. @a true means connected state, Otherwise, @a false.
+ * @param[in] remote_address The remote address
+ * @param[in] type The type of PAN service
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_nap_set_connection_state_changed_cb()
+ * @see bt_nap_unset_connection_state_changed_cb()
+ */
+typedef void (*bt_panu_connection_state_changed_cb) (int result, bool connected, const char *remote_address, bt_panu_service_type_e type, void *user_data);
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __TIZEN_NETWORK_BLUETOOTH_TYPE_H__
--- /dev/null
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
+#define __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
+
+#include "bluetooth_type.h"
+#include "bluetooth_type_product.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * @file bluetooth_product.h
+ */
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Sets the manufacturer data of local Bluetooth adapter.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] data The manufacturer specific data of the Bluetooth device.
+ * @param[in] len The length of @a data.Maximaum length is 240 bytes.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @post bt_adapter_manufacturer_data_changed_cb() will be invoked
+ * if this function returns #BT_ERROR_NONE.
+ *
+ * @see bt_adapter_manufacturer_data_changed_cb
+ * @see bt_adapter_set_manufacturer_data_changed_cb()
+ * @see bt_adapter_unset_manufacturer_data_changed_cb()
+ */
+int bt_adapter_set_manufacturer_data(char *data, int len);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Registers a callback function to be invoked
+ * when the manufacturer data of Bluetooth adapter changes.
+ * @since_tizen 2.3
+ *
+ * @param[in] callback The callback function to invoke
+ * @param[in] user_data The user data to be passed to the callback function
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @post bt_adapter_manufacturer_data_changed_cb() will be invoked.
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_unset_manufacturer_data_changed_cb()
+ */
+int bt_adapter_set_manufacturer_data_changed_cb(
+ bt_adapter_manufacturer_data_changed_cb callback,
+ void *user_data);
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Unregisters the callback function.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ *
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ *
+ * @see bt_initialize()
+ * @see bt_adapter_set_manufacturer_data_changed_cb()
+ */
+int bt_adapter_unset_manufacturer_data_changed_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Sets the scan interval and widow, synchronously.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] scan_params The parameters of le scanning \n
+ * If NULL is passed, default values which are defined in driver / controller are used.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_ENABLED Adapter is not enabled
+ * @retval #BT_ERROR_INVALID_PARAM Parameter is invalid
+ * @pre The state of local Bluetooth must be #BT_ADAPTER_ENABLED.
+ * @pre The Bluetooth service must be initialized with bt_initialize().
+ * @see bt_initialize()
+ */
+int bt_adapter_le_set_scan_parameter(bt_adapter_le_scan_params_s *scan_params);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Enables RSSI monitoring and sets threshold for LE/ACL link present with the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device for which RSSI is to be monitored
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] low_threshold Lower threshold value for the LE Link in dBm.
+ * @param[in] in_range_threshold In-Range threshold value for the LE Link in dBm.
+ * @param[in] cb_enable Callback to be called when RSSI monitoring is enabled.
+ * @param[in] user_data_enable Data to be passed to RSSI enable callback.
+ * @param[in] cb_alert Callback to receive RSSI Alert values.
+ * @param[in] user_data_alert Data to be passed to RSSI Alert callback.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @remarks High Threshold value is set to 127.
+ *
+ * @see bt_device_unset_rssi_alert_cb()
+ * @see bt_device_disable_rssi_monitor()
+ */
+int bt_device_enable_rssi_monitor(const char *remote_address,
+ bt_device_connection_link_type_e link_type,
+ int low_threshold, int in_range_threshold,
+ bt_rssi_monitor_enabled_cb cb_enable, void *user_data_enable,
+ bt_rssi_alert_cb cb_alert, void *user_data_alert);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Disables RSSI monitoring for LE/ACL link present with the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device for which RSSI monitoring is to be disabled
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] cb_disable Callback to be called when RSSI monitoring is disabled.
+ * @param[in] user_data_enable Data to be passed to RSSI enable callback.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @remarks Low Threshold, In-range Threshold and High Threshold value are set to 0 to disable RSSI monitoring.
+ * @remarks This also calls bt_device_unset_rssi_alert_cb()
+ *
+ * @see bt_device_unset_rssi_alert_cb()
+ * @see bt_device_enable_rssi_monitor()
+ */
+int bt_device_disable_rssi_monitor(const char *remote_address,
+ bt_device_connection_link_type_e link_type,
+ bt_rssi_monitor_enabled_cb cb_disable, void *user_data_disable);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Get Raw RSSI for LE link present with the remote device.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ *
+ * @param[in] remote_address The address of the remote Bluetooth device for which RSSI is to be monitored
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] callback Callback to receive Raw RSSI values.
+ * @param[in] user_data Data to be passed to Raw RSSI callback.
+ *
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_RESOURCE_BUSY Device or resource busy
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ *
+ * @see bt_device_le_unset_rssi_strength_cb()
+ */
+int bt_device_get_rssi_strength(const char *remote_address,
+ bt_device_connection_link_type_e link_type,
+ bt_rssi_strength_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Unset the callback to receive RSSI Alert values.
+ * @since_tizen 2.3
+ *
+ * @return 0 on success, otherwise a negative error value.
+ *
+ * @see bt_device_le_enable_rssi()
+ */
+int bt_device_unset_rssi_alert_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Notifies the XSAT vendor command to the remote.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] state The XSAT vendor dependent command string. Ex: "AT+SAT= 00,TY,WA"
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_BONDED Remote device is not bonded
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @retval #BT_ERROR_OPERATION_FAILED Operation failed
+ * @pre The Bluetooth audio device must be connected with bt_audio_connect().
+ * @see bt_audio_connect()
+ */
+int bt_ag_notify_vendor_cmd(const char *command);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Registers a callback function that will be invoked when a XSATvendor AT command is transmitted from Hands-Free.
+ * @since_tizen 2.3
+ * @param[in] callback The callback function to register
+ * @param[in] user_data The user data to be passed to the callback function
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_vendor_cmd_cb()
+ * @see bt_ag_unset_vendor_cmd_cb()
+ */
+int bt_ag_set_vendor_cmd_cb(bt_ag_vendor_cmd_cb callback, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Unregisters a callback function that will be invoked when a XSATvendor AT command is transmitted from Hands-Free
+ * @since_tizen 2.3
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @pre The Bluetooth audio service must be initialized with bt_audio_initialize().
+ * @see bt_audio_initialize()
+ * @see bt_ag_vendor_cmd_cb()
+ * @see bt_ag_set_vendor_cmd_cb()
+ */
+int bt_ag_unset_vendor_cmd_cb(void);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Checks whether the remoted device is wbs (Wide Band Speech) mode or not.
+ * @since_tizen 2.3
+ * @param[out] wbs_mode The wbs status: (@c true = wide band speech, @c false = narrow band speech)
+ * @return 0 on success, otherwise a negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_NOT_INITIALIZED Not initialized
+ * @retval #BT_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval #BT_ERROR_NOT_ENABLED Not enabled
+ * @retval #BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED Remote device is not connected
+ * @pre The remote device is connected by bt_audio_connect() with #BT_AUDIO_PROFILE_TYPE_HSP_HFP service.
+ * @see bt_audio_connect()
+ */
+int bt_ag_is_wbs_mode(bool *wbs_mode);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_A2DP_MODULE
+ * @brief Sets copy protection. streaming application that needs to have the copy protection for the streaming data, shall invoke this API.
+ * @since_tizen 2.3
+ * @privlevel platform
+ * @privilege %http://tizen.org/privilege/bluetooth.admin
+ * @param[in] status - TRUE/FALSE
+ * @return 0 on success, otherwise negative error value.
+ * @retval #BT_ERROR_NONE Successful
+ * @retval #BT_ERROR_OPERATION_FAILED on failure
+ */
+int bt_a2dp_set_content_protection(bool status);
+
+
+/**
+ * @}
+ */
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __TIZEN_NETWORK_BLUETOOTH_PRODUCT_H__
--- /dev/null
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the License);
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
+#define __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
+
+ #ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/**
+ * @file bluetooth_type_product.h
+ */
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Enumerations of the Bluetooth adapter le scan type.
+ */
+typedef enum
+{
+ BT_ADAPTER_LE_PASSIVE_SCAN = 0x00,
+ BT_ADAPTER_LE_ACTIVE_SCAN
+} bt_adapter_le_scan_type_e;
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_LE_MODULE
+ * @brief Structure of le scan parameters
+ *
+ * @see bt_adapter_le_set_scan_parameter()
+ * @see bt_adapter_le_start_device_discovery()
+ */
+typedef struct {
+ bt_adapter_le_scan_type_e type; /**< LE scan type */
+ float interval; /**< LE scan interval */
+ float window; /**< LE scan window */
+} bt_adapter_le_scan_params_s;
+
+/**
+ * @internal
+ * @ingroup CAPI_NETWORK_BLUETOOTH_ADAPTER_MODULE
+ * @brief Called when the manufacturer dat changes.
+ * @param[in] data The manufacurer data of the Bluetooth device to be changed
+ * @param[in] len The length of @a data
+ * @param[in] user_data The user data passed from the callback registration function
+ * @pre This function will be invoked when the manufacturer data of Bluetooth adapter changes
+ * if callback is registered using bt_adapter_set_manufacturer_data_changed_cb().
+ * @see bt_adapter_set_manufacturer_data()
+ * @see bt_adapter_set_manufacturer_data_changed_cb()
+ * @see bt_adapter_unset_manufacturer_data_changed_cb()
+ */
+typedef void (*bt_adapter_manufacturer_data_changed_cb) (char *data,
+ int len, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when RSSI monitoring is enabled.
+ * @param[in] remote_address Remote Device address
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] rssi_enabled RSSI monitoring status (@c 1 = enabled, @c 0 = disabled)
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_device_enable_rssi_monitor()
+ * @see bt_device_disable_rssi_monitor()
+ */
+typedef void (*bt_rssi_monitor_enabled_cb)(const char *remote_address,
+ bt_device_connection_link_type_e link_type,
+ int rssi_enabled, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when RSSI Alert is received.
+ * @param[in] remote_address Remote Device address
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] rssi_alert_type RSSI Alert type (@c 1 = High Alert (In-Range Alert), @c 2 = Low Alert)
+ * @param[in] rssi_alert_dbm RSSI Alert signal strength value
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_device_enable_rssi_monitor()
+ * @see bt_device_disable_rssi_monitor()
+ */
+typedef void (*bt_rssi_alert_cb)(char *bt_address,
+ bt_device_connection_link_type_e link_type,
+ int rssi_alert_type, int rssi_alert_dbm, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_DEVICE_MODULE
+ * @brief Called when Raw RSSI signal strength is received.
+ * @param[in] remote_address Remote Device address
+ * @param[in] link_type Link type for the connection (@c 0 = BR/EDR link, @c 1 = LE link).
+ * @param[in] rssi_dbm Raw RSSI signal strength value
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_device_get_rssi_strength()
+ */
+typedef void (*bt_rssi_strength_cb)(char *bt_address,
+ bt_device_connection_link_type_e link_type,
+ int rssi_dbm, void *user_data);
+
+/**
+ * @ingroup CAPI_NETWORK_BLUETOOTH_AUDIO_AG_MODULE
+ * @brief Called when a XSAT vendor command is transmitted from Hands-Free.
+ * @param[in] command The XSAT vendor command transmitted from Hands-Free
+ * @param[in] user_data The user data passed from the callback registration function
+ * @see bt_ag_set_vendor_cmd_cb()
+ * @see bt_ag_unset_vendor_cmd_cb()
+ */
+typedef void (*bt_ag_vendor_cmd_cb) (char *command, void *user_data);
+
+
+/**
+ * @}
+ */
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#endif // __TIZEN_NETWORK_BLUETOOTH_TYPE_PRODUCT_H__
+++ /dev/null
-#Assumes ndk directory is at ~/
-#set ndk directory PATH in .bashrc and use the ndk-build directly
-NDK_PATH = ~/ndk
-NDK_BUILD = $(NDK_PATH)/ndk-build
-
-BUILD_DIR = $(CURDIR)
-APPLICATION_BUILD = $(BUILD_DIR)
-ROOT_DIR = $(BUILD_DIR)
-
-#Clean files
-LIBS_DIR = $(ROOT_DIR)/libs
-OBJ_DIR = $(ROOT_DIR)/obj
-
-all:
- $(NDK_BUILD) NDK_PROJECT_PATH=$(APPLICATION_BUILD)
-
-clean :
- @$(RM) -rf $(LIBS_DIR) $(OBJ_DIR)
\ No newline at end of file
+++ /dev/null
-APP_PATH := $(call my-dir)
-
-#specify project root path here wrt make file directory
-PROJECT_ROOT_PATH = ../../..
-PROJECT_API_PATH = $(PROJECT_ROOT_PATH)/api
-
-#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-#Build sample_main
-include $(CLEAR_VARS)
-LOCAL_PATH = $(APP_PATH)
-LOCAL_MODULE = sample
-LOCAL_C_INCLUDES = $(PROJECT_API_PATH)
-LOCAL_STATIC_LIBRARIES = CA
-LOCAL_SRC_FILES = sample_main.c
-include $(BUILD_EXECUTABLE)
-#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-#Build glib CACommon CACoap CA
-include $(CLEAR_VARS)
-PROJECT_LIB_PATH = $(PROJECT_ROOT_PATH)/build/android
-include $(PROJECT_LIB_PATH)/jni/Android.mk
-#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
+++ /dev/null
-APP_STL := gnustl_static
-
-APP_PLATFORM = android-19
-APP_CPPFLAGS += -fexceptions
-#APP_CPPFLAGS += -frtti += -Wno-error=format-security
-APP_CFLAGS = -Wno-error=format-security
\ No newline at end of file
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2014 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "cacommon.h"
-#include "cainterface.h"
-
-#define MAX_BUF_LEN 1024
-#define MAX_OPT_LEN 16
-#define TRUE 1
-#define FALSE 0
-
-char get_menu();
-void process();
-
-void start_listening_server();
-void start_discovery_server();
-void find_resource();
-void send_request();
-void send_response();
-void advertise_resource();
-void send_notification();
-void select_network();
-void unselect_network();
-void handle_request_response();
-void find_fixed_resource();
-
-void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo);
-void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo);
-void send_request_tmp(CARemoteEndpoint_t* endpoint, CAToken_t token);
-int received = FALSE;
-
-int main()
-{
- system("clear");
-
- printf("=============================================\n");
- printf("\t\tsample main\n");
- printf("=============================================\n");
-
- CAInitialize();
-
- // network enable
- // default
- printf("select default network(WIFI)\n");
- CASelectNetwork(CA_WIFI);
-
- // set handler.
- CARegisterHandler(request_handler, response_handler);
-
- process();
-
- CATerminate();
-
- return 0;
-}
-
-void process()
-{
- while (1)
- {
- char menu = get_menu();
-
- switch (menu)
- {
- case 'm': // menu
- case 'M':
- continue;
-
- case 'q': // quit
- case 'Q':
- printf("quit..!!\n");
- return;
-
- case 's': // start server
- case 'S':
- start_listening_server();
- break;
-
- case 'c': // start client
- case 'D':
- start_discovery_server();
- break;
-
- case 'f': // find resource
- case 'F':
- find_resource();
- break;
-
- case 'r': // send request
- case 'R':
- send_request();
- break;
-
- case 'a': // advertise resource
- case 'A':
- advertise_resource();
- break;
-
- case 'b': // send notification
- case 'B':
- send_notification();
- break;
-
- case 'n': // select network
- case 'N':
- select_network();
- break;
-
- case 'x': // unselect network
- case 'X':
- unselect_network();
- break;
-
- case 'h': // handle request response
- case 'H':
- handle_request_response();
- break;
- case 'y':
- case 'Y':
- while (1)
- {
- received = FALSE;
- find_fixed_resource();
- while (received == FALSE)
- {
- sleep(1);
- handle_request_response();
-
- }
- }
- break;
- case 'z':
- case 'Z':
- start_listening_server();
- while (1)
- {
- sleep(1);
- handle_request_response();
- }
- break;
-
- default:
- printf("not supported menu!!\n");
- break;
- }
- }
-
-}
-
-void start_listening_server()
-{
- printf("start listening server!!\n");
-
- CAStartListeningServer();
-}
-
-void start_discovery_server()
-{
- printf("start discovery client!!\n");
-
- CAStartDiscoveryServer();
-}
-
-void find_fixed_resource()
-{
- char buf[MAX_BUF_LEN] =
- { 0, };
- strcpy(buf, "a/light");
-
- CAResult_t res = CAFindResource(buf, "temptoken");
-
- if (res != CA_STATUS_OK)
- {
- printf("find resource error!!\n");
- }
- else
- {
- printf("find resource to %s URI\n", buf);
- }
-
- printf("=============================================\n");
-}
-
-void find_resource()
-{
- char buf[MAX_BUF_LEN];
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- printf("\n=============================================\n");
- printf("ex) a/light\n");
- printf("reference uri : ");
-
- gets(buf);
-
- CAResult_t res = CAFindResource(buf, "temptoken");
-
- if (res != CA_STATUS_OK)
- {
- printf("find resource error!!\n");
- }
- else
- {
- printf("find resource to %s URI\n", buf);
- }
-
- printf("=============================================\n");
-}
-
-void send_request()
-{
- char buf[MAX_BUF_LEN];
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- printf("\n=============================================\n");
- printf("10.11.12.13:4545/resource_uri ( for IP )\n");
- printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
- printf("uri : ");
-
- gets(buf);
-
- // create remote endpoint
- CARemoteEndpoint_t* endpoint = NULL;
- CAResult_t res = CACreateRemoteEndpoint(buf, &endpoint);
-
- if (res != CA_STATUS_OK)
- {
- printf("create remote endpoint error!!");
- CADestroyRemoteEndpoint(endpoint);
- return;
- }
-
- // create token
- CAToken_t token = NULL;
- res = CAGenerateToken(&token);
-
- if (res != CA_STATUS_OK)
- {
- printf("token generate error!!");
- token = NULL;
- }
-
- printf("generated token %s\n", (token != NULL) ? token : "");
-
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
- requestData.token = token;
- requestData.payload = "Temp Json Payload";
-
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
- requestInfo.method = CA_GET;
- requestInfo.info = requestData;
-
- // send request
- CASendRequest(endpoint, &requestInfo);
-
- if (token != NULL)
- {
- CADestroyToken(token);
- }
-
- // destroy remote endpoint
- if (endpoint != NULL)
- {
- CADestroyRemoteEndpoint(endpoint);
- }
-
- printf("=============================================\n");
-}
-
-void advertise_resource()
-{
- char buf[MAX_BUF_LEN];
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- printf("\n=============================================\n");
- printf("uri : ");
-
- scanf("%s", buf);
-
- int optionNum = 0;
- char optionData[MAX_OPT_LEN];
-
- printf("Option Num : ");
- scanf("%d", &optionNum);
- CAHeaderOption_t *headerOpt;
- headerOpt = (CAHeaderOption_t*) malloc(sizeof(CAHeaderOption_t) * optionNum);
- if (NULL == headerOpt)
- {
- printf("Memory allocation failed!\n");
- return;
- }
- memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
-
- int i;
- for (i = 0; i < optionNum; i++)
- {
- int optionID = 0;
- printf("[%d] Option ID : ", i + 1);
- scanf("%d", &optionID);
- headerOpt[i].optionID = optionID;
-
- memset(optionData, 0, sizeof(char) * MAX_OPT_LEN);
- printf("[%d] Option Data : ", i + 1);
- scanf("%s", optionData);
- memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
- printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
-
- headerOpt[i].optionLength = (uint16_t) strlen(optionData);
- }
- printf("\n=============================================\n");
-
- CAAdvertiseResource(buf, "temptoken", headerOpt, (uint8_t) optionNum);
-
- free(headerOpt);
-
-}
-
-void send_notification()
-{
- char buf[MAX_BUF_LEN];
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- printf("\n=============================================\n");
- printf("10.11.12.13:4545/resource_uri ( for IP )\n");
- printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
- printf("uri : ");
-
- gets(buf);
-
- // create remote endpoint
- CARemoteEndpoint_t* endpoint = NULL;
- CAResult_t res = CACreateRemoteEndpoint(buf, &endpoint);
-
- if (res != CA_STATUS_OK)
- {
- printf("create remote endpoint error!!");
- CADestroyRemoteEndpoint(endpoint);
- return;
- }
-
- CAInfo_t respondeData;
- memset(&respondeData, 0, sizeof(CAInfo_t));
- respondeData.token = "client token";
- respondeData.payload = "Temp Notification Data";
-
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_SUCCESS;
- responseInfo.info = respondeData;
-
- // send request
- CASendNotification(endpoint, &responseInfo);
-
- // destroy remote endpoint
- if (endpoint != NULL)
- {
- CADestroyRemoteEndpoint(endpoint);
- }
- printf("\n=============================================\n");
-}
-
-void select_network()
-{
- char buf[MAX_BUF_LEN];
-
- printf("\n=============================================\n");
- printf("\tselect network\n");
- printf("ETHERNET : 0\n");
- printf("WIFI : 1\n");
- printf("EDR : 2\n");
- printf("LE : 3\n");
- printf("select : ");
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- gets(buf);
-
- int number = buf[0] - '0';
-
- number = (number < 0 || number > 3) ? 1 : number;
-
- CASelectNetwork(1 << number);
-
- printf("=============================================\n");
-}
-
-void unselect_network()
-{
- char buf[MAX_BUF_LEN];
-
- printf("\n=============================================\n");
- printf("\tunselect enabled network\n");
- printf("ETHERNET : 0\n");
- printf("WIFI : 1\n");
- printf("EDR : 2\n");
- printf("LE : 3\n");
- printf("select : ");
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- gets(buf);
-
- int number = buf[0] - '0';
-
- number = (number < 0 || number > 3) ? 1 : number;
-
- CAUnSelectNetwork(1 << number);
-
- printf("=============================================\n");
-}
-
-char get_menu()
-{
- char buf[MAX_BUF_LEN];
-
- printf("\n=============================================\n");
- printf("\t\tMenu\n");
- printf("\ts : start server\n");
- printf("\tc : start client\n");
- printf("\tf : find resource\n");
- printf("\tr : send request\n");
- printf("\ta : advertise resource\n");
- printf("\tb : send notification\n");
- printf("\tn : select network\n");
- printf("\tx : unselect network\n");
- printf("\th : handle request response\n");
- printf("\ty : run static client\n");
- printf("\tz : run static server\n");
- printf("\tq : quit\n");
- printf("=============================================\n");
- printf("select : ");
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- gets(buf);
-
- return buf[0];
-}
-
-void handle_request_response()
-{
- printf("handle_request_response\n");
- CAHandleRequestResponse();
-}
-
-void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo)
-{
-
- printf("[CALLBACK] request_handler, uri : %s, data : %s\n",
- (object != NULL) ? object->resourceUri : "",
- (requestInfo != NULL) ? requestInfo->info.payload : "");
-
- printf("[CALLBACK] request_handler, address : %s\n",
- (object != NULL) ? object->addressInfo.IP.ipAddress : "");
-
- if (requestInfo->info.options)
- {
- uint32_t len = requestInfo->info.numOptions;
- uint32_t i;
- for (i = 0; i < len; i++)
- {
- printf("[CALLBACK] request_handler, option ID : %d\n",
- requestInfo->info.options[i].optionID);
- printf("[CALLBACK] request_handler, options data length : %d\n",
- requestInfo->info.options[i].optionLength);
- printf("[CALLBACK] request_handler, options data : %s\n",
- requestInfo->info.options[i].optionData);
- }
- }
-
- printf("send response with URI\n");
- send_response(object, (requestInfo != NULL) ? requestInfo->info.token : "");
-
- received = TRUE;
-
-}
-
-void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo)
-{
-
- printf("[CALLBACK] response_handler, uri : %s, data : %s\n",
- (object != NULL) ? object->resourceUri : "",
- (responseInfo != NULL) ? responseInfo->info.payload : "");
-
- printf("[CALLBACK] response_handler, address : %s\n",
- (object != NULL) ? object->addressInfo.IP.ipAddress : "");
-
- if (responseInfo->info.options)
- {
- uint32_t len = responseInfo->info.numOptions;
- uint32_t i;
- for (i = 0; i < len; i++)
- {
- printf("[CALLBACK] response_handler, option ID : %d\n",
- responseInfo->info.options[i].optionID);
- printf("[CALLBACK] response_handler, options data length : %d\n",
- responseInfo->info.options[i].optionLength);
- printf("[CALLBACK] response_handler, options data : %s\n",
- responseInfo->info.options[i].optionData);
- }
- }
- received = TRUE;
-
- //printf("send request with URI\n");
- //send_request_tmp(object, (responseInfo != NULL) ? responseInfo->info.token : "");
-}
-
-void send_response(CARemoteEndpoint_t* endpoint, CAToken_t request_token)
-{
-
- printf("\n=============================================\n");
-
- CAInfo_t responseData;
- //responseData = (CAInfo*) malloc(sizeof(CAInfo));
- memset(&responseData, 0, sizeof(CAInfo_t));
- responseData.token = request_token;
- responseData.payload = "response payload";
-
- CAResponseInfo_t responseInfo;
- //responseInfo = (CAResponseInfo*) malloc(sizeof(CAResponseInfo));
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = 203;
- responseInfo.info = responseData;
-
- // send request (connectivityType from remoteEndpoint of request Info)
- CASendResponse(endpoint, &responseInfo);
-
- printf("=============================================\n");
-
-}
-
-void send_request_tmp(CARemoteEndpoint_t* endpoint, CAToken_t token)
-{
-
- printf("\n=============================================\n");
-
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
- requestData.token = token;
- requestData.payload = "Temp Json Payload";
-
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
- requestInfo.method = CA_GET;
- requestInfo.info = requestData;
-
- // send request
- endpoint->connectivityType = CA_WIFI;
- CASendRequest(endpoint, &requestInfo);
-
- printf("=============================================\n");
-
-}
-
android:theme="@style/AppTheme" >
<activity
android:name="com.iotivity.service.MainActivity"
- android:label="@string/app_name"
+ android:label="@string/app_name"
android:windowSoftInputMode="stateHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
</application>
-
+
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
</manifest>
+
$(NDK_BUILD) NDK_PROJECT_PATH=$(APPLICATION_BUILD)
clean :
- @$(RM) -rf $(LIBS_DIR) $(OBJ_DIR)
\ No newline at end of file
+ @$(RM) -rf $(LIBS_DIR) $(OBJ_DIR)
LOCAL_SRC_FILES := ResourceModel.c
LOCAL_STATIC_LIBRARIES := CA
LOCAL_LDLIBS := -llog
+LOCAL_C_INCLUDES := ../../../api
include $(BUILD_SHARED_LIBRARY)
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
CA_LIB_PATH = $(PROJECT_ROOT_PATH)/build/android
include $(CA_LIB_PATH)/jni/Android.mk
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
APP_PLATFORM = android-19
APP_CPPFLAGS += -fexceptions
APP_CPPFLAGS += -frtti
-APP_CFLAGS = -Wno-error=format-security
\ No newline at end of file
+APP_CFLAGS = -Wno-error=format-security
#include <stdlib.h>
#include <string.h>
-#include <../../../../api/cainterface.h>
-#include <../../../../api/cacommon.h>
+#include "cainterface.h"
+#include "cacommon.h"
#include "com_iotivity_service_RMInterface.h"
#define LOG_TAG "JNI_INTERFACE_SAMPLE"
*/
#define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
-int gReceived;
-CABool_t gLocalUnicastPort;
-CABool_t gLocalSecurePort;
+#define PORT_LENGTH 5
+#define SECURE_DEFAULT_PORT 5684
+
+int g_received = 0;
+uint16_t g_localSecurePort = SECURE_DEFAULT_PORT;
void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo);
void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo);
-void send_response(const CARemoteEndpoint_t* endpoint, CAToken_t request_token);
-void get_resource_uri(char *URI, char *resourceURI, int length);
+void get_resource_uri(const char *URI, char *resourceURI, int length);
int get_secure_information(CAPayload_t payLoad);
CAResult_t get_network_type(int selectedNetwork);
void callback(char *subject, char *receivedData);
-CAConnectivityType_t gSelectedNwType;
-static CAToken_t gLastRequestToken = NULL;
-static const char *gSecureInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+CAConnectivityType_t g_selectedNwType = CA_WIFI;
+static CAToken_t g_lastRequestToken = NULL;
+static const char SECURE_COAPS_PREFIX[] = "coaps://";
+static const char SECURE_INFO_DATA[]
+ = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
"\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
-static const char *gNormalInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+static const char NORMAL_INFO_DATA[]
+ = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
"\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
-static jobject gResponseListenerObject = NULL;
+static jobject g_responseListenerObject = NULL;
extern JavaVM *g_jvm;
-static CARemoteEndpoint_t* clientEndpoint =NULL;
-static CAToken_t clientToken;
-
// init
-JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_setNativeResponseListener(JNIEnv *env, jobject obj, jobject listener){
+JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_setNativeResponseListener
+ (JNIEnv *env, jobject obj, jobject listener){
LOGI("setNativeResponseListener");
- gResponseListenerObject = (*env)->NewGlobalRef(env, obj);
+ g_responseListenerObject = (*env)->NewGlobalRef(env, obj);
}
#ifdef __WITH_DTLS__
void clearDtlsCredentialInfo()
{
- printf("clearDtlsCredentialInfo IN\n");
+ LOGI("clearDtlsCredentialInfo IN\n");
if (pskCredsBlob)
{
// Initialize sensitive data to zeroes before freeing.
- memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCredsBlob)*(pskCredsBlob->num));
- free(pskCredsBlob->creds);
+ if (pskCredsBlob->creds != NULL)
+ {
+ memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCredsBlob)*(pskCredsBlob->num));
+ free(pskCredsBlob->creds);
+ }
memset(pskCredsBlob, 0, sizeof(OCDtlsPskCredsBlob));
free(pskCredsBlob);
pskCredsBlob = NULL;
}
- printf("clearDtlsCredentialInfo OUT\n");
+ LOGI("clearDtlsCredentialInfo OUT\n");
}
// Internal API. Invoked by OC stack to retrieve credentials from this module
void CAGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo)
{
- printf("CAGetDtlsPskCredentials IN\n");
+ LOGI("CAGetDtlsPskCredentials IN\n");
*credInfo = pskCredsBlob;
- printf("CAGetDtlsPskCredentials OUT\n");
+ LOGI("CAGetDtlsPskCredentials OUT\n");
}
int32_t SetCredentials()
{
- printf("SetCredentials IN\n");
- pskCredsBlob = (OCDtlsPskCredsBlob *)malloc(sizeof(OCDtlsPskCredsBlob));
-
- memset(pskCredsBlob, 0x0, sizeof(OCDtlsPskCredsBlob));
+ LOGI("SetCredentials IN\n");
+ pskCredsBlob = (OCDtlsPskCredsBlob *)calloc(1, sizeof(OCDtlsPskCredsBlob));
+ if (NULL == pskCredsBlob)
+ {
+ LOGI("Memory allocation failed!\n");
+ return -1;
+ }
memcpy(pskCredsBlob->rsIdentity, IDENTITY, DTLS_PSK_ID_LEN);
pskCredsBlob->num = 1;
- pskCredsBlob->creds = (OCDtlsPskCredsBlob *)malloc(sizeof(OCDtlsPskCredsBlob) *(pskCredsBlob->num));
-
- memcpy(pskCredsBlob->creds[0].clientIdentity, IDENTITY, DTLS_PSK_ID_LEN);
- memcpy(pskCredsBlob->creds[0].rsClientPsk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
-
- printf("SetCredentials OUT\n");
- return 1;
-}
-#endif
-
-JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
-{
- printf("JNI_OnLoad");
-
- JNIEnv* env;
- if((*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6) != JNI_OK)
+ pskCredsBlob->creds = (OCDtlsPskCredsBlob *)malloc(sizeof(OCDtlsPskCredsBlob) *
+ (pskCredsBlob->num));
+ if (NULL == pskCredsBlob->creds)
{
+ LOGI("Memory allocation failed!\n");
return -1;
}
- g_jvm = jvm; /* cache the JavaVM pointer */
-
- CANativeJNISetJavaVM(g_jvm);
- return JNI_VERSION_1_6;
-}
-
-void JNI_OnUnload(JavaVM *jvm, void *reserved)
-{
- printf("JNI_OnUnload");
-
- JNIEnv* env;
- if((*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6) != JNI_OK)
+ uint32_t i;
+ for (i = 0; i < pskCredsBlob->num; i++)
{
- return;
+ memcpy(pskCredsBlob->creds[i].id, IDENTITY, DTLS_PSK_ID_LEN);
+ memcpy(pskCredsBlob->creds[i].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
}
- g_jvm = 0;
- return;
+ LOGI("SetCredentials OUT\n");
+ return 1;
}
+#endif
JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMInitialize
(JNIEnv *env, jobject obj, jobject context)
{
LOGI("RMInitialize");
-
- //Currently set context for Android Platform
- CANativeJNISetContext(env, context);
+ //Currently set context for WiFiCore
+ CAJniSetContext(context);
+ CALEServerJNISetContext(env, context);
+ CALEClientJNISetContext(env, context);
+ CALENetworkMonitorJNISetContext(env, context);
CAResult_t res;
#ifdef __WITH_DTLS__
- if (SetCredentials() == 0)
+ if (SetCredentials() != 1)
{
- printf("SetCredentials failed\n");
+ LOGI("SetCredentials failed\n");
+ return;
}
res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
if(res != CA_STATUS_OK)
{
- printf("Set credential handler fail\n");
+ LOGI("Set credential handler fail\n");
+ return;
}
#endif
CARegisterHandler(request_handler, response_handler);
}
-JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMFindResource(JNIEnv *env, jobject obj,
- jstring uri)
+JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMFindResource(JNIEnv *env,
+ jobject obj, jstring uri)
{
const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
LOGI("RMFindResource - %s", strUri);
CAResult_t res = CAGenerateToken(&token);
if (res != CA_STATUS_OK)
{
- printf("token generate error!!\n");
+ LOGI("token generate error!!\n");
token = NULL;
+ return;
}
LOGI("generated token %s\n", (token != NULL) ? token : "");
else
{
LOGI("find resource to %s URI", strUri);
- gLastRequestToken = token;
+ g_lastRequestToken = token;
}
}
-JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendRequest(JNIEnv *env, jobject obj,
- jstring uri, jstring payload, jint selectedNetwork, jint isSecured, jint msgType)
+JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendRequest(JNIEnv *env,
+ jobject obj, jstring uri, jstring payload, jint selectedNetwork, jint isSecured,
+ jint msgType)
{
const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
LOGI("RMSendRequest - %s", strUri);
//create remote endpoint
CARemoteEndpoint_t* endpoint = NULL;
- if(CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t)strUri, gSelectedNwType, &endpoint))
+ if(CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t)strUri, g_selectedNwType, &endpoint))
{
LOGI("Could not create remote end point");
CADestroyRemoteEndpoint(endpoint);
res = CAGenerateToken(&token);
if (res != CA_STATUS_OK)
{
- printf("token generate error!!\n");
+ LOGI("token generate error!!\n");
token = NULL;
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ return;
}
char resourceURI[15] = {0};
get_resource_uri((const CAURI_t)strUri, resourceURI, 14);
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ CAInfo_t requestData = {0};
requestData.token = token;
const char* strPayload = (*env)->GetStringUTFChars(env, payload, NULL);
if (isSecured == 1)
{
- int length = strlen(gSecureInfoData) + strlen(resourceURI) + 1;
+ uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
requestData.payload = (CAPayload_t) malloc(length);
- sprintf(requestData.payload, gSecureInfoData, resourceURI, gLocalSecurePort);
+ if (NULL == requestData.payload)
+ {
+ LOGI("Memory allocation failed!\n");
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
+ snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
}
else
{
- int length = strlen(strPayload) + strlen(resourceURI) + 1;
+ uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
requestData.payload = (CAPayload_t) malloc(length);
- sprintf(requestData.payload, strPayload, resourceURI);
+ if (NULL == requestData.payload)
+ {
+ LOGI("Memory allocation failed!\n");
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
+ snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
}
requestData.type = messageType;
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ CARequestInfo_t requestInfo = {0};
requestInfo.method = CA_GET;
requestInfo.info = requestData;
}
// destroy token
- if (token != NULL)
- {
- CADestroyToken(token);
- }
+ CADestroyToken(token);
// destroy remote endpoint
- if (endpoint != NULL)
- {
- CADestroyRemoteEndpoint(endpoint);
- }
+ CADestroyRemoteEndpoint(endpoint);
}
JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendResponse(JNIEnv *env,
- jobject obj, jint selectedNetwork, jint isSecured, jint msgType, jint responseValue)
+ jobject obj, jstring uri, jstring payload, jint selectedNetwork, jint isSecured)
{
LOGI("RMSendResponse");
+ const char* strUri = (*env)->GetStringUTFChars(env, uri, NULL);
+ LOGI("RMSendResponse - %s", strUri);
+
CAResult_t res;
LOGI("selectedNetwork - %d", selectedNetwork);
res = get_network_type(selectedNetwork);
if (res != CA_STATUS_OK)
{
- LOGI("Not supported network type");
return;
}
- if (clientEndpoint == NULL)
+ //create remote endpoint
+ CARemoteEndpoint_t* endpoint = NULL;
+
+ if(CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t)strUri, g_selectedNwType, &endpoint))
{
- LOGI("No Request received");
+ LOGI("Could not create remote end point");
+ CADestroyRemoteEndpoint(endpoint);
return;
}
- CAMessageType_t messageType = msgType;
+ CAMessageType_t messageType = CA_MSG_ACKNOWLEDGE;
- CAInfo_t responseData;
- memset(&responseData, 0, sizeof(CAInfo_t));
- responseData.token = clientToken;
+ // create token
+ CAToken_t token = NULL;
+ res = CAGenerateToken(&token);
+ if (res != CA_STATUS_OK)
+ {
+ LOGI("token generate error!");
+ token = NULL;
+ }
+ char resourceURI[15] = {0};
+
+ get_resource_uri((const CAURI_t)strUri, resourceURI, 14);
+
+ CAInfo_t responseData = {0};
+ responseData.token = token;
+
+ const char* strPayload = (*env)->GetStringUTFChars(env, payload, NULL);
if (isSecured == 1)
{
- int length = strlen(gSecureInfoData) + strlen(clientEndpoint->resourceUri) + 1;
+ uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
responseData.payload = (CAPayload_t) malloc(length);
- sprintf(responseData.payload, gSecureInfoData, clientEndpoint->resourceUri, gLocalSecurePort);
+ if (NULL == responseData.payload)
+ {
+ LOGI("Memory allocation failed!\n");
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
+ snprintf(responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
}
else
{
- int length = strlen("sendResponse Payload") + strlen(clientEndpoint->resourceUri) + 1;
+ uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
responseData.payload = (CAPayload_t) malloc(length);
- sprintf(responseData.payload, gNormalInfoData, clientEndpoint->resourceUri);
+ if (NULL == responseData.payload)
+ {
+ LOGI("Memory allocation failed!\n");
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
+ snprintf(responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
}
responseData.type = messageType;
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = responseValue;
+ CAResponseInfo_t responseInfo = {0};
+ responseInfo.result = CA_SUCCESS;
responseInfo.info = responseData;
// send request
- if(CA_STATUS_OK != CASendResponse(clientEndpoint, &responseInfo))
+ if(CA_STATUS_OK != CASendResponse(endpoint, &responseInfo))
{
LOGI("Could not send response");
}
+ LOGI("Send response");
+
// destroy token
- if (clientToken != NULL)
- {
- CADestroyToken(clientToken);
- }
+ CADestroyToken(token);
// destroy remote endpoint
- if (clientEndpoint != NULL)
- {
- CADestroyRemoteEndpoint(clientEndpoint);
- }
-
+ CADestroyRemoteEndpoint(endpoint);
}
JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMAdvertiseResource(JNIEnv *env,
int optionNum = 2;
CAHeaderOption_t *headerOpt;
- headerOpt = (CAHeaderOption_t*) malloc(sizeof(CAHeaderOption_t) * optionNum);
+ headerOpt = (CAHeaderOption_t*) calloc(1, sizeof(CAHeaderOption_t) * optionNum);
if (NULL == headerOpt)
{
- printf("Memory allocation failed!\n");
+ LOGI("Memory allocation failed!\n");
return;
}
- memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
char* tmpOptionData1 = "Hello";
headerOpt[0].optionID = 3000;
if (res != CA_STATUS_OK)
{
LOGI("token generate error!");
- token = NULL;
+ free(headerOpt);
+ return;
}
CAAdvertiseResource((const CAURI_t)strUri, token, headerOpt, (uint8_t) optionNum);
//create remote endpoint
CARemoteEndpoint_t* endpoint = NULL;
- if(CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t)strUri, gSelectedNwType, &endpoint))
+ if(CA_STATUS_OK != CACreateRemoteEndpoint((const CAURI_t)strUri, g_selectedNwType, &endpoint))
{
LOGI("Could not create remote end point");
CADestroyRemoteEndpoint(endpoint);
get_resource_uri((const CAURI_t)strUri, resourceURI, 14);
- CAInfo_t responseData;
- memset(&responseData, 0, sizeof(CAInfo_t));
+ CAInfo_t responseData = {0};
responseData.token = token;
const char* strPayload = (*env)->GetStringUTFChars(env, payload, NULL);
if (isSecured == 1)
{
- int length = strlen(gSecureInfoData) + strlen(resourceURI) + 1;
+ uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
responseData.payload = (CAPayload_t) malloc(length);
- sprintf(responseData.payload, gSecureInfoData, resourceURI, gLocalSecurePort);
+ if (NULL == responseData.payload)
+ {
+ LOGI("Memory allocation failed!\n");
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
+ snprintf(responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
}
else
{
- int length = strlen(strPayload) + strlen(resourceURI) + 1;
+ uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
responseData.payload = (CAPayload_t) malloc(length);
- sprintf(responseData.payload, strPayload, resourceURI);
+ if (NULL == responseData.payload)
+ {
+ LOGI("Memory allocation failed!\n");
+ // destroy token
+ CADestroyToken(token);
+ // destroy remote endpoint
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
+ snprintf(responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
}
responseData.type = messageType;
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ CAResponseInfo_t responseInfo = {0};
responseInfo.result = CA_SUCCESS;
responseInfo.info = responseData;
LOGI("Send Notification");
// destroy token
- if (token != NULL)
- {
- CADestroyToken(token);
- }
+ CADestroyToken(token);
// destroy remote endpoint
- if (endpoint != NULL)
- {
- CADestroyRemoteEndpoint(endpoint);
- }
+ CADestroyRemoteEndpoint(endpoint);
}
JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSelectNetwork(JNIEnv *env, jobject obj,
void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo)
{
-
- char *cloneUri = NULL;
- char *cloneRemoteAddress = NULL;
- char *clonePayload = NULL;
- char *cloneOptionData = NULL;
- uint32_t len = 0;
-
if (!object)
{
LOGI("Remote endpoint is NULL!");
LOGI("##########received request from remote device #############\n");
LOGI("Uri: %s\n", object->resourceUri);
LOGI("Remote Address: %s\n", object->addressInfo.IP.ipAddress);
+
LOGI("Data: %s\n", requestInfo->info.payload);
- LOGI("Token: %s\n", requestInfo->info.token);
- LOGI("Code: %d\n", requestInfo->method);
- if (NULL != gResponseListenerObject)
+ if (NULL != g_responseListenerObject)
{
callback("received request from remote device", "#######");
+ callback("Uri: ", object->resourceUri);
- if (object->resourceUri != NULL)
- {
- len = strlen(object->resourceUri);
- cloneUri = (char *) OICMalloc(sizeof(char) * (len + 1));
+ callback("Remote Address: ", (char *) object->addressInfo.IP.ipAddress);
- if (cloneUri == NULL)
- {
- LOGI("CACloneRemoteEndpoint Out of memory");
- return;
- }
-
- memset(cloneUri, 0, sizeof(char) * (len + 1));
- strncpy(cloneUri, object->resourceUri, len);
-
- callback("Uri: ", cloneUri);
- free(cloneUri);
- }
-
- len = strlen(object->addressInfo.IP.ipAddress);
- cloneRemoteAddress = (char *) OICMalloc(sizeof(char) * (len + 1));
-
- if (cloneRemoteAddress == NULL)
+ if(requestInfo->info.payload)
{
- LOGI("CACloneRemoteEndpoint Out of memory");
- return;
- }
-
- memset(cloneRemoteAddress, 0, sizeof(char) * (len + 1));
- strncpy(cloneRemoteAddress, object->addressInfo.IP.ipAddress, len);
-
- callback("Remote Address: ", cloneRemoteAddress);
- free(cloneRemoteAddress);
-
-
- if(requestInfo->info.payload != NULL)
- {
- len = strlen(requestInfo->info.payload);
- clonePayload = (char *) OICMalloc(sizeof(char) * (len + 1));
-
- if (clonePayload == NULL)
- {
- LOGI("CACloneRemoteEndpoint Out of memory");
- return;
- }
-
- memset(clonePayload, 0, sizeof(char) * (len + 1));
- strncpy(clonePayload, requestInfo->info.payload, len);
-
- callback("Data: ", clonePayload);
- free(clonePayload);
+ callback("Data: ", requestInfo->info.payload);
}
}
- if (gLastRequestToken != NULL && requestInfo->info.token != NULL
- && (strcmp((char *)gLastRequestToken, requestInfo->info.token) == 0))
+ if (g_lastRequestToken != NULL && requestInfo->info.token != NULL
+ && (strcmp((char *)g_lastRequestToken, requestInfo->info.token) == 0))
{
LOGI("token is same. received request of it's own. skip.. \n");
return;
{
uint32_t len = requestInfo->info.numOptions;
uint32_t i;
-
- LOGI("Option count: %d\n", requestInfo->info.numOptions);
-
for (i = 0; i < len; i++)
{
LOGI("Option %d\n", i + 1);
LOGI("Data[%d]: %s\n", requestInfo->info.options[i].optionLength,
requestInfo->info.options[i].optionData);
- if (NULL != gResponseListenerObject)
+ if (NULL != g_responseListenerObject)
{
- char optionInfo[1024] = {0,};
- sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i+1,
- requestInfo->info.options[i].optionID, requestInfo->info.options[i].optionLength);
-
- callback("Option info: ", optionInfo);
-
- if (requestInfo->info.options[i].optionData != NULL)
- {
- uint32_t optionDataLen = strlen(requestInfo->info.options[i].optionData);
- cloneOptionData = (char *) OICMalloc(sizeof(char) * (optionDataLen + 1));
-
- if (cloneOptionData == NULL)
- {
- LOGI("CACloneRemoteEndpoint Out of memory");
- return;
- }
+ char tmpbuf[30];
+ sprintf(tmpbuf, "%d", i + 1);
+ callback("Option: ", tmpbuf);
- memset(cloneOptionData, 0, sizeof(char) * (optionDataLen + 1));
- strncpy(cloneOptionData, requestInfo->info.options[i].optionData, optionDataLen);
+ sprintf(tmpbuf, "%d", requestInfo->info.options[i].optionID);
+ callback("ID: ", tmpbuf);
- callback("Option Data: ", cloneOptionData);
- free(cloneOptionData);
- }
+ sprintf(tmpbuf, "Data:[%d]", requestInfo->info.options[i].optionLength);
+ callback("tmpbuf: ", requestInfo->info.options[i].optionData);
}
}
}
-
- printf("############################################################\n");
+ LOGI("############################################################\n");
//Check if this has secure communication information
- if (requestInfo->info.payload && object->resourceUri)
+ if (requestInfo->info.payload)
{
int securePort = get_secure_information(requestInfo->info.payload);
if (0 < securePort) //Set the remote endpoint secure details and send response
{
LOGI("This is secure resource...\n");
char *uri = NULL;
- int length = 0;
+ uint32_t length = 0;
- length = 8; //length of "coaps://"
- length += strlen(object->addressInfo.IP.ipAddress) + 5; // length of "ipaddress:port"
+ length = sizeof(SECURE_COAPS_PREFIX) - 1; //length of "coaps://"
+ length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH; // length of "ipaddress:port"
length += strlen(object->resourceUri) + 1;
uri = calloc(1,sizeof(char)*length);
if (!uri)
{
- printf("Failed to create new uri\n");
+ LOGI("Failed to create new uri\n");
return;
}
- sprintf(uri,"coaps://%s:%d/%s",object->addressInfo.IP.ipAddress,
+ sprintf(uri,"%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
securePort, object->resourceUri);
CARemoteEndpoint_t *endpoint = NULL;
LOGI("Failed to create duplicate of remote endpoint!\n");
return;
}
- endpoint->isSecured = CA_TRUE;
+ endpoint->isSecured = true;
object = endpoint;
}
}
- gReceived = 1;
+ g_received = 1;
- clientEndpoint = object;
- clientToken = requestInfo->info.token;
}
void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo)
{
- char *cloneUri = NULL;
- char *cloneRemoteAddress = NULL;
- char *clonePayload = NULL;
- char *cloneOptionData = NULL;
- uint32_t len = 0;
-
LOGI("##########Received response from remote device #############\n");
LOGI("Uri: %s\n", object->resourceUri);
- LOGI("Remote Address: %s\n", object->addressInfo.IP.ipAddress);
- LOGI("response result: %d\n", responseInfo->result);
- LOGI("Data: %s\n", responseInfo->info.payload);
- LOGI("Token: %s\n", responseInfo->info.token);
- LOGI("Code: %d\n", responseInfo->result);
- if (NULL != gResponseListenerObject)
+ if(object->connectivityType == CA_EDR)
{
- if (object->resourceUri != NULL)
- {
- len = strlen(object->resourceUri);
- cloneUri = (char *) OICMalloc(sizeof(char) * (len + 1));
-
- if (cloneUri == NULL)
- {
- LOGI("CACloneRemoteEndpoint Out of memory");
- return;
- }
-
- memset(cloneUri, 0, sizeof(char) * (len + 1));
- strncpy(cloneUri, object->resourceUri, len);
+ LOGI("Remote Address: %s\n", object->addressInfo.BT.btMacAddress);
+ } else if(object->connectivityType == CA_LE)
+ {
+ LOGI("Remote Address: %s\n", object->addressInfo.LE.leMacAddress);
+ } else if(object->connectivityType == CA_WIFI)
+ {
+ LOGI("Remote Address: %s\n", object->addressInfo.IP.ipAddress);
+ }
- callback("Uri: ", cloneUri);
- free(cloneUri);
- }
+ LOGI("response result: %d\n", responseInfo->result);
+ LOGI("Data: %s\n", responseInfo->info.payload);
- len = strlen(object->addressInfo.IP.ipAddress);
- cloneRemoteAddress = (char *) OICMalloc(sizeof(char) * (len + 1));
+ if (NULL != g_responseListenerObject)
+ {
+ callback("received response from remote device", "#######");
+ callback("Uri: ", object->resourceUri);
- if (cloneRemoteAddress == NULL)
+ if(object->connectivityType == CA_EDR)
{
- LOGI("CACloneRemoteEndpoint Out of memory");
- return;
+ callback("Remote Address: ", (char*) object->addressInfo.BT.btMacAddress);
+ } else if(object->connectivityType == CA_LE)
+ {
+ callback("Remote Address: ", (char*) object->addressInfo.LE.leMacAddress);
+ } else if(object->connectivityType == CA_WIFI)
+ {
+ callback("Remote Address: ", (char*) object->addressInfo.IP.ipAddress);
}
- memset(cloneRemoteAddress, 0, sizeof(char) * (len + 1));
- strncpy(cloneRemoteAddress, object->addressInfo.IP.ipAddress, len);
-
- callback("Remote Address: ", cloneRemoteAddress);
- free(cloneRemoteAddress);
-
-
- if(responseInfo->info.payload != NULL)
+ if(responseInfo->info.payload)
{
- len = strlen(responseInfo->info.payload);
- clonePayload = (char *) OICMalloc(sizeof(char) * (len + 1));
-
- if (clonePayload == NULL)
- {
- LOGI("CACloneRemoteEndpoint Out of memory");
- return;
- }
-
- memset(clonePayload, 0, sizeof(char) * (len + 1));
- strncpy(clonePayload, responseInfo->info.payload, len);
-
- callback("Data: ", clonePayload);
- free(clonePayload);
+ callback("Data: ", responseInfo->info.payload);
}
}
LOGI("Data[%d]: %s\n", responseInfo->info.options[i].optionLength,
responseInfo->info.options[i].optionData);
- if (NULL != gResponseListenerObject)
+ if (NULL != g_responseListenerObject)
{
- char optionInfo[1024] = {0,};
- sprintf(optionInfo, "Num[%d] - ID : %d, Option Length : %d", i+1,
- responseInfo->info.options[i].optionID,
- responseInfo->info.options[i].optionLength);
-
- callback("Option info: ", optionInfo);
-
- if (responseInfo->info.options[i].optionData != NULL)
- {
- uint32_t optionDataLen = strlen(responseInfo->info.options[i].optionData);
- cloneOptionData = (char *) OICMalloc(sizeof(char) * (optionDataLen + 1));
-
- if (cloneOptionData == NULL)
- {
- LOGI("CACloneRemoteEndpoint Out of memory");
- return;
- }
- memset(cloneOptionData, 0, sizeof(char) * (optionDataLen + 1));
- strncpy(cloneOptionData, responseInfo->info.options[i].optionData, optionDataLen);
- callback("Option Data: ", cloneOptionData);
- free(cloneOptionData);
- }
+ char tmpbuf[30];
+ sprintf(tmpbuf, "%d", i + 1);
+ callback("Option: ", tmpbuf);
+
+ sprintf(tmpbuf, "%d", responseInfo->info.options[i].optionID);
+ callback("ID: ", tmpbuf);
+
+ sprintf(tmpbuf, "Data:[%d]", responseInfo->info.options[i].optionLength);
+ callback("tmpbuf: ", responseInfo->info.options[i].optionData);
}
}
}
LOGI("############################################################\n");
- gReceived = 1;
+ g_received = 1;
//Check if this has secure communication information
if (responseInfo->info.payload)
}
}
-void get_resource_uri(char *URI, char *resourceURI, int length)
+void get_resource_uri(const char *URI, char *resourceURI, int length)
{
- char *startPos = URI;
- char *temp = NULL;
+ const char *startPos = URI;
+ const char *temp = NULL;
if (NULL != (temp = strstr(URI, "://")))
{
startPos = strchr(temp + 3, '/');
if (!startPos)
{
- printf("Resource URI is missing\n");
+ LOGI("Resource URI is missing\n");
return;
}
}
- char *endPos = strchr(startPos, '?');
+ const char *endPos = strchr(startPos, '?');
if (!endPos)
{
endPos = URI + strlen(URI);
}
- endPos -= 1;
+ --endPos;
if (endPos - startPos <= length)
memcpy(resourceURI, startPos + 1, endPos - startPos);
- printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
+ LOGI("URI: %s, ResourceURI:%s\n", URI, resourceURI);
}
int get_secure_information(CAPayload_t payLoad)
{
- printf("entering get_secure_information\n");
+ LOGI("entering get_secure_information\n");
if (!payLoad)
{
- printf("Payload is NULL\n");
+ LOGI("Payload is NULL\n");
return -1;
}
- char *subString = NULL;
+ const char *subString = NULL;
if (NULL == (subString = strstr(payLoad, "\"sec\":1")))
{
- printf("This is not secure resource\n");
+ LOGI("This is not secure resource\n");
return -1;
}
if (NULL == (subString = strstr(payLoad, "\"port\":")))
{
- printf("This secure resource does not have port information\n");
+ LOGI("This secure resource does not have port information\n");
return -1;
}
- char *startPos = strstr(subString, ":");
+ const char *startPos = strstr(subString, ":");
if (!startPos)
{
- printf("Parsing failed !\n");
+ LOGI("Parsing failed !\n");
return -1;
}
- char *endPos = strstr(startPos, "}");
+ const char *endPos = strstr(startPos, "}");
if (!endPos)
{
- printf("Parsing failed !\n");
+ LOGI("Parsing failed !\n");
return -1;
}
- char portStr[4] = {0};
+ char portStr[6] = {0};
memcpy(portStr, startPos + 1, (endPos-1) - startPos);
- printf("secured port is: %s\n", portStr);
+ LOGI("secured port is: %s\n", portStr);
return atoi(portStr);
}
}
if (number & CA_ETHERNET)
{
- gSelectedNwType = CA_ETHERNET;
+ g_selectedNwType = CA_ETHERNET;
return CA_STATUS_OK;
}
if (number & CA_WIFI)
{
- gSelectedNwType = CA_WIFI;
+ g_selectedNwType = CA_WIFI;
return CA_STATUS_OK;
}
if (number & CA_EDR)
{
- gSelectedNwType = CA_EDR;
+ g_selectedNwType = CA_EDR;
return CA_STATUS_OK;
}
if (number & CA_LE)
{
- gSelectedNwType = CA_LE;
+ g_selectedNwType = CA_LE;
return CA_STATUS_OK;
}
return CA_NOT_SUPPORTED;
}
-void callback(char *subject, char *receivedData)
+void callback(char *subject, char *receicedData)
{
JNIEnv* env = NULL;
int status = (*g_jvm)->GetEnv(g_jvm, (void **) &env, JNI_VERSION_1_6);
int res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- jclass cls = (*env)->GetObjectClass(env, gResponseListenerObject);
- jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived", "(Ljava/lang/String;Ljava/lang/String;)V");
+ jclass cls = (*env)->GetObjectClass(env, g_responseListenerObject);
+ jmethodID mid = (*env)->GetMethodID(env, cls, "OnResponseReceived",
+ "(Ljava/lang/String;Ljava/lang/String;)V");
jstring jsubject = (*env)->NewStringUTF(env, (char*)subject);
- jstring jreceivedData = (*env)->NewStringUTF(env, (char*)receivedData);
- (*env)->CallVoidMethod(env, gResponseListenerObject, mid, jsubject, jreceivedData);
-
+ jstring jreceivedData = (*env)->NewStringUTF(env, (char*)receicedData);
+ (*env)->CallVoidMethod(env, g_responseListenerObject, mid, jsubject, jreceivedData);
}
-/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_iotivity_service_RMInterface */
#ifdef __cplusplus
extern "C" {
#endif
+JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_setNativeResponseListener
+ (JNIEnv *, jobject, jobject);
/*
* Class: com_iotivity_service_RMInterface
* Method: RMInitialize
- * Signature: (Landroid/content/Context;)I
+ * Signature: (Landroid/content/Context;)V
*/
-JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_setNativeResponseListener
- (JNIEnv *, jobject, jobject);
-
JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMInitialize
(JNIEnv *, jobject, jobject);
/*
* Class: com_iotivity_service_RMInterface
* Method: RMSendResponse
- * Signature: (IIII)V
+ * Signature: (Ljava/lang/String;III)V
*/
JNIEXPORT void JNICALL Java_com_iotivity_service_RMInterface_RMSendResponse
- (JNIEnv *, jobject, jint, jint, jint, jint);
+ (JNIEnv *, jobject, jstring, jstring, jint, jint);
/*
* Class: com_iotivity_service_RMInterface
}
#endif
#endif
+
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
+
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.iotivity.service.MainActivity" >
-
+
<RelativeLayout
android:id="@+id/sample_service_layout"
android:layout_width="fill_parent"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
-
+
<RelativeLayout
android:id="@+id/layout_network"
android:layout_width="fill_parent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_mode" >
-
+
<TextView
android:id="@+id/tv_find"
android:layout_width="fill_parent"
- android:layout_height="wrap_content"
+ android:layout_height="wrap_content"
android:text="[Find Resource]"
/>
-
- </RelativeLayout>
-
+
+ </RelativeLayout>
+
<RelativeLayout
android:id="@+id/layout_find"
android:layout_width="fill_parent"
android:layout_toLeftOf="@id/btn_find_resource"
android:text="@string/uri" />
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_Response_Noti_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_mode" >
-
+
<TextView
android:id="@+id/tv_Response_Noti"
android:layout_width="fill_parent"
- android:layout_height="wrap_content"
+ android:layout_height="wrap_content"
android:text="[Send Response / Send Notification]"
/>
-
+
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_request_setting_for_server"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_Response_Noti_title" >
-
+
<Button
android:id="@+id/btn_Request_setting_for_server"
android:layout_width="fill_parent"
android:layout_alignParentRight="true"
android:text="@string/request_setting" />
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_notify"
android:layout_width="fill_parent"
android:layout_alignParentRight="true"
android:text="@string/notification" />
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_payload_server_ed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_notify" >
-
+
<EditText
android:id="@+id/et_payload_data_for_server"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="@string/payload_data_server" />
-
+
</RelativeLayout>
<RelativeLayout
android:layout_height="wrap_content"
android:layout_below="@id/layout_payload_server_ed" >
-
<Button
android:id="@+id/btn_notify"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="@string/notify" />
-
+
<Button
android:id="@+id/btn_sendresponse"
android:layout_width="fill_parent"
android:layout_toLeftOf="@id/btn_notify"
android:text="@string/sendresponse" />
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_advertise_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_server_bt" >
-
+
<TextView
android:id="@+id/tv_advertise"
android:layout_width="fill_parent"
- android:layout_height="wrap_content"
+ android:layout_height="wrap_content"
android:text="[Advertise Resource]"
/>
-
- </RelativeLayout>
-
+
+ </RelativeLayout>
+
<RelativeLayout
android:id="@+id/layout_advertise_resource"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="@string/advertise" />
-
+
<EditText
android:id="@+id/et_uri_advertise"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/btn_advertise"
- android:text="@string/uri" />
+ android:text="@string/uri" />
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_request_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_find" >
-
+
<TextView
android:id="@+id/tv_request"
android:layout_width="fill_parent"
- android:layout_height="wrap_content"
+ android:layout_height="wrap_content"
android:text="[Send Request]"
/>
-
- </RelativeLayout>
-
+
+ </RelativeLayout>
+
<RelativeLayout
android:id="@+id/layout_request_setting_for_client"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_request_title" >
-
+
<Button
android:id="@+id/btn_Request_setting_for_client"
android:layout_width="fill_parent"
android:layout_alignParentRight="true"
android:text="@string/request_setting" />
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_request"
android:layout_width="fill_parent"
android:layout_toLeftOf="@id/btn_Request"
android:text="@string/req_data" />
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_payload_client_ed"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_request" >
-
+
<EditText
android:id="@+id/et_payload_data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="@string/payload_data_client" />
-
+
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/layout_advertise_resource" >
-
+
<TextView
android:id="@+id/tv_handle"
android:layout_width="fill_parent"
- android:layout_height="wrap_content"
+ android:layout_height="wrap_content"
android:text="[Handle Reqeust/Response data]"
/>
-
- </RelativeLayout>
-
+
+ </RelativeLayout>
+
<RelativeLayout
android:id="@+id/layout_receive"
android:layout_width="fill_parent"
android:layout_alignParentRight="true"
android:text="@string/receive" />
</RelativeLayout>
-
+
<RelativeLayout
android:id="@+id/layout_received"
android:layout_width="fill_parent"
android:text="@string/received" />
</RelativeLayout>
</RelativeLayout>
-
+
<ScrollView
android:id="@+id/sv_result_scoll"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
-</RelativeLayout>
\ No newline at end of file
+</RelativeLayout>
android:title="@string/action_settings"/>
</menu>
+
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>
+
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
+
<string name="request">Request</string>
<string name="response">Response</string>
<string name="uri">/a/light</string>
- <string name="notification">coap://D8:07:62:33:CE:11/a/bulb</string>
- <string name="req_data">coap://FC:88:0D:47:0C:0F/b/light</string>
+ <string name="notification"></string>
+ <string name="req_data"></string>
<string name="resp_data">resourceUri/response</string>
<string name="receive">Receive</string>
<string name="received">Received Message</string>
<string name="action_settings">Settings</string>
<string name="payload_data_client">PayloadData</string>
<string name="payload_data_server">PayloadData</string>
-
</resources>
\ No newline at end of file
-
package com.iotivity.jar;
import android.bluetooth.BluetoothAdapter;
import android.util.Log;
public class CALeInterface {
-
+
public CALeInterface(Context context) {
-
+
CARegisterLeScanCallback(mLeScanCallback);
CARegisterLeGattCallback(mGattCallback);
CARegisterLeGattServerCallback(mGattServerCallback);
CARegisterBluetoothLeAdvertiseCallback(mAdvertiseCallback);
-
+
registerIntentFilter(context);
}
-
+
public static void getLeScanCallback() {
CARegisterLeScanCallback(mLeScanCallback);
}
-
+
public static void getLeGattCallback() {
CARegisterLeGattCallback(mGattCallback);
}
-
+
public static void getLeGattServerCallback() {
CARegisterLeGattServerCallback(mGattServerCallback);
}
-
+
public static void getBluetoothLeAdvertiseCallback() {
CARegisterBluetoothLeAdvertiseCallback(mAdvertiseCallback);
}
-
+
public static IntentFilter registerIntentFilter(Context context) {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
context.registerReceiver(mReceiver, filter);
return filter;
}
-
- public native static void CARegisterLeScanCallback(BluetoothAdapter.LeScanCallback callback);
-
- public native static void CARegisterLeGattCallback(BluetoothGattCallback callback);
-
- public native static void CARegisterLeGattServerCallback(BluetoothGattServerCallback callback);
-
- public native static void CARegisterBluetoothLeAdvertiseCallback(AdvertiseCallback callback);
-
+
+ public native static void CARegisterLeScanCallback(
+ BluetoothAdapter.LeScanCallback callback);
+
+ public native static void CARegisterLeGattCallback(
+ BluetoothGattCallback callback);
+
+ public native static void CARegisterLeGattServerCallback(
+ BluetoothGattServerCallback callback);
+
+ public native static void CARegisterBluetoothLeAdvertiseCallback(
+ AdvertiseCallback callback);
+
// BluetoothAdapter.LeScanCallback
- public native static void CALeScanCallback(BluetoothDevice device, int rssi, byte[] scanRecord);
-
+ public native static void CALeScanCallback(BluetoothDevice device,
+ int rssi, byte[] scanRecord);
+
// BluetoothGattCallback
- public native static void CALeGattConnectionStateChangeCallback(BluetoothGatt gatt, int status, int newState);
-
- public native static void CALeGattServicesDiscoveredCallback(BluetoothGatt gatt, int status);
-
- public native static void CALeGattCharacteristicReadCallback(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] data, int status);
-
- public native static void CALeGattCharacteristicWriteCallback(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] data, int status);
-
- public native static void CALeGattCharacteristicChangedCallback(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, byte[] data);
-
- public native static void CALeGattDescriptorReadCallback(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status);
-
- public native static void CALeGattDescriptorWriteCallback(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status);
-
- public native static void CALeGattReliableWriteCompletedCallback(BluetoothGatt gatt, int status);
-
- public native static void CALeGattReadRemoteRssiCallback(BluetoothGatt gatt, int rssi, int status);
-
+ public native static void CALeGattConnectionStateChangeCallback(
+ BluetoothGatt gatt, int status, int newState);
+
+ public native static void CALeGattServicesDiscoveredCallback(
+ BluetoothGatt gatt, int status);
+
+ public native static void CALeGattCharacteristicReadCallback(
+ BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
+ byte[] data, int status);
+
+ public native static void CALeGattCharacteristicWriteCallback(
+ BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
+ byte[] data, int status);
+
+ public native static void CALeGattCharacteristicChangedCallback(
+ BluetoothGatt gatt, BluetoothGattCharacteristic characteristic,
+ byte[] data);
+
+ public native static void CALeGattDescriptorReadCallback(
+ BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status);
+
+ public native static void CALeGattDescriptorWriteCallback(
+ BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status);
+
+ public native static void CALeGattReliableWriteCompletedCallback(
+ BluetoothGatt gatt, int status);
+
+ public native static void CALeGattReadRemoteRssiCallback(
+ BluetoothGatt gatt, int rssi, int status);
+
// BluetoothGattServerCallback
- public native static void CALeGattServerConnectionStateChangeCallback(BluetoothDevice device, int status, int newState);
-
- public native static void CALeGattServerServiceAddedCallback(int status, BluetoothGattService service);
-
- public native static void CALeGattServerCharacteristicReadRequestCallback(BluetoothDevice device,
- int requestId, int offset, BluetoothGattCharacteristic characteristic, byte[] data);
-
- public native static void CALeGattServerCharacteristicWriteRequestCallback(BluetoothDevice device, int requestId,
- BluetoothGattCharacteristic characteristic, byte[] data, boolean preparedWrite,
+ public native static void CALeGattServerConnectionStateChangeCallback(
+ BluetoothDevice device, int status, int newState);
+
+ public native static void CALeGattServerServiceAddedCallback(int status,
+ BluetoothGattService service);
+
+ public native static void CALeGattServerCharacteristicReadRequestCallback(
+ BluetoothDevice device, int requestId, int offset,
+ BluetoothGattCharacteristic characteristic, byte[] data);
+
+ public native static void CALeGattServerCharacteristicWriteRequestCallback(
+ BluetoothDevice device, int requestId,
+ BluetoothGattCharacteristic characteristic, byte[] data,
+ boolean preparedWrite, boolean responseNeeded, int offset,
+ byte[] value);
+
+ public native static void CALeGattServerDescriptorReadRequestCallback(
+ BluetoothDevice device, int requestId, int offset,
+ BluetoothGattDescriptor descriptor);
+
+ public native static void CALeGattServerDescriptorWriteRequestCallback(
+ BluetoothDevice device, int requestId,
+ BluetoothGattDescriptor descriptor, boolean preparedWrite,
boolean responseNeeded, int offset, byte[] value);
-
- public native static void CALeGattServerDescriptorReadRequestCallback(BluetoothDevice device,
- int requestId, int offset, BluetoothGattDescriptor descriptor);
-
- public native static void CALeGattServerDescriptorWriteRequestCallback(BluetoothDevice device, int requestId,
- BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value);
-
- public native static void CALeGattServerExecuteWriteCallback(BluetoothDevice device, int requestId, boolean execute);
-
- public native static void CALeGattServerNotificationSentCallback(BluetoothDevice device, int status);
+
+ public native static void CALeGattServerExecuteWriteCallback(
+ BluetoothDevice device, int requestId, boolean execute);
+
+ public native static void CALeGattServerNotificationSentCallback(
+ BluetoothDevice device, int status);
// AdvertiseCallback
- public native static void CALeAdvertiseStartSuccessCallback(AdvertiseSettings settingsInEffect);
-
+ public native static void CALeAdvertiseStartSuccessCallback(
+ AdvertiseSettings settingsInEffect);
+
public native static void CALeAdvertiseStartFailureCallback(int errorCode);
-
+
// Network Monitor
- public native static void CALeStateChangedCallback(int state);
-
+ public native static void CALeStateChangedCallback(int state);
+
// Callback
- private static BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
-
+ private static BluetoothAdapter.LeScanCallback mLeScanCallback
+ = new BluetoothAdapter.LeScanCallback() {
+
@Override
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
-
+
try {
- CALeScanCallback(device, rssi, scanRecord);
+ CALeScanCallback(device, rssi, scanRecord);
} catch(UnsatisfiedLinkError e) {
-
+
}
}
};
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
-
+
CALeGattConnectionStateChangeCallback(gatt, status, newState);
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
-
+
CALeGattServicesDiscoveredCallback(gatt, status);
}
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
-
- CALeGattCharacteristicReadCallback(gatt, characteristic,
- characteristic.getValue(), status);
+
+ CALeGattCharacteristicReadCallback(gatt, characteristic,
+ characteristic.getValue(), status);
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
-
- CALeGattCharacteristicWriteCallback(gatt, characteristic,
- characteristic.getValue(), status);
+
+ CALeGattCharacteristicWriteCallback(gatt, characteristic,
+ characteristic.getValue(), status);
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
-
- CALeGattCharacteristicChangedCallback(gatt, characteristic,
- characteristic.getValue());
+
+ CALeGattCharacteristicChangedCallback(gatt, characteristic,
+ characteristic.getValue());
}
@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
int status) {
super.onDescriptorRead(gatt, descriptor, status);
-
+
CALeGattDescriptorReadCallback(gatt, descriptor, status);
}
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
int status) {
super.onDescriptorWrite(gatt, descriptor, status);
-
+
CALeGattDescriptorWriteCallback(gatt, descriptor, status);
}
@Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
super.onReliableWriteCompleted(gatt, status);
-
+
CALeGattReliableWriteCompletedCallback(gatt, status);
}
@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
-
+
CALeGattReadRemoteRssiCallback(gatt, rssi, status);
}
};
-
-
- private static final BluetoothGattServerCallback mGattServerCallback = new BluetoothGattServerCallback() {
+
+ private static final BluetoothGattServerCallback mGattServerCallback
+ = new BluetoothGattServerCallback() {
@Override
public void onConnectionStateChange(BluetoothDevice device, int status,
int newState) {
super.onConnectionStateChange(device, status, newState);
-
+
CALeGattServerConnectionStateChangeCallback(device, status, newState);
}
@Override
public void onServiceAdded(int status, BluetoothGattService service) {
super.onServiceAdded(status, service);
-
+
CALeGattServerServiceAddedCallback(status, service);
}
int requestId, int offset,
BluetoothGattCharacteristic characteristic) {
super.onCharacteristicReadRequest(device, requestId, offset, characteristic);
-
- CALeGattServerCharacteristicReadRequestCallback(device, requestId, offset, characteristic, characteristic.getValue());
+
+ CALeGattServerCharacteristicReadRequestCallback(device, requestId, offset,
+ characteristic, characteristic.getValue());
}
@Override
byte[] value) {
super.onCharacteristicWriteRequest(device, requestId, characteristic,
preparedWrite, responseNeeded, offset, value);
-
+
CALeGattServerCharacteristicWriteRequestCallback(device, requestId, characteristic,
value, preparedWrite, responseNeeded, offset, value);
}
public void onDescriptorReadRequest(BluetoothDevice device,
int requestId, int offset, BluetoothGattDescriptor descriptor) {
super.onDescriptorReadRequest(device, requestId, offset, descriptor);
-
+
CALeGattServerDescriptorReadRequestCallback(device, requestId, offset, descriptor);
}
byte[] value) {
super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite,
responseNeeded, offset, value);
-
- CALeGattServerDescriptorWriteRequestCallback(device, requestId, descriptor, preparedWrite,
- responseNeeded, offset, value);
+
+ CALeGattServerDescriptorWriteRequestCallback(device, requestId, descriptor,
+ preparedWrite, responseNeeded, offset, value);
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId,
boolean execute) {
super.onExecuteWrite(device, requestId, execute);
-
+
CALeGattServerExecuteWriteCallback(device, requestId, execute);
}
@Override
public void onNotificationSent(BluetoothDevice device, int status) {
super.onNotificationSent(device, status);
-
+
CALeGattServerNotificationSentCallback(device, status);
}
};
-
+
private static final AdvertiseCallback mAdvertiseCallback = new AdvertiseCallback() {
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
-
+
CALeAdvertiseStartSuccessCallback(settingsInEffect);
}
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
-
+
CALeAdvertiseStartFailureCallback(errorCode);
}
};
-
+
private static final BroadcastReceiver mReceiver = new BroadcastReceiver() {
-
+
@Override
public void onReceive(Context context, Intent intent) {
-
+
String action = intent.getAction();
-
+
if (action != null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
-
- int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
-
- if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF) // STATE_ON:12, STATE_OFF:10
- {
+
+ int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
+ BluetoothAdapter.ERROR);
+ // STATE_ON:12, STATE_OFF:10
+ if (state == BluetoothAdapter.STATE_ON || state == BluetoothAdapter.STATE_OFF) {
CALeStateChangedCallback(state);
- }
+ }
}
}
};
}
+
WifiManager.WIFI_STATE_UNKNOWN) == WifiManager.WIFI_STATE_DISABLED) {
CAWiFiStateDisabled();
} else if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
- ConnectivityManager manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
+ ConnectivityManager manager = (ConnectivityManager)
+ mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
+ NetworkInfo nwInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
- if(nwInfo.isConnected()) {
- CAWiFiStateEnabled();
+ if(nwInfo.isConnected()) {
+ CAWiFiStateEnabled();
}
}
}
public native static void CAWiFiStateDisabled();
}
+
private final CharSequence[] mCheckBoxItems = { Network.WIFI.name(),
Network.EDR.name(), Network.LE.name() };
- private final CharSequence[] mDTLSCheckBoxItems = { DTLS.UNSECURED.name(),
- DTLS.SECURED.name() };
+ private final CharSequence[] mDTLSCheckBoxItems = { DTLS.SECURED.name(),
+ DTLS.UNSECURED.name() };
private final CharSequence[] mMsgTyleCheckBoxItems = { MsgType.CON.name(),
- MsgType.NON.name(), MsgType.ACK.name(), MsgType.RESET.name() };
-
- private final CharSequence[] mResponseResultCheckBoxItems = {
- ResponseResult.CA_SUCCESS.name(), ResponseResult.CA_CREATED.name(),
- ResponseResult.CA_DELETED.name(), ResponseResult.CA_EMPTY.name(),
- ResponseResult.CA_BAD_REQ.name(), ResponseResult.CA_BAD_OPT.name(),
- ResponseResult.CA_NOT_FOUND.name(),
- ResponseResult.CA_RETRANSMIT_TIMEOUT.name() };
+ MsgType.NON.name() };
private enum Mode {
SERVER, CLIENT, BOTH, UNKNOWN
};
private enum DTLS {
- UNSECURED, SECURED
+ SECURED, UNSECURED
};
private enum MsgType {
- CON, NON, ACK, RESET
+ CON, NON
};
- private enum ResponseResult {
- CA_SUCCESS, CA_CREATED, CA_DELETED, CA_EMPTY, CA_BAD_REQ, CA_BAD_OPT,
- CA_NOT_FOUND, CA_RETRANSMIT_TIMEOUT
- }
-
private Mode mCurrentMode = Mode.UNKNOWN;
private ArrayList<Integer> mSelectedItems = new ArrayList<Integer>();
private EditText mPayload_ed = null;
- private EditText mAdvertise_ed = null;
-
private Button mFind_btn = null;
private Button mNotify_btn = null;
/**
* Defined ConnectivityType in cacommon.c
- *
+ *
* CA_ETHERNET = (1 << 0) CA_WIFI = (1 << 1) CA_EDR = (1 << 2) CA_LE = (1 <<
* 3)
*/
private int CA_WIFI = (1 << 1);
private int CA_EDR = (1 << 2);
private int CA_LE = (1 << 3);
- private int isSecured = -1;
- private int msgType = -1;
- private int responseValue = -1;
+ private int isSecured = 0;
+ private int msgType = 0;
private int selectedItem = 0;
- private int selectedResponseValue = -1;
int selectedNetwork = 0;
@Override
// client
mSendRequestLayout = (RelativeLayout) findViewById(R.id.layout_request);
- mSendRequestSettingLayout = (RelativeLayout)
+ mSendRequestSettingLayout = (RelativeLayout)
findViewById(R.id.layout_request_setting_for_client);
mFindResourceLayout = (RelativeLayout) findViewById(R.id.layout_find);
mFindTitleLayout = (RelativeLayout) findViewById(R.id.layout_find_title);
// server
mSendNotificationLayout = (RelativeLayout) findViewById(R.id.layout_notify);
- mPayLoadServerEditLayout = (RelativeLayout)
- findViewById(R.id.layout_payload_server_ed);
- mSendResponseNotiSettingLayout = (RelativeLayout)
+ mPayLoadServerEditLayout = (RelativeLayout) findViewById(R.id.layout_payload_server_ed);
+ mSendResponseNotiSettingLayout = (RelativeLayout)
findViewById(R.id.layout_request_setting_for_server);
mServerButtonLayout = (RelativeLayout) findViewById(R.id.layout_server_bt);
- mResponseNotificationTitleLayout = (RelativeLayout)
+ mResponseNotificationTitleLayout = (RelativeLayout)
findViewById(R.id.layout_Response_Noti_title);
mAdvertiseTitleLayout = (RelativeLayout) findViewById(R.id.layout_advertise_title);
mAdvertiseResourceLayout = (RelativeLayout) findViewById(R.id.layout_advertise_resource);
mNotification_ed = (EditText) findViewById(R.id.et_notification);
mReqData_ed = (EditText) findViewById(R.id.et_req_data);
mPayload_ed = (EditText) findViewById(R.id.et_payload_data_for_server);
- mAdvertise_ed = (EditText) findViewById(R.id.et_uri_advertise);
-
+
mFind_btn = (Button) findViewById(R.id.btn_find_resource);
mResponse_btn = (Button) findViewById(R.id.btn_sendresponse);
mNotify_btn = (Button) findViewById(R.id.btn_notify);
mAdvertiseResource_btn = (Button) findViewById(R.id.btn_advertise);
mReqeust_btn = (Button) findViewById(R.id.btn_Request);
mReqeust_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_client);
- mResponse_Notify_setting_btn = (Button) findViewById(R.id.btn_Request_setting_for_server);
+ mResponse_Notify_setting_btn = (Button)
+ findViewById(R.id.btn_Request_setting_for_server);
mRecv_btn = (Button) findViewById(R.id.btn_receive);
mFind_btn.setOnClickListener(mFindResourceHandler);
// Initialize Connectivity Abstraction
RM.RMInitialize(getApplicationContext());
// Select default network(WIFI)
-// RM.RMSelectNetwork(CA_WIFI);
+ RM.RMSelectNetwork(CA_WIFI);
// set handler
RM.RMRegisterHandler();
}
public void onClick(View v) {
DLog.v(TAG, "SendResponse click");
- RM.RMSendResponse(selectedNetwork, isSecured, msgType, responseValue);
+ RM.RMSendResponse(mNotification_ed.getText().toString(),
+ mPayload_ed.getText().toString(), selectedNetwork,
+ isSecured);
}
};
public void onClick(View v) {
DLog.v(TAG, "AdvertiseResource click");
- RM.RMAdvertiseResource(mAdvertise_ed.getText().toString(),
+ RM.RMAdvertiseResource(mNotification_ed.getText().toString(),
selectedNetwork);
}
};
public void onClick(View v) {
checkMsgSecured("Select DTLS Type");
- checkMsgType("Select Msg Type");
- checkResponseResult("Select Value of Response Result");
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(title)
- .setSingleChoiceItems(mDTLSCheckBoxItems, isSecured,
+ .setSingleChoiceItems(mDTLSCheckBoxItems, -1,
new DialogInterface.OnClickListener() {
@Override
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(title)
- .setSingleChoiceItems(mMsgTyleCheckBoxItems, msgType,
+ .setSingleChoiceItems(mMsgTyleCheckBoxItems, -1,
new DialogInterface.OnClickListener() {
@Override
} else if (selectedItem == MsgType.NON.ordinal()) {
msgType = 1;
DLog.v(TAG, "Message Type is NON");
- } else if (selectedItem == MsgType.ACK.ordinal()) {
- msgType = 2;
- DLog.v(TAG, "Message Type is ACK");
- } else if (selectedItem == MsgType.RESET.ordinal()) {
- msgType = 3;
- DLog.v(TAG, "Message Type is RESET");
}
- }
- }).show();
- }
- private void checkResponseResult(String title) {
-
- AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
- builder.setTitle(title)
- .setSingleChoiceItems(mResponseResultCheckBoxItems, selectedResponseValue,
- new DialogInterface.OnClickListener() {
-
- @Override
- public void onClick(DialogInterface dialog,
- int which) {
- selectedResponseValue = which;
- }
- })
- .setPositiveButton("OK", new DialogInterface.OnClickListener() {
-
- @Override
- public void onClick(DialogInterface dialog, int which) {
-
- if (selectedResponseValue == ResponseResult.CA_SUCCESS.ordinal()) {
- responseValue = 200;
- DLog.v(TAG, "Response Value is CA_SUCCESS");
- } else if (selectedResponseValue == ResponseResult.CA_CREATED
- .ordinal()) {
- responseValue = 201;
- DLog.v(TAG, "Response Value is CA_CREATED");
- } else if (selectedResponseValue == ResponseResult.CA_DELETED
- .ordinal()) {
- responseValue = 202;
- DLog.v(TAG, "Response Value is CA_DELETED");
- } else if (selectedResponseValue == ResponseResult.CA_EMPTY
- .ordinal()) {
- responseValue = 231;
- DLog.v(TAG, "Response Value is CA_EMPTY");
- } else if (selectedResponseValue == ResponseResult.CA_BAD_REQ
- .ordinal()) {
- responseValue = 400;
- DLog.v(TAG, "Response Value is CA_BAD_REQ");
- } else if (selectedResponseValue == ResponseResult.CA_BAD_OPT
- .ordinal()) {
- responseValue = 402;
- DLog.v(TAG, "Response Value is CA_BAD_OPT");
- } else if (selectedResponseValue == ResponseResult.CA_NOT_FOUND
- .ordinal()) {
- responseValue = 404;
- DLog.v(TAG, "Response Value is CA_NOT_FOUND");
- } else if (selectedResponseValue == ResponseResult.CA_RETRANSMIT_TIMEOUT
- .ordinal()) {
- responseValue = 531;
- DLog.v(TAG, "Response Value is CA_RETRANSMIT_TIMEOUT");
- }
}
}).show();
}
DLog.v(TAG, callbackData);
}
-}
\ No newline at end of file
+}
public native void RMSendRequest(String uri, String payload,
int selectedNetwork, int isSecured, int msgType);
- public native void RMSendResponse(int selectedNetwork, int isSecured,
- int msgType, int responseValue);
+ public native void RMSendResponse(String uri, String payload,
+ int selectedNetwork, int isSecured);
public native void RMAdvertiseResource(String advertiseResource,
int selectedNetwork);
}
}
-}
\ No newline at end of file
+}
Alias('arduino_simplecs', i_arduino_simplecs)
sample_env.Default('CASample.hex')
-if(sample_env['UPLOAD'] == True):
+if(sample_env['UPLOAD'] == True):
sample_env.Upload(env.get('BUILD_DIR') + '/samples/arduino/' + 'CASample.hex')
+
#include "cainterface.h"
#include "Arduino.h"
+#ifdef ETHERNET_ADAPTER
+#include "Ethernet.h"
+#endif
+
+#ifdef WIFI_ADAPTER
+#include "WiFi.h"
+#endif
+
#include "oic_malloc.h"
#define MAX_BUF_LEN 100 //1024
#define MAX_OPT_LEN 16
-#define printf Serial.println
-//#define printf
-
-bool isLeSelected = false;
-
-void print_menu();
-void process();
-
-void initialize();
-void start_listening_server();
-void start_discovery_server();
-void find_resource();
-void send_request();
-void send_request_all();
-void send_response(CARemoteEndpoint_t *endpoint, const CAInfo_t* info);
-void advertise_resource();
-void send_notification();
-void select_network();
-void unselect_network();
-void handle_request_response();
-
-void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
-void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token);
-void terminate();
-
-void getData(char *readInput, int16_t bufferLength, int16_t *dataLength)
+static bool g_isLeSelected = false;
+
+static void PrintMenu();
+static void Process();
+static void Initialize();
+static void StartListeningServer();
+static void StartDiscoveryServer();
+static void FindResource();
+static void SendRequest();
+static void SendRequestAll();
+static void SendResponse(CARemoteEndpoint_t *endpoint, const CAInfo_t* info);
+static void AdvertiseResource();
+static void SendNotification();
+static void SelectNetwork();
+static void UnselectNetwork();
+static void HandleRequestResponse();
+
+static void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
+static void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+static void Terminate();
+
+void GetData(char *readInput, size_t bufferLength, size_t *dataLength)
{
- while (!Serial.available());
+ if (!readInput || bufferLength == 0 || !dataLength)
+ {
+ Serial.println("Invalid buffer");
+ return;
+ }
+
+ while (!Serial.available())
+ {
+ delay(500);
+ }
int len = 0;
while (Serial.available())
{
(*dataLength) = len;
}
-CAConnectivityType_t getConnectivityType()
+CAConnectivityType_t GetConnectivityType()
{
- char type[2];
- memset(type, 0, sizeof(char));
- printf("Select network");
- printf("ETHERNET: 0");
- printf("WIFI: 1");
- printf("EDR: 2");
- printf("LE: 3");
-
-
- int16_t typeLen = 0;
- getData(type, sizeof(type), &typeLen);
- int num = type[0] - '0';
- switch (num)
+ char type[2] = {0};
+ Serial.println("Select network");
+ Serial.println("ETHERNET: 0");
+ Serial.println("WIFI: 1");
+ Serial.println("EDR: 2");
+ Serial.println("LE: 3");
+
+ size_t typeLen = 0;
+ GetData(type, sizeof(type), &typeLen);
+ if (0 >= typeLen)
{
- case 0:
+ Serial.println("i/p err,default ethernet");
+ return CA_ETHERNET;
+ }
+ switch (type[0])
+ {
+ case '0':
return CA_ETHERNET;
- case 1:
+ case '1':
return CA_WIFI;
- case 2:
+ case '2':
return CA_EDR;
- case 3:
+ case '3':
return CA_LE;
}
return CA_ETHERNET;
}
+
void setup()
{
Serial.begin (115200);
- printf("============");
- printf("CA SAMPLE");
- printf("============");
- print_menu();
+ Serial.println("============");
+ Serial.println("CA SAMPLE");
+ Serial.println("============");
+ PrintMenu();
}
void loop()
{
- char buffer[5];
- memset(buffer, 0, sizeof(buffer));
- int16_t len;
+ char buffer[5] = {0};
+ size_t len;
if (Serial.available() > 0)
{
- getData(buffer, sizeof(buffer), &len);
+ GetData(buffer, sizeof(buffer), &len);
+ if (0 >= len)
+ {
+ Serial.println("i/p err");
+ return;
+ }
switch (toupper(buffer[0]))
{
case 'M': // menu
- print_menu();
+ PrintMenu();
break;
case 'Q': // quit
- printf("quit");
+ Serial.println("quit");
return;
case 'I': // Initialize interface
- initialize();
+ Initialize();
break;
case 'S': // start listening server
- start_listening_server();
+ StartListeningServer();
break;
case 'D': // start discovery server
- start_discovery_server();
+ StartDiscoveryServer();
break;
case 'F': // find resource
- find_resource();
+ FindResource();
break;
case 'R': // send request
- send_request();
+ SendRequest();
break;
case 'E': //send request to all
- send_request_all();
+ SendRequestAll();
break;
case 'A': // advertise resource
- advertise_resource();
+ AdvertiseResource();
break;
case 'B': // send notification
- send_notification();
+ SendNotification();
break;
case 'N': // select network
- select_network();
+ SelectNetwork();
break;
case 'X': // unselect network
- unselect_network();
+ UnselectNetwork();
break;
case 'H': // handle request response
- handle_request_response();
+ HandleRequestResponse();
break;
case 'T': // handle request response
- terminate();
+ Terminate();
break;
default:
- printf("wrong menu");
+ Serial.println("wrong menu");
break;
}
}
//1:Add check for startserver before calling below api
- if (true == isLeSelected)
+ if (g_isLeSelected)
{
- handle_request_response();
+ HandleRequestResponse();
}
delay(1000);
}
-void initialize()
+void Initialize()
{
- CAInitialize();
- select_network();
+ if(CAInitialize() != CA_STATUS_OK)
+ {
+ Serial.println("Initialize failed");
+ return;
+ }
+ SelectNetwork();
// set handler.
- CARegisterHandler(request_handler, response_handler);
+ CARegisterHandler(RequestHandler, ResponseHandler);
}
-void start_listening_server()
+void StartListeningServer()
{
- printf("start server");
- CAStartListeningServer();
+ Serial.println("listening server");
+ CAResult_t ret = CAStartListeningServer();
+ if(ret != CA_STATUS_OK)
+ {
+ Serial.print("listening failed: ");
+ Serial.println(ret);
+ return;
+ }
}
-void start_discovery_server()
+void StartDiscoveryServer()
{
- printf("start server");
- CAStartDiscoveryServer();
+ Serial.println("discovery server");
+ CAResult_t ret = CAStartDiscoveryServer();
+ if(ret != CA_STATUS_OK)
+ {
+ Serial.print("discovery failed: ");
+ Serial.println(ret);
+ return;
+ }
}
-void find_resource()
+void FindResource()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- printf("============");
- printf("ex) /a/light");
- printf("uri: ");
- int len = 0;
- getData(buf, sizeof(buf), &len);
-
+ char buf[MAX_BUF_LEN] = {0};
+ Serial.println("============");
+ Serial.println("ex) /a/light");
+ Serial.println("uri: ");
+ size_t len = 0;
+ GetData(buf, sizeof(buf), &len);
+ if (0 >= len)
+ {
+ Serial.println("i/p err");
+ return;
+ }
// create token
CAToken_t token = NULL;
CAResult_t res = CAGenerateToken(&token);
- if (res != CA_STATUS_OK)
+ if (res != CA_STATUS_OK || token == NULL)
{
- printf("token generate error!!");
- token = NULL;
+ Serial.println("token error");
+ return;
}
- printf("token");
- printf((token != NULL) ? token : "");
+ Serial.print("token:");
+ Serial.println(token);
res = CAFindResource(buf, token);
if (res != CA_STATUS_OK)
{
- printf("find error");
+ Serial.print("find error: ");
+ Serial.println(res);
}
else
{
- printf("success: ");
- printf(buf);
+ Serial.println("success: ");
+ Serial.println(buf);
}
CADestroyToken(token);
}
-void send_request()
+void SendRequest()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
+ char buf[MAX_BUF_LEN] = {0};
CAConnectivityType_t selectedNetwork;
- selectedNetwork = getConnectivityType();
+ selectedNetwork = GetConnectivityType();
- printf("============");
- printf("10.11.12.13:4545/res_uri (for IP)");
- printf("10:11:12:13:45:45/res_uri (for BT)");
- printf("uri: ");
+ Serial.println("============");
+ Serial.println("10.11.12.13:4545/res_uri (for IP)");
+ Serial.println("10:11:12:13:45:45/res_uri (for BT)");
+ Serial.println("uri: ");
- int16_t len = 0;
- getData(buf, (int16_t)sizeof(buf), &len);
+ size_t len = 0;
+ GetData(buf, sizeof(buf), &len);
+ if (0 >= len)
+ {
+ Serial.println("i/p err");
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
CAResult_t res = CACreateRemoteEndpoint(buf,selectedNetwork,&endpoint);
if (res != CA_STATUS_OK)
{
- printf("Out of memory");
+ Serial.println("Out of memory");
CADestroyRemoteEndpoint(endpoint);
return;
}
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ memset(buf, 0, sizeof(buf));
- printf("\n=============================================\n");
- printf("0:CON, 1:NON\n");
- printf("select message type : ");
+ Serial.println("\n=============================================\n");
+ Serial.println("0:CON, 1:NON\n");
+ Serial.println("select message type : ");
+ GetData(buf, sizeof(buf), &len);
+ CAMessageType_t msgType = CA_MSG_CONFIRM;
- getData(buf, (int16_t)sizeof(buf), &len);
-
- int32_t msg_type = (CAMessageType_t) (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0;
- CAMessageType_t msgType; // = (CAMessageType_t) (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0;
- if(msg_type == 0)
- msgType = CA_MSG_CONFIRM;
- else if(msg_type == 1)
- msgType = CA_MSG_NONCONFIRM;
- else if(msg_type == 2)
- msgType = CA_MSG_ACKNOWLEDGE;
- else if(msg_type == 3)
- msgType = CA_MSG_RESET;
+ if (0 >= len)
+ {
+ Serial.println("i/p err,default: 0");
+ }
+ else if(buf[0] == '1')
+ {
+ msgType = CA_MSG_NONCONFIRM;
+ }
// create token
CAToken_t token = NULL;
res = CAGenerateToken(&token);
if (res != CA_STATUS_OK)
{
- printf("token error");
+ Serial.println("token error");
token = NULL;
+ return;
}
- printf((token != NULL) ? token : "");
-
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ Serial.println((token != NULL) ? token : "");
+ CAInfo_t requestData = {CA_MSG_RESET};
requestData.token = token;
requestData.payload = (CAPayload_t)"Json Payload";
requestData.type = msgType;
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
requestInfo.method = CA_GET;
requestInfo.info = requestData;
CADestroyRemoteEndpoint(endpoint);
}
- printf("============");
+ Serial.println("============");
}
-void send_request_all()
+void SendRequestAll()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = {0};
CAConnectivityType_t selectedNetwork;
- selectedNetwork = getConnectivityType();
+ selectedNetwork = GetConnectivityType();
- printf("=========");
- printf("10.11.12.13:4545/resource_uri ( for IP )");
- printf("10:11:12:13:45:45/resource_uri ( for BT )");
- printf("uri : ");
+ Serial.println("=========");
+ Serial.println("10.11.12.13:4545/resource_uri ( for IP )");
+ Serial.println("10:11:12:13:45:45/resource_uri ( for BT )");
+ Serial.println("uri : ");
- int16_t len = 0;
- getData(buf, (int16_t)sizeof(buf), &len);
+ size_t len = 0;
+ GetData(buf, sizeof(buf), &len);
+ if (0 >= len)
+ {
+ Serial.println("i/p err");
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
if (res != CA_STATUS_OK)
{
- printf("create remote endpoint error");
+ Serial.println("create remote endpoint error");
CADestroyRemoteEndpoint(endpoint);
return;
}
-
CAGroupEndpoint_t *group = NULL;
group = (CAGroupEndpoint_t *)OICMalloc(sizeof(CAGroupEndpoint_t));
group->connectivityType = endpoint->connectivityType;
group->resourceUri = endpoint->resourceUri;
-
// create token
CAToken_t token = NULL;
res = CAGenerateToken(&token);
-
if (res != CA_STATUS_OK)
{
- printf("token error");
+ Serial.println("token error");
token = NULL;
+ return;
}
- printf((token != NULL) ? token : "");
+ Serial.println((token != NULL) ? token : "");
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ CAInfo_t requestData = {CA_MSG_RESET};
requestData.token = token;
requestData.payload = "Temp Json Payload";
requestData.type = CA_MSG_NONCONFIRM;
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+
+ CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
requestInfo.method = CA_GET;
requestInfo.info = requestData;
}
OICFree(group);
-
- printf("==========");
+ Serial.println("==========");
}
-void advertise_resource()
+void AdvertiseResource()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = {0};
- printf("============");
- printf("uri: ");
+ Serial.println("============");
+ Serial.println("uri: ");
- int16_t len = 0;
- getData(buf, (int16_t)sizeof(buf), &len);
+ size_t len = 0;
+ GetData(buf, sizeof(buf), &len);
+ if (0 >= len)
+ {
+ Serial.println("no i/p");
+ return;
+ }
int16_t optionNum = 0;
- char optionData[MAX_OPT_LEN];
- char optionNumBuf[2];
-
- printf("Option Num: ");
- getData(optionNumBuf, (int16_t)sizeof(optionNumBuf), &len);
- optionNum = optionNumBuf[0] - '0';
- printf(optionNum);
+ char optionData[MAX_OPT_LEN] = {0};
+ char optionNumBuf[2] = {0};
+ Serial.println("Option Num: ");
+ GetData(optionNumBuf, sizeof(optionNumBuf), &len);
+ if (0 >= len)
+ {
+ Serial.println("no i/p,0 option");
+ }
+ else
+ {
+ optionNum = atoi(optionNumBuf);
+ Serial.println(optionNum);
+ }
CAHeaderOption_t *headerOpt = NULL;
if (optionNum > 0)
{
- headerOpt = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * optionNum);
+ headerOpt = (CAHeaderOption_t *) OICCalloc(optionNum, sizeof(CAHeaderOption_t));
if (NULL == headerOpt)
{
- printf("Out of memory");
+ Serial.println("Out of memory");
return;
}
- memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
}
int i;
for (i = 0 ; i < optionNum ; i++)
{
int optionID = 0;
- char getOptionID[2];
- getData(getOptionID, (int16_t)sizeof(getOptionID), &len);
- printf("Option Num: ");
- printf(i + 1);
- optionID = getOptionID[0];
- printf(optionID);
+ char getOptionID[4];
+ Serial.println("Opt ID:");
+ GetData(getOptionID, sizeof(getOptionID), &len);
+ if (0 >= len)
+ {
+ Serial.println("no i/p");
+ continue;
+ }
+ else
+ {
+ optionID = atoi(getOptionID);
+ }
- headerOpt[i].optionID = optionID;
- memset(optionData, 0, sizeof(char) * MAX_OPT_LEN);
- printf("Option Data itr");
- printf(i + 1);
+ memset(optionData, 0, sizeof(optionData));
+ Serial.println("Opt Data:");
+ GetData(optionData, sizeof(optionData), &len);
+ if (0 >= len)
+ {
+ Serial.println("no i/p");
+ continue;
+ }
- int len = 0;
- getData(optionData, (int16_t)sizeof(optionData), &len);
+ headerOpt[i].optionID = optionID;
memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
- printf(i + 1);
- printf("data");
- printf(optionData);
+ Serial.println("ID:");
+ Serial.println(optionID);
+ Serial.println("Data:");
+ Serial.println(optionData);
headerOpt[i].optionLength = (uint16_t)strlen(optionData);
}
- printf("============");
+ Serial.println("============");
// create token
CAToken_t token = NULL;
CAResult_t res = CAGenerateToken(&token);
if (res != CA_STATUS_OK)
{
- printf("token generate error!!");
+ Serial.println("token error");
token = NULL;
+ return;
}
- printf("token");
- printf((token != NULL) ? token : "");
+ Serial.println("token");
+ Serial.println((token != NULL) ? token : "");
CAAdvertiseResource(buf, token, headerOpt, (uint8_t)optionNum);
- if (NULL != headerOpt)
- {
- OICFree(headerOpt);
- }
+ OICFree(headerOpt);
CADestroyToken(token);
}
-void send_notification()
+void SendNotification()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = {0};
CAConnectivityType_t selectedNetwork;
- selectedNetwork = getConnectivityType();
+ selectedNetwork = GetConnectivityType();
- printf("============");
- printf("10.11.12.13:4545/res_uri (for IP)");
- printf("10:11:12:13:45:45/res_uri (for BT)");
- printf("uri: ");
+ Serial.println("============");
+ Serial.println("10.11.12.13:4545/res_uri (for IP)");
+ Serial.println("10:11:12:13:45:45/res_uri (for BT)");
+ Serial.println("uri: ");
- int16_t len = 0;
- getData(buf, (int16_t)sizeof(buf), &len);
+ size_t len = 0;
+ GetData(buf, sizeof(buf), &len);
+ if (0 >= len)
+ {
+ Serial.println("i/p err");
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
CAResult_t res = CACreateRemoteEndpoint(buf,selectedNetwork,&endpoint);
if (CA_STATUS_OK != res)
{
- printf("Out of memory");
+ Serial.println("Out of memory");
CADestroyRemoteEndpoint(endpoint);
return;
}
- CAInfo_t respondeData;
- memset(&respondeData, 0, sizeof(CAInfo_t));
+ CAInfo_t respondeData = {CA_MSG_RESET};
respondeData.token = (CAToken_t)"token";
respondeData.payload = (CAPayload_t)"Notification Data";
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
responseInfo.result = CA_SUCCESS;
responseInfo.info = respondeData;
{
CADestroyRemoteEndpoint(endpoint);
}
- printf("============");
+ Serial.println("============");
}
-void select_network()
+void SelectNetwork()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- printf("============");
- printf("Select network");
- printf("ETHERNET: 0");
- printf("WIFI: 1");
- printf("EDR: 2");
- printf("LE: 3\n");
-
- int16_t len = 0;
- getData(buf, (int16_t)sizeof(buf), &len);
+ char buf[MAX_BUF_LEN] = {0};
+
+ Serial.println("============");
+ Serial.println("Select network");
+ Serial.println("ETHERNET: 0");
+ Serial.println("WIFI: 1");
+ Serial.println("EDR: 2");
+ Serial.println("LE: 3\n");
+
+ size_t len = 0;
+ GetData(buf, sizeof(buf), &len);
int number = buf[0] - '0';
- number = (number < 0 || number > 3) ? 1 : number;
- if (number == 3)
+ if (0 >= len || number < 0 || number > 3)
+ {
+ Serial.println("Wrong i/p. WIFI selected");
+ number = 1;
+ }
+
+ switch (number)
{
- isLeSelected = true;
+ case 0:
+ {
+#ifdef ETHERNET_ADAPTER
+ // Note: ****Update the MAC address here with your shield's MAC address****
+ uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
+ uint8_t error = Ethernet.begin(ETHERNET_MAC);
+ if (error == 0)
+ {
+ Serial.print("Failed: ");
+ Serial.println(error);
+ return;
+ }
+#endif
+ }
+ break;
+ case 1:
+ {
+#ifdef WIFI_ADAPTER
+ const char ssid[] = "SSID"; // your network SSID (name)
+ const char pass[] = "SSID_Password"; // your network password
+ int16_t status = WL_IDLE_STATUS; // the Wifi radio's status
+
+ if (WiFi.status() == WL_NO_SHIELD)
+ {
+ Serial.println("ERROR:No Shield");
+ return;
+ }
+
+ while (status != WL_CONNECTED)
+ {
+ Serial.print("connecting: ");
+ Serial.println(ssid);
+ // WiFi.begin api is weird. ssid should also be taken as const char *
+ // Connect to WPA/WPA2 network:
+ status = WiFi.begin((char *)ssid, pass);
+ }
+#endif
+ }
+ break;
+ case 2:
+ // Nothing TBD here
+ break;
+ case 3:
+ g_isLeSelected = true;
+ break;
}
- CASelectNetwork(1 << number);
- printf("============");
+
+ CASelectNetwork(CAConnectivityType_t(1<<number));
+ Serial.println("============");
}
-void unselect_network()
+void UnselectNetwork()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- printf("============");
- printf("Unselect network");
- printf("ETHERNET: 0");
- printf("WIFI: 1");
- printf("EDR: 2");
- printf("LE: 3\n");
-
- int16_t len = 0;
- getData(buf, (int16_t)sizeof(buf), &len);
+ char buf[MAX_BUF_LEN] = {0};
+
+ Serial.println("============");
+ Serial.println("Unselect network");
+ Serial.println("ETHERNET: 0");
+ Serial.println("WIFI: 1");
+ Serial.println("EDR: 2");
+ Serial.println("LE: 3\n");
+
+ size_t len = 0;
+ GetData(buf, sizeof(buf), &len);
int number = buf[0] - '0';
- printf(number);
- number = (number < 0 || number > 3) ? 1 : number;
+ Serial.println(number);
+ if (0 >= len || number < 0 || number > 3)
+ {
+ Serial.println("Wrong i/p. WIFI selected");
+ number = 1;
+ }
if (number == 3)
{
- isLeSelected = false;
+ g_isLeSelected = false;
}
CAUnSelectNetwork(1 << number);
- printf("Terminate");
+ Serial.println("Terminate");
CATerminate();
- printf("============");
+ Serial.println("============");
}
-void print_menu()
+void PrintMenu()
{
- printf("============");
- printf("i: Initialize");
- printf("s: start listening server");
- printf("d: start discovery server");
- printf("f: find resource");
- printf("r: send request");
- printf("e: send request to all");
- printf("a: advertise resource");
- printf("b: send notification");
- printf("n: select network");
- printf("x: unselect network");
- printf("h: handle request response");
- printf("t: terminate");
- printf("q: quit");
- printf("============");
+ Serial.println("============");
+ Serial.println("i: Initialize");
+ Serial.println("s: start listening server");
+ Serial.println("d: start discovery server");
+ Serial.println("f: find resource");
+ Serial.println("r: send request");
+ Serial.println("e: send request to all");
+ Serial.println("a: advertise resource");
+ Serial.println("b: send notification");
+ Serial.println("n: select network");
+ Serial.println("x: unselect network");
+ Serial.println("h: handle request response");
+ Serial.println("t: terminate");
+ Serial.println("q: quit");
+ Serial.println("============");
}
-void handle_request_response()
+void HandleRequestResponse()
{
CAHandleRequestResponse();
}
-void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
{
if (!object)
{
- printf("Remote endpoint is NULL!");
+ Serial.println("Remote endpoint is NULL!");
return;
}
if (!requestInfo)
{
- printf("Request info is NULL!");
+ Serial.println("Request info is NULL!");
return;
}
- printf("uri: ");
- printf(object->resourceUri);
- printf("RAddr: ");
- printf(object->addressInfo.IP.ipAddress);
- printf("Port: ");
- printf(object->addressInfo.IP.port);
- printf("data: ");
- printf(requestInfo->info.payload);
- printf("Type: ");
- printf(requestInfo->info.type);
+ Serial.println("uri: ");
+ Serial.println(object->resourceUri);
+ Serial.println("RAddr: ");
+ Serial.println(object->addressInfo.IP.ipAddress);
+ Serial.println("Port: ");
+ Serial.println(object->addressInfo.IP.port);
+ Serial.println("data: ");
+ Serial.println(requestInfo->info.payload);
+ Serial.println("Type: ");
+ Serial.println(requestInfo->info.type);
if (requestInfo->info.options)
{
uint32_t i;
for (i = 0; i < len; i++)
{
- printf("Option:");
- printf(i+1);
- printf("ID:");
- printf(requestInfo->info.options[i].optionID);
- printf("Data:");
- printf((char*)requestInfo->info.options[i].optionData);
+ Serial.println("Option:");
+ Serial.println(i+1);
+ Serial.println("ID:");
+ Serial.println(requestInfo->info.options[i].optionID);
+ Serial.println("Data:");
+ Serial.println((char*)requestInfo->info.options[i].optionData);
}
}
- printf("send response");
- send_response((CARemoteEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
+ Serial.println("send response");
+ SendResponse((CARemoteEndpoint_t *)object, (requestInfo != NULL) ? &requestInfo->info : NULL);
}
-void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
- printf("uri: ");
- printf((object != NULL) ? object->resourceUri : "");
- printf("data: ");
- printf((responseInfo != NULL) ? responseInfo->info.payload : "");
- printf("Type: ");
- printf(responseInfo->info.type);
- printf("res result=");
- printf(responseInfo->result);
+ if (object && object->resourceUri)
+ {
+ Serial.print("uri: ");
+ Serial.println(object->resourceUri);
+ }
+
+ if (responseInfo)
+ {
+ Serial.print("data: ");
+ Serial.println(responseInfo->info.payload);
+ Serial.print("Type: ");
+ Serial.println(responseInfo->info.type);
+ Serial.print("res result=");
+ Serial.println(responseInfo->result);
+ }
}
-void send_response(CARemoteEndpoint_t *endpoint, const CAInfo_t* info)
+void SendResponse(CARemoteEndpoint_t *endpoint, const CAInfo_t* info)
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- printf("============");
- printf("Select Message Type");
- printf("CON: 0");
- printf("NON: 1");
- printf("ACK: 2");
- printf("RESET: 3");
-
-
- int16_t len = 0;
- getData(buf, (int16_t)sizeof(buf), &len);
- int32_t messageType = buf[0] - '0';
- int32_t respCode =231 ;
-
- if(messageType != 3)
- {
- printf("============");
- printf("Select Resp code:");
- printf("Success: 200");
- printf("Created: 201");
- printf("Deleted: 202");
- printf("Empty : 231");
- printf("BadReq : 400");
- printf("BadOpt : 402");
- printf("NotFnd : 404");
- printf("Timeout: 531");
- getData(buf, (int16_t)sizeof(buf), &len);
- respCode = atoi(buf);
- }
-
- CAInfo_t responseData;
- memset(&responseData, 0, sizeof(CAInfo_t));
- responseData.type = (CAMessageType_t)messageType;
+ Serial.println("============");
+ CAInfo_t responseData = {CA_MSG_RESET};
+ if(info && info->type == CA_MSG_CONFIRM)
+ {
+ responseData.type = CA_MSG_ACKNOWLEDGE;
+ }
+ else
+ {
+ responseData.type = CA_MSG_NONCONFIRM;
+ }
responseData.messageId = (info != NULL) ? info->messageId : 0;
responseData.token = (info != NULL) ? (CAToken_t)info->token : (CAToken_t)"";
responseData.payload = (CAPayload_t)"response payload";
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = (CAResponseResult_t)respCode;
+ CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
+ responseInfo.result = (CAResponseResult_t)203;
responseInfo.info = responseData;
+
// send request (connectivityType from remoteEndpoint of request Info)
CAResult_t res = CASendResponse(endpoint, &responseInfo);
if(res != CA_STATUS_OK)
{
- printf("Snd Resp error");
+ Serial.println("Snd Resp error");
}
else
{
- printf("Snd Resp success");
+ Serial.println("Snd Resp success");
}
- printf("============");
-
+ Serial.println("============");
}
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token)
+void Terminate()
{
-
- printf("============");
-
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
- requestData.token = token;
- requestData.payload = (CAPayload_t)"Json Payload";
-
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
- requestInfo.method = CA_GET;
- requestInfo.info = requestData;
-
- // send request
- endpoint->connectivityType = CA_WIFI;
- CASendRequest(endpoint, &requestInfo);
-
- printf("============");
-
+ UnselectNetwork();
}
-void terminate()
-{
- unselect_network();
-}
+++ /dev/null
-/*
-
-Copyright (c) 2012-2014 RedBearLab
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-*/
-
-/*
- * HelloWorldl
- *
- * HelloWorld sketch, work with the Chat iOS/Android App.
- * It will send "Hello World" string to the App every 1 sec.
- *
- */
-
-
-////////////////////////////////////////////////////////////
-//
-// This file can be used internal purpose only
-// Do NOT use this file to test.
-//
-////////////////////////////////////////////////////////////
-
-#ifdef __ARDUINO_BLE__
-#include <logger.h>
-
-//"services.h/spi.h/boards.h" is needed in every new project
-#include <SPI.h>
-#include <boards.h>
-#include <RBL_nRF8001.h>
-
-#define PCF(str) ((PROGMEM const char *)(F(str)))
-#define printf Serial.println
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-#include <errno.h>
-#include "Arduino.h"
-#include "caadapterinterface.h"
-#include "cacommon.h"
-#include "caleadapter_singlethread.h"
-
-char localBTAddress[20] = "DB:F7:EB:B5:0F:07"; //BT Address is not used internally by OIC API.
-int number = 0;
-char coapData[30] = "Arduino Test Sample : \0";
-
-CAConnectivityHandler_t *gConnectivityHandlers = NULL;
-CALocalConnectivity_t localEndpoint;
-CARemoteEndpoint_t remoteMulticastEndpoint;
-CARemoteEndpoint_t remoteEndpoint[2];
-
-int CAInterfaceInitializeEndpoint()
-{
- int i = 0;
- /* As of initializing one endpoint */
- for (i = 1; i < /*10*/2; i++)
- {
- if (i == 0)
- {
- /*
- remoteEndpoint[i].connectivityType = WiFi;
- remoteEndpoint[i].endpoint_info = (Address*) malloc (sizeof(Address));
- if (NULL == remoteEndpoint[i].endpoint_info)
- {
- return -1;
- }
- memset(remoteEndpoint[i].endpoint_info, 0, sizeof(Address));
- remoteEndpoint[i].endpoint_info->address = (char*) malloc (sizeof(remoteIPAddress) + 1);
- if (NULL == remoteEndpoint[i].endpoint_info->address)
- {
- return -1;
- }
- memset((void*)remoteEndpoint[i].endpoint_info->address, 0, sizeof(remoteIPAddress) + 1);
- strncpy((char*)remoteEndpoint[i].endpoint_info->address, remoteIPAddress, strlen(remoteIPAddress));
- remoteEndpoint[i].endpoint_info->port = 8254; // Send the corresponding port here
- remoteMulticastEndpoint.connectivityType = WiFi;
- */
- }
- else if (i == 1) //BLE
- {
- /*localEndpoint.endpoint_info = (Address*) malloc (sizeof(Address));
- if (NULL == localEndpoint.endpoint_info)
- {
- return -1;
- }
- memset(localEndpoint.endpoint_info, 0, sizeof(Address));
- localEndpoint.interface.address = (char*) malloc (sizeof(localBTAddress) + 1);
- if (NULL == localEndpoint.interface.address)
- {
- return -1;
- }
- memset((void*)localEndpoint.interface.address, 0, sizeof(localBTAddress) + 1);
- strncpy((char*)localEndpoint.interface.address, localBTAddress, strlen(localBTAddress));*/
-
- remoteEndpoint[i].connectivityType = CA_LE;
- remoteMulticastEndpoint.connectivityType = CA_LE;
- }
-
- }
- return true;
-}
-
-
-void CAInterfaceRegisterCallback(CAConnectivityHandler_t handler , CAConnectivityType_t cType)
-{
- //printf("\ninterfaceRegisterCallback Entry in Sample");
- gConnectivityHandlers = (CAConnectivityHandler_t *) malloc(sizeof(CAConnectivityHandler_t));
- //gConnectivityHandlers->cType = cType;
- gConnectivityHandlers->startListenServer = handler.startListenServer;
- gConnectivityHandlers->terminate = handler.terminate;
- gConnectivityHandlers->sendData = handler.sendData;
- gConnectivityHandlers->sendDataToAll = handler.sendDataToAll;
- gConnectivityHandlers->GetnetInfo = handler.GetnetInfo;
- gConnectivityHandlers->readData = handler.readData;
- gConnectivityHandlers->startListenServer();
- printf("Control comes here");
-}
-
-void CARequestResponseHandler(CARemoteEndpoint_t *object, void *data, uint32_t dataLength)
-{
-#ifdef INTERFACESAMPLE_TIZEN
- printf("\nData Received from");
- printf("\nReceived Data : %s \n", (char *)data);
-#else
- printf("\nData Received from ");
- //printf(object->endpointAddress.address);
- printf("\nReceived Data :");
- printf((char *)data);
-#endif //#ifdef INTERFACESAMPLE_TIZEN
-
-}
-
-
-void CANetworkInterfaceCallback(CALocalConnectivity_t *localEndPoint,
- CANetworkStatus_t networkConnectivityState)
-{
- printf("\nnetworkInterfaceCallback Entry in Sample");
- /*if (localEndPoint == NULL)
- {
- printf("\nNULL Object");
- }
- if (localEndPoint->interface.address){
- printf("Local Interface Address");
- printf(localEndPoint->interface.address);
- }
-
- if (networkConnectivityState == INTERFACE_UP)
- printf("\n WiFi Network Status is UP");
- else
- printf("\n WiFi Network Status is DOWN");*/
- printf("\nnetworkInterfaceCallback Exit in Sample");
-}
-
-
-void setup()
-{
- Serial.begin (115200);
- CAInterfaceInitializeEndpoint();
- CAInitializeLE(CAInterfaceRegisterCallback, CARequestResponseHandler, CANetworkInterfaceCallback);
-}
-unsigned char buf[16] = {0};
-unsigned char len = 0;
-
-void loop()
-{
- if (Serial.available() > 0)
- {
- Serial.println("Serial available.");
- switch (Serial.read())
- {
- case 's':
- {
- Serial.println("sending data");
- if ( ble_connected() )
- {
- Serial.println("Sending Data");
- gConnectivityHandlers->sendData(&remoteEndpoint[1], coapData, strlen(coapData));
- Serial.println("Sent Data");
- }
- }
- break;
- case 'n':
- {
- Serial.println("Before get network information");
- uint32_t size = 0;
- static CALocalConnectivity_t *localLeEndpoint = NULL;
- gConnectivityHandlers->GetnetInfo(&localLeEndpoint, &size);
- Serial.print("LEAddr:");
- Serial.println(localLeEndpoint->addressInfo.LE.leMacAddress);
- Serial.println("After get network information");
- }
- break;
- }
- }
- gConnectivityHandlers->readData();
- delay(1000);
-}
-#else
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-//#include <fcntl.h>
-#include <errno.h>
-
-#include "Arduino.h"
-
-#include "cawifiadapter_singlethread.h"
-
-#include <logger.h>
-#include "caadapterinterface.h"
-//#include "cawifiethernetadapter.h"
-#include "cacommon.h"
-#define MOD_NAME "ArduinoSample"
-static CALocalConnectivity_t *localWifiEndpoint = NULL;
-static CARemoteEndpoint_t remoteMulticastEndpoint;
-static CARemoteEndpoint_t remoteEndpoint[10]; /* 10 RemoteEndpoints are currently kept */
-static char remoteIPAddress[CA_IPADDR_SIZE] =
- "192.168.1.105"; //Change the receiver IP address during testing.
-static char readIpAddress[20];
-//Hardcoded coap data for Test
-static char coapData[500] =
- "{\"oc:\[{href\":\"/a/light\",\"ref\":{\"power\":\"20\",\"state\":\"true\"}}]}";
-
-typedef struct ConnectivityHandlerList
-{
- CAConnectivityType_t type;
- CAConnectivityHandler_t handler;
- struct ConnectivityHandlerList *nextHandler;
-} ConnectivityHandlerList;
-
-static ConnectivityHandlerList *gConnectivityHandlers = NULL;
-
-int16_t CAInterfaceInitializeEndpoint()
-{
- int16_t i = 0;
- /* As of initializing one endpoint */
- for (i = 0; i < 1; i++)
- {
- remoteEndpoint[i].connectivityType = CA_WIFI;
- memset((void *)remoteEndpoint[i].addressInfo.IP.ipAddress, 0, sizeof(remoteIPAddress) + 1);
- strncpy((char *)remoteEndpoint[i].addressInfo.IP.ipAddress, remoteIPAddress,
- strlen(remoteIPAddress));
- remoteEndpoint[i].addressInfo.IP.port = 5683; /* Send the corresponding port here */
- }
-
- remoteMulticastEndpoint.connectivityType = CA_WIFI;
- return true;
-}
-
-void CAStoreInterfaceCallbacks(ConnectivityHandlerList *newHandler)
-{
- OIC_LOG(DEBUG, MOD_NAME, "storeInterfaceCallbacks Entry in Sample");
- newHandler->nextHandler = NULL;
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
-
- if (!tempConnectivityHandlers)
- {
- gConnectivityHandlers = newHandler;
- OIC_LOG(DEBUG, MOD_NAME, "storeInterfaceCallbacks Exit in Sample");
- return;
- }
-
- while (tempConnectivityHandlers->nextHandler)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- tempConnectivityHandlers->nextHandler = newHandler;
- OIC_LOG(DEBUG, MOD_NAME, "storeInterfaceCallbacks Exit in Sample");
-}
-
-void CAInterfaceRegisterCallback(CAConnectivityHandler_t handler,
- CAConnectivityType_t connType)
-{
- OIC_LOG(DEBUG, MOD_NAME, "interfaceRegisterCallback Entry in Sample");
- ConnectivityHandlerList *newConnectivityHandler = (ConnectivityHandlerList *) malloc(sizeof(
- ConnectivityHandlerList));
- if (NULL == newConnectivityHandler)
- {
- printf("Failed to allocate memory !\n");
- return;
- }
-
- newConnectivityHandler->type = connType;
- newConnectivityHandler->handler = handler;
- CAStoreInterfaceCallbacks(newConnectivityHandler);
- OIC_LOG(DEBUG, MOD_NAME, "interfaceRegisterCallback Exit in Sample");
-}
-
-void CANetworkPacketHandler(CARemoteEndpoint_t *object, void *data, uint32_t dataLength)
-{
- OIC_LOG(DEBUG, MOD_NAME, "networkPacketHandler Entry in Sample");
- if (object == NULL || data == NULL)
- {
- printf("\nNULL Object");
- return;
- }
-
- OIC_LOG(DEBUG, MOD_NAME, "Data Received from ");
- OIC_LOG_V(DEBUG, MOD_NAME, object->addressInfo.IP.ipAddress);
- OIC_LOG(DEBUG, MOD_NAME, "Received Data :");
- OIC_LOG_V(DEBUG, MOD_NAME, (char *)data);
- OIC_LOG(DEBUG, MOD_NAME, "networkPacketHandler Exit in Sample");
-}
-
-void CANetworkInterfaceCallback(CALocalConnectivity_t *localEndPoint,
- CANetworkStatus_t networkConnectivityState)
-{
- OIC_LOG(DEBUG, MOD_NAME, "networkInterfaceCallback Entry in Sample");
- if (localEndPoint == NULL)
- {
- OIC_LOG(DEBUG, MOD_NAME, "NULL Object");
- return;
- }
-
- OIC_LOG(DEBUG, MOD_NAME, "Local Interface Address: ");
- OIC_LOG(DEBUG, MOD_NAME, localEndPoint->addressInfo.IP.ipAddress);
-
- if (networkConnectivityState == CA_INTERFACE_UP)
- {
- OIC_LOG(DEBUG, MOD_NAME, " WiFi Network Status is UP");
- }
- else
- {
- OIC_LOG(DEBUG, MOD_NAME, " WiFi Network Status is DOWN");
- }
- OIC_LOG(DEBUG, MOD_NAME, "networkInterfaceCallback Exit in Sample");
-}
-
-
-void CAFreeData(void *data)
-{
- OIC_LOG(DEBUG, MOD_NAME, "freeData Entry in Sample");
- if (data)
- {
- free(data);
- }
- OIC_LOG(DEBUG, MOD_NAME, "freeData Exit in Sample");
-}
-
-int16_t CASelectConnectivityType()
-{
- int16_t cType;
- OIC_LOG(DEBUG, MOD_NAME, "*******Select the Connectivity Type*******");
- OIC_LOG(DEBUG, MOD_NAME, " [1] WiFi ");
- OIC_LOG(DEBUG, MOD_NAME, " [2] BT ");
- OIC_LOG(DEBUG, MOD_NAME, " [3] BLE ");
- cType = 1;
- return cType;
-}
-
-int16_t CAInterfaceStartServer(CAConnectivityType_t connType)
-{
- OIC_LOG(DEBUG, MOD_NAME, "interfaceStartServer Starting...");
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- OIC_LOG(DEBUG, MOD_NAME, "None of the interface is initialized");
- return 0;
- }
- while (tempConnectivityHandlers && tempConnectivityHandlers->type == connType)
- {
- if (connType == CA_WIFI)
- {
- OIC_LOG(DEBUG, MOD_NAME, "Connection Type = WiFi.");
- uint32_t size = 0;
- tempConnectivityHandlers->handler.GetnetInfo(&localWifiEndpoint, &size);
- OIC_LOG(DEBUG, MOD_NAME, "tempConnectivityHandlers ->NetInfoCallback");
- localWifiEndpoint->addressInfo.IP.port = 5683;
- OIC_LOG(DEBUG, MOD_NAME, "LocalWiFiEndPoint Port is 5683");
- OIC_LOG(DEBUG, MOD_NAME, "Local Address = ");
- OIC_LOG(DEBUG, MOD_NAME, localWifiEndpoint->addressInfo.IP.ipAddress);
- tempConnectivityHandlers->handler.startAdapter();
- tempConnectivityHandlers->handler.startDiscoverServer();
- }
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
- return true;
-}
-
-int16_t CAInterfaceStopServer(CAConnectivityType_t connType)
-{
- OIC_LOG(DEBUG, MOD_NAME, "interfaceStopServer Starting...");
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- OIC_LOG(DEBUG, MOD_NAME, "None of the interface is initialized");
- return 0;
- }
- while (tempConnectivityHandlers && tempConnectivityHandlers->type == connType)
- {
- tempConnectivityHandlers->handler.terminate();
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
- return true;
-}
-
-int16_t CAInterfaceSendUnicastData(CAConnectivityType_t connType)
-{
- OIC_LOG(DEBUG, MOD_NAME, "PLEASE ENTER THE IP ADDRESS ");
- while (!Serial.available());
- strncpy(readIpAddress, (Serial.readStringUntil('\n')).c_str(), 20);
- strncpy((char *)remoteEndpoint[0].addressInfo.IP.ipAddress, readIpAddress,
- strlen(readIpAddress));
- remoteEndpoint[0].addressInfo.IP.port = 5683;
-
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- OIC_LOG(DEBUG, MOD_NAME, " None of the interface is initialized ");
- return 0;
- }
- while (tempConnectivityHandlers && tempConnectivityHandlers->type == connType)
- {
- tempConnectivityHandlers->handler.sendData(&remoteEndpoint[0], coapData, strlen(coapData));
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
- return true;
-}
-
-int16_t CAInterfaceSendMulticastData(CAConnectivityType_t connType)
-{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- OIC_LOG(DEBUG, MOD_NAME, "None of the interface is initialized");
- return 0;
- }
- while (tempConnectivityHandlers && tempConnectivityHandlers->type == connType)
- {
- if (connType == CA_WIFI)
- {
- tempConnectivityHandlers->handler.sendDataToAll(coapData, strlen(coapData));
- }
- else if (connType == CA_EDR || connType == CA_LE)
- {
- //iterate all endpoints, check ConnectivityType for BT, BLE and call SendDataToAll
- }
-
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
- return true;
-}
-
-void CATestInitializeInterface()
-{
- OIC_LOG(DEBUG, MOD_NAME, "testInitializeInterface Entry");
- int16_t interface = CASelectConnectivityType();
- OIC_LOG_V(DEBUG, MOD_NAME, "Interface : %d", interface);
- if (interface == 0)
- {
- return;
- }
-
- if (1 == interface) /* WIFI */
- {
- CAInitializeWifi(CAInterfaceRegisterCallback, CANetworkPacketHandler,
- CANetworkInterfaceCallback);
- CAInterfaceStartServer(CA_WIFI);
- }
- else if (2 == interface) /*BT*/
- {
- }
- else if (3 == interface) /*BLE*/
- {
- }
-
- OIC_LOG(DEBUG, MOD_NAME, "testInitializeInterface Exit");
-}
-
-void CATestTerminateInterface()
-{
- int16_t interface = CASelectConnectivityType();
- if (interface == 0)
- {
- return;
- }
- if (1 == interface) /* WIFI */
- {
- CAInterfaceStopServer(CA_WIFI);
- //CATerminateWifi();
- }
- else if (2 == interface) /*BT*/
- {
- }
- else if (3 == interface) /*BLE*/
- {
- }
-
- /* Freeing the allocated Memory */
- //freeInterfaceMemory((void*)localWifiEndpoint->interface.address);
- //freeInterfaceMemory(localWifiEndpoint->endpoint_info);
- CAFreeData(localWifiEndpoint);
-}
-
-void CATestSendUnicastData()
-{
- int16_t interface = CASelectConnectivityType();
- if (interface == 0)
- {
- return;
- }
- if (1 == interface) /* WIFI */
- {
- CAInterfaceSendUnicastData(CA_WIFI);
- }
- else if (2 == interface) /*BT*/
- {
- }
- else if (3 == interface) /*BLE*/
- {
- }
-}
-
-void CATestSendMulticastData()
-{
- int16_t interface = CASelectConnectivityType();
- if (interface == 0)
- {
- return;
- }
-
- if (1 == interface) /* WIFI */
- {
- CAInterfaceSendMulticastData(CA_WIFI);
- }
- else if (2 == interface) /*BT*/
- {
- }
- else if (3 == interface) /*BLE*/
- {
- }
-}
-
-static void CATestPrintHelp(void)
-{
- OIC_LOG(DEBUG, MOD_NAME, " =====================================================================");
- OIC_LOG(DEBUG, MOD_NAME, "| Welcome to Connectivity Abstraction |");
- OIC_LOG(DEBUG, MOD_NAME, "| - CA Unit Test v1.0 - |");
- OIC_LOG(DEBUG, MOD_NAME, "|---------------------------------------------------------------------|");
- OIC_LOG(DEBUG, MOD_NAME, "| ** Options ** |");
- OIC_LOG(DEBUG, MOD_NAME, "| i - Initialize the Interface |");
- OIC_LOG(DEBUG, MOD_NAME, "| d - Terminate the Interface |");
- OIC_LOG(DEBUG, MOD_NAME, "| s - Send Unicast Data |");
- OIC_LOG(DEBUG, MOD_NAME, "| m - Send Multicast Data |");
- OIC_LOG(DEBUG, MOD_NAME, "| x - quit the test. |");
- OIC_LOG(DEBUG, MOD_NAME, "| r - Print the menu again. |");
- OIC_LOG(DEBUG, MOD_NAME, " =====================================================================");
-}
-
-void loop()
-{
- delay(2000);
- if (gConnectivityHandlers)
- {
- gConnectivityHandlers->handler.readData();
- }
- if (Serial.available() > 0)
- {
- OIC_LOG(DEBUG, MOD_NAME, "Serial available.");
- switch (Serial.read())
- {
- case 'i':
- OIC_LOG(DEBUG, MOD_NAME, "Initializing Interface.");
- CATestInitializeInterface();
- break;
- case 'x':
- OIC_LOG(DEBUG, MOD_NAME, "Terminating Interface.");
- CATestTerminateInterface();
- break;
- case 'd':
- OIC_LOG(DEBUG, MOD_NAME, "Terminating Interface.");
- CATestTerminateInterface();
- break;
- case 's':
- CATestSendUnicastData();
- break;
- case 'm':
- CATestSendMulticastData();
- break;
- case 'r':
- CATestPrintHelp();
- break;
- }
- }
-}
-
-void setup()
-{
- //OC_LOG_INIT();
- Serial.begin(115200);
- OIC_LOG(DEBUG, MOD_NAME, "Setup Started.");
- CAInterfaceInitializeEndpoint();
- OIC_LOG(DEBUG, MOD_NAME, "After initializing endpoints.");
- CATestPrintHelp();
-}
-
-#endif //#ifdef __ARDUINO_BLE__
+++ /dev/null
-/.objs/
-/out/
##
## compiler flags
##
-LIBS = -lconnectivity_abstraction -L$(PROJECT_OUT_PATH)
+LIBS = -L$(PROJECT_OUT_PATH) -lconnectivity_abstraction
CFLAGS = -g -c -Wall -fPIC
$(CC) -o $@ $(COMPONENT_OBJS) $(LIBS) $(LFLAGS)
@$(MV) $(TARGET) $(COMPONENT_OUT_PATH)/.
-clean :
+clean :
@$(RM) $(COMPONENT_OBJ_PATH) \
$(COMPONENT_OUT_PATH)
.PHONY: all clean install
+
-//----------------------------------------------------------------------
-// NOTICE - Transition to SCONS
-//----------------------------------------------------------------------
-
-The IoTivity build system is transitioning to SCONS. Although the
-makefiles are still available (until v1.0) and some developers are
-still using them, they are currently no longer supported. To learn more
-about building using SCONS see Readme.scons.txt in the repository root
-directory. The build steps used in continuous integration can be found
-in auto_build.sh which is also in the the repository root directory.
-
-//----------------------------------------------------------------------
#1. build "connectivity" project
- execute make command in "connectivity/build/" folder.
ex. $./sample.sh WITH_DTLS (This will make a clean build and execute application)
+
print "Reading sample application build script"
build_dir = sample_env.get('BUILD_DIR')
-sample_dir = './samples/linux/'
+sample_dir = './samples/linux/'
secured = sample_env.get('SECURED')
-print "Sample secured flag is %s" % secured
+print "Sample secured flag is %s" % secured
sample_src = ['./sample_main.c',]
print " sample src %s" % sample_src
+
cd out
LD_LIBRARY_PATH=../../../build/out ./sample_main
+
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
+#include <stdbool.h>
+
#include "cacommon.h"
#include "cainterface.h"
#ifdef __WITH_DTLS__
#define MAX_BUF_LEN 1024
#define MAX_OPT_LEN 16
-#define TRUE 1
-#define FALSE 0
+
+#define PORT_LENGTH 5
+
+#define SECURE_DEFAULT_PORT 5684
/**
* @def RS_IDENTITY
*/
#define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
-
-int gReceived;
-CABool_t gLocalUnicastPort;
-CABool_t gLocalSecurePort;
-CAConnectivityType_t gSelectedNwType = CA_ETHERNET;
-const char* gMessageType[] = {"CON", "NON", "ACK", "RESET"};
+int g_received;
+uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
+CAConnectivityType_t g_selected_nw_type = CA_ETHERNET;
+const char* MESSAGE_TYPE[] = {"CON", "NON", "ACK", "RESET"};
char get_menu();
void process();
CAResult_t get_network_type();
+CAResult_t get_input_data(char *buf, int32_t length);
void start_listening_server();
void start_discovery_server();
void find_resource();
void send_request();
void send_request_all();
+void send_response();
void advertise_resource();
void send_notification();
void select_network();
void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token);
-void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info);
void get_resource_uri(char *URI, char *resourceURI, int length);
int get_secure_information(CAPayload_t payLoad);
-static CAToken_t gLastRequestToken = NULL;
-static const char *gSecureInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+static CAToken_t g_last_request_token = NULL;
+static const char SECURE_COAPS_PREFIX[] = "coaps://";
+static const char SECURE_INFO_DATA[] =
+ "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
"\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
-static const char *gNormalInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+static const char NORMAL_INFO_DATA[] =
+ "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
"\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
#ifdef __WITH_DTLS__
printf("clearDtlsCredentialInfo IN\n");
if (pskCredsBlob)
{
- // Zero out sensitive data before freeing.
- if (pskCredsBlob->num)
- {
- memset(pskCredsBlob, 0,
- sizeof(OCDtlsPskCredsBlob) + (sizeof(OCDtlsPskCreds)*(pskCredsBlob->num - 1)));
- }
+ // Initialize sensitive data to zeroes before freeing.
+ memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+ free(pskCredsBlob->creds);
+
+ memset(pskCredsBlob, 0, sizeof(OCDtlsPskCredsBlob));
free(pskCredsBlob);
pskCredsBlob = NULL;
}
}
// Internal API. Invoked by OC stack to retrieve credentials from this module
-void OCGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo)
-{
- printf("OCGetDtlsPskCredentials IN\n");
-
- *credInfo = pskCredsBlob;
-
- printf("OCGetDtlsPskCredentials OUT\n");
-}
-// Internal API. Invoked by OC stack to retrieve credentials from this module
void CAGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo)
{
printf("CAGetDtlsPskCredentials IN\n");
- *credInfo = pskCredsBlob;
+ if (pskCredsBlob != NULL)
+ {
+ *credInfo = pskCredsBlob;
+ }
printf("CAGetDtlsPskCredentials OUT\n");
}
+
int32_t SetCredentials()
{
printf("SetCredentials IN\n");
- pskCredsBlob = (OCDtlsPskCredsBlob *)malloc(sizeof(OCDtlsPskCredsBlob));
-
- memset(pskCredsBlob, 0x0, sizeof(OCDtlsPskCredsBlob));
+ pskCredsBlob = (OCDtlsPskCredsBlob *)calloc(1, sizeof(OCDtlsPskCredsBlob));
+ if (NULL == pskCredsBlob)
+ {
+ printf("Memory allocation failed!\n");
+ return -1;
+ }
memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
pskCredsBlob->num = 1;
pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+ if (NULL == pskCredsBlob->creds)
+ {
+ printf("Memory allocation failed!\n");
+ return -1;
+ }
memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
if (SetCredentials() == 0)
{
printf("SetCredentials failed\n");
- return 0;
+ return -1;
}
res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
if(res != CA_STATUS_OK)
{
printf("Set credential handler fail\n");
- return 0;
+ return -1;
}
#endif
res = CAInitialize();
if (res != CA_STATUS_OK)
{
printf("CAInitialize fail\n");
- return 0;
- }
-
-#if 0
- // network enable
- // default
- printf("select default network(WIFI)\n");
- res = CASelectNetwork(CA_WIFI);
- if (res != CA_STATUS_OK)
- {
- printf("CASelectNetwork fail\n");
- return 0;
+ return -1;
}
-#endif
// set handler.
CARegisterHandler(request_handler, response_handler);
process();
- if (gLastRequestToken != NULL)
- {
- CADestroyToken(gLastRequestToken);
- }
- gLastRequestToken = NULL;
+ CADestroyToken(g_last_request_token);
+
+ g_last_request_token = NULL;
CATerminate();
#ifdef __WITH_DTLS__
{
case 'm': // menu
case 'M':
- continue;
+ break;
case 'q': // quit
case 'Q':
break;
case 'c': // start client
- case 'D':
+ case 'C':
start_discovery_server();
break;
case 'H':
handle_request_response();
break;
+
case 'y':
case 'Y':
while (1)
{
- gReceived = 0;
+ g_received = 0;
find_fixed_resource();
- while (gReceived == 0)
+ while (g_received == 0)
{
sleep(1);
handle_request_response();
case 'w':
case 'W':
- gReceived = 0;
+ g_received = 0;
start_discovery_server();
send_secure_request();
- while (gReceived == 0)
+ while (g_received == 0)
{
sleep(1);
handle_request_response();
}
-
break;
case 'z':
break;
}
}
-
}
-
-
void start_listening_server()
{
printf("start listening server!!\n");
CAResult_t res = CAStartListeningServer();
if (res != CA_STATUS_OK)
{
- printf("start listening server fail\n");
+ printf("start listening server fail, error code : %d\n", res);
}
else
{
CAResult_t res = CAStartDiscoveryServer();
if (res != CA_STATUS_OK)
{
- printf("start discovery client fail\n");
+ printf("start discovery client fail, error code : %d\n", res);
}
else
{
void find_fixed_resource()
{
- char buf[MAX_BUF_LEN] =
- { 0, };
+ char buf[MAX_BUF_LEN] = { 0 };
strcpy(buf, "/a/light");
// create token
if (res != CA_STATUS_OK)
{
printf("token generate error!!");
- token = NULL;
+ return;
}
printf("generated token %s\n", (token != NULL) ? token : "");
res = CAFindResource(buf, token);
if (res != CA_STATUS_OK)
{
- printf("find resource error!!\n");
+ printf("find resource error : %d\n", res);
}
else
{
}
// delete token
- /*
- if (token != NULL)
- {
- CADestroyToken(token);
- }
- */
+ CADestroyToken(token);
printf("=============================================\n");
}
void find_resource()
{
- char buf[MAX_BUF_LEN];
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = { 0 };
printf("\n=============================================\n");
printf("ex) /a/light\n");
printf("reference uri : ");
- if(gets(buf) == NULL)
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
return;
+ }
// create token
CAToken_t token = NULL;
if (res != CA_STATUS_OK)
{
printf("token generate error!!\n");
- token = NULL;
+ return;
}
printf("generated token %s\n", (token != NULL) ? token : "");
res = CAFindResource(buf, token);
if (res != CA_STATUS_OK)
{
- printf("find resource error!!\n");
+ printf("find resource error : %d\n", res);
}
else
{
printf("find resource to %s URI\n", buf);
- if (gLastRequestToken != NULL)
+ if (g_last_request_token != NULL)
{
- CADestroyToken(gLastRequestToken);
+ CADestroyToken(g_last_request_token);
}
- gLastRequestToken = token;
+ g_last_request_token = token;
}
- // delete token
- /*
- if (token != NULL)
- {
- CADestroyToken(token);
- }
- */
-
printf("=============================================\n");
}
void send_request()
{
- char secureRequest[2] = {0};
+ char secureRequest[MAX_BUF_LEN] = {0};
CAResult_t res;
res = get_network_type();
}
printf("Do you want to send secure request ?.... enter (0/1): ");
- if( gets(secureRequest) == NULL)
+ if (CA_STATUS_OK != get_input_data(secureRequest, MAX_BUF_LEN))
+ {
return;
- if ('1' == secureRequest[0])
+ }
+
+ if (strcmp(secureRequest, "1") == 0)
{
printf("Enter the URI like below....\n");
printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
}
- else
+ else if (strcmp(secureRequest, "0") == 0)
{
printf("Enter the URI like below....\n");
printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
}
+ else
+ {
+ printf("input data is wrong value\n");
+ return;
+ }
char uri[MAX_BUF_LEN] = {'\0'};
- if( gets(uri) == NULL)
- return ;
+
+ if (CA_STATUS_OK != get_input_data(uri, MAX_BUF_LEN))
+ {
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
- if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, gSelectedNwType, &endpoint)
- || !endpoint)
+ res = CACreateRemoteEndpoint(uri, g_selected_nw_type, &endpoint);
+ if (CA_STATUS_OK != res || !endpoint)
{
- printf("Failed to create remote endpoint!\n");
+ printf("Failed to create remote endpoint, error code : %d\n", res);
CADestroyRemoteEndpoint(endpoint);
return;
}
- //endpoint->connectivityType = gSelectedNwType;
-
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = { 0 };
printf("\n=============================================\n");
printf("0:CON, 1:NON\n");
printf("select message type : ");
- if( gets(buf) == NULL)
- return ;
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
+ return;
+ }
- CAMessageType_t msgType = (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0;
+ CAMessageType_t msgType = (buf[0] == '1') ? 1 : 0;
// create token
CAToken_t token = NULL;
- if (CA_STATUS_OK != CAGenerateToken(&token))
+ res = CAGenerateToken(&token);
+ if (CA_STATUS_OK != res)
{
- printf("token generate error!!\n");
- token = NULL;
+ printf("token generate error, error code : %d\n", res);
+ return;
}
printf("generated token %s\n", (token != NULL) ? token : "");
get_resource_uri(uri, resourceURI, 14);
// create request data
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ CAInfo_t requestData = { 0 };
requestData.token = token;
- if ('1' == secureRequest[0])
+ if (strcmp(secureRequest, "1") == 0)
{
- int length = strlen(gSecureInfoData) + strlen(resourceURI) + 1;
- requestData.payload = (CAPayload_t) malloc(length);
- sprintf(requestData.payload, gSecureInfoData, resourceURI, gLocalSecurePort);
+ int length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
+ requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ if (requestData.payload == NULL)
+ {
+ printf("memory alloc fail\n");
+ return;
+ }
+ snprintf(requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_local_secure_port);
}
else
{
- int length = strlen(gNormalInfoData) + strlen(resourceURI) + 1;
- requestData.payload = (CAPayload_t) malloc(length);
- sprintf(requestData.payload, gNormalInfoData, resourceURI);
+ int length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
+ requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ if (requestData.payload == NULL)
+ {
+ printf("memory alloc fail\n");
+ return;
+ }
+ snprintf(requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
}
requestData.type = msgType;
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
requestInfo.info = requestData;
// send request
CASendRequest(endpoint, &requestInfo);
- if (token != NULL)
- {
- CADestroyToken(token);
- }
- if (requestData.payload != NULL)
- {
- free(requestData.payload);
- }
+ CADestroyToken(token);
+
+ free(requestData.payload);
+
// destroy remote endpoint
CADestroyRemoteEndpoint(endpoint);
+
printf("=============================================\n");
}
void send_secure_request()
{
+ CAResult_t res;
char uri[MAX_BUF_LEN];
char ipv4addr[CA_IPADDR_SIZE];
printf("\n=============================================\n");
printf("Enter IPv4 address of the source hosting secure resource (Ex: 11.12.13.14)\n");
- fgets(ipv4addr, CA_IPADDR_SIZE, stdin);
- snprintf(uri, MAX_BUF_LEN, "coaps://%s:5684/a/light", ipv4addr);
+ if (CA_STATUS_OK != get_input_data(ipv4addr, CA_IPADDR_SIZE))
+ {
+ return;
+ }
+ snprintf(uri, MAX_BUF_LEN, "%s%s:5684/a/light", SECURE_COAPS_PREFIX, ipv4addr);
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
- if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, CA_ETHERNET, &endpoint))
+ res = CACreateRemoteEndpoint(uri, CA_ETHERNET, &endpoint);
+ if (CA_STATUS_OK != res)
{
- printf("Failed to create remote endpoint!\n");
+ printf("Failed to create remote endpoint, error code: %d\n", res);
goto exit;
}
// create request data
CAMessageType_t msgType = CA_MSG_NONCONFIRM;
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ CAInfo_t requestData = { 0 };
requestData.token = token;
requestData.type = msgType;
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
requestInfo.info = requestData;
void send_request_all()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = { 0 };
CAResult_t res;
printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
printf("uri : ");
- if( gets(buf) == NULL)
- return ;
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(buf, gSelectedNwType, &endpoint);
+ res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
if (res != CA_STATUS_OK)
{
- printf("create remote endpoint error!!\n");
+ printf("create remote endpoint error, error code: %d\n", res);
CADestroyRemoteEndpoint(endpoint);
return;
}
-
- CAGroupEndpoint_t *group = NULL;
- group = (CAGroupEndpoint_t *)malloc(sizeof(CAGroupEndpoint_t));
+ CAGroupEndpoint_t *group = (CAGroupEndpoint_t *)malloc(sizeof(CAGroupEndpoint_t));
+ if (NULL == group)
+ {
+ printf("Memory allocation failed!\n");
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
group->connectivityType = endpoint->connectivityType;
group->resourceUri = endpoint->resourceUri;
-
// create token
CAToken_t token = NULL;
res = CAGenerateToken(&token);
if (res != CA_STATUS_OK)
{
printf("token generate error!!\n");
- token = NULL;
+ return;
}
printf("generated token %s\n", (token != NULL) ? token : "");
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ CAInfo_t requestData = { 0 };
requestData.token = token;
requestData.payload = "Temp Json Payload";
- requestData.type = CA_MSG_NONCONFIRM;
+ requestData.type = CA_MSG_NONCONFIRM;
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ CARequestInfo_t requestInfo = { 0 };
requestInfo.method = CA_GET;
requestInfo.info = requestData;
// send request
- // CASendRequest(endpoint, &requestInfo);
CASendRequestToAll(group, &requestInfo);
- if (token != NULL)
- {
- CADestroyToken(token);
- }
+ CADestroyToken(token);
// destroy remote endpoint
- if (endpoint != NULL)
- {
- CADestroyRemoteEndpoint(endpoint);
- }
+ CADestroyRemoteEndpoint(endpoint);
free(group);
void advertise_resource()
{
- char buf[MAX_BUF_LEN];
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = { 0 };
printf("\n=============================================\n");
printf("uri : ");
- scanf("%s", buf);
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
+ return;
+ }
int optionNum = 0;
- char optionData[MAX_OPT_LEN];
+ char optionNumBuf[MAX_BUF_LEN] = { 0 };
+ char optionData[MAX_OPT_LEN] = { 0 } ;
printf("Option Num : ");
- scanf("%d", &optionNum);
+ if (CA_STATUS_OK != get_input_data(optionNumBuf, MAX_BUF_LEN))
+ {
+ return;
+ }
+
+ optionNum = atoi(optionNumBuf);
+
CAHeaderOption_t *headerOpt;
- headerOpt = (CAHeaderOption_t *) malloc(sizeof(CAHeaderOption_t) * optionNum);
+ headerOpt = (CAHeaderOption_t *) calloc(1, optionNum * sizeof(CAHeaderOption_t));
if (NULL == headerOpt)
{
printf("Memory allocation failed!\n");
return;
}
- memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
int i;
for (i = 0; i < optionNum; i++)
{
int optionID = 0;
+ char getOptionID[MAX_BUF_LEN] = { 0 } ;
+
printf("[%d] Option ID : ", i + 1);
- scanf("%d", &optionID);
+ if (CA_STATUS_OK != get_input_data(getOptionID, MAX_BUF_LEN))
+ {
+ return;
+ }
+ optionID = atoi(getOptionID);
+
headerOpt[i].optionID = optionID;
- memset(optionData, 0, sizeof(char) * MAX_OPT_LEN);
printf("[%d] Option Data : ", i + 1);
- scanf("%s", optionData);
+ if (CA_STATUS_OK != get_input_data(optionData, MAX_OPT_LEN))
+ {
+ return;
+ }
+
memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
{
printf("token generate error!!\n");
token = NULL;
+ return;
}
printf("generated token %s\n", (token != NULL) ? token : "");
CAAdvertiseResource(buf, token, headerOpt, (uint8_t) optionNum);
// delete token
- if (token != NULL)
- {
- CADestroyToken(token);
- }
+ CADestroyToken(token);
free(headerOpt);
-
}
void send_notification()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = { 0 };
CAResult_t res;
}
printf("\n=============================================\n");
+ printf("Enter the URI like below....\n");
printf("10.11.12.13:4545/resource_uri ( for IP )\n");
printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
printf("uri : ");
- if( gets(buf) == NULL)
- return ;
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(buf, gSelectedNwType, &endpoint);
+ res = CACreateRemoteEndpoint(buf, g_selected_nw_type, &endpoint);
if (res != CA_STATUS_OK)
{
- printf("create remote endpoint error!!\n");
+ printf("create remote endpoint error, error code: %d\n", res);
CADestroyRemoteEndpoint(endpoint);
return;
}
- CAInfo_t respondeData;
- memset(&respondeData, 0, sizeof(CAInfo_t));
- respondeData.token = "client token";
- respondeData.payload = "Temp Notification Data";
+ CAInfo_t respondData = { 0 };
+ respondData.token = "client token";
+ respondData.payload = "Temp Notification Data";
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ CAResponseInfo_t responseInfo = { 0 };
responseInfo.result = CA_SUCCESS;
- responseInfo.info = respondeData;
+ responseInfo.info = respondData;
// send request
res = CASendNotification(endpoint, &responseInfo);
if (res != CA_STATUS_OK)
{
- printf("send notification error\n");
+ printf("send notification error, error code: %d\n", res);
}
else
{
}
// destroy remote endpoint
- if (endpoint != NULL)
- {
- CADestroyRemoteEndpoint(endpoint);
- }
+ CADestroyRemoteEndpoint(endpoint);
printf("\n=============================================\n");
}
void select_network()
{
- char buf[MAX_BUF_LEN];
+ char buf[MAX_BUF_LEN] = { 0 };
printf("\n=============================================\n");
printf("\tselect network\n");
printf("LE : 3\n");
printf("select : ");
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- if( gets(buf) == NULL)
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
return;
+ }
int number = buf[0] - '0';
- number = (number < 0 || number > 3) ? 0 : number;
+ if (number < 0 || number > 3)
+ {
+ printf("invalid network type\n");
+ return;
+ }
CAResult_t res = CASelectNetwork(1 << number);
if (res != CA_STATUS_OK)
{
printf("select network error\n");
- gSelectedNwType = 1 << number;
+ g_selected_nw_type = 1 << number;
}
else
{
void unselect_network()
{
- char buf[MAX_BUF_LEN];
+ char buf[MAX_BUF_LEN] = { 0 };
printf("\n=============================================\n");
printf("\tunselect enabled network\n");
printf("LE : 3\n");
printf("select : ");
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- if( gets(buf) == NULL)
- return ;
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
+ return;
+ }
int number = buf[0] - '0';
- number = (number < 0 || number > 3) ? 1 : number;
+ if (number < 0 || number > 3)
+ {
+ printf("invalid network type\n");
+ return;
+ }
CAResult_t res = CAUnSelectNetwork(1 << number);
if (res != CA_STATUS_OK)
char get_menu()
{
- char buf[MAX_BUF_LEN];
+ char buf[MAX_BUF_LEN] = { 0 };
printf("\n=============================================\n");
printf("\t\tMenu\n");
printf("=============================================\n");
printf("select : ");
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- if( gets(buf) == NULL)
- return 'q';
+ get_input_data(buf, MAX_BUF_LEN);
return buf[0];
}
CAResult_t res = CAHandleRequestResponse();
if (res != CA_STATUS_OK)
{
- printf("handle request error\n");
+ printf("handle request error, error code: %d\n", res);
}
else
{
printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
printf("Secured: %d\n\n", tempInfo[index].isSecured);
- if (CA_TRUE == tempInfo[index].isSecured)
+ if (tempInfo[index].isSecured)
{
- gLocalSecurePort = tempInfo[index].addressInfo.IP.port;
- }
- else
- {
- gLocalUnicastPort = tempInfo[index].addressInfo.IP.port;
+ g_local_secure_port = tempInfo[index].addressInfo.IP.port;
}
}
object->addressInfo.IP.port, object->isSecured);
printf("Data: %s\n", requestInfo->info.payload);
- printf("Message type: %s\n", gMessageType[requestInfo->info.type]);
- if (gLastRequestToken != NULL && requestInfo->info.token != NULL
- && (strcmp((char *)gLastRequestToken, requestInfo->info.token) == 0))
+ printf("Message type: %s\n", MESSAGE_TYPE[requestInfo->info.type]);
+ if (g_last_request_token != NULL && requestInfo->info.token != NULL
+ && (strcmp((char *)g_last_request_token, requestInfo->info.token) == 0))
{
printf("token is same. received request of it's own. skip.. \n");
return;
char *uri = NULL;
int length = 0;
- length = 8; //length of "coaps://"
- length += strlen(object->addressInfo.IP.ipAddress) + 5; // length of "ipaddress:port"
+ //length of "coaps://"
+ length = sizeof(SECURE_COAPS_PREFIX) - 1;
+
+ // length of "ipaddress:port"
+ length += strlen(object->addressInfo.IP.ipAddress) + PORT_LENGTH;
length += strlen(object->resourceUri) + 1;
uri = calloc(1, sizeof(char) * length);
printf("Failed to create new uri\n");
return;
}
- sprintf(uri, "coaps://%s:%d/%s", object->addressInfo.IP.ipAddress,
+ sprintf(uri, "%s%s:%d/%s", SECURE_COAPS_PREFIX, object->addressInfo.IP.ipAddress,
securePort, object->resourceUri);
CARemoteEndpoint_t *endpoint = NULL;
printf("Failed to create duplicate of remote endpoint!\n");
return;
}
- //endpoint->connectivityType = object->connectivityType;
- endpoint->isSecured = CA_TRUE;
+ endpoint->isSecured = true;
object = endpoint;
free(uri);
printf("send response with URI\n");
send_response(object, &requestInfo->info);
- gReceived = 1;
+ g_received = 1;
}
void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
object->addressInfo.IP.port, object->isSecured);
printf("response result : %d\n", responseInfo->result);
printf("Data: %s\n", responseInfo->info.payload);
- printf("Message type: %s\n", gMessageType[responseInfo->info.type]);
- printf("Token: %s\n", responseInfo->info.token);
+ printf("Message type: %s\n", MESSAGE_TYPE[responseInfo->info.type]);
if (responseInfo->info.options)
{
uint32_t len = responseInfo->info.numOptions;
}
}
printf("############################################################\n");
- gReceived = 1;
+ g_received = 1;
//Check if this has secure communication information
if (responseInfo->info.payload)
void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
{
- char buf[MAX_BUF_LEN];
-
printf("entering send_response\n");
- printf("\n=============================================\n");
- printf("\tselect message type\n");
- printf("CA_MSG_CONFIRM : 0\n");
- printf("CA_MSG_NONCONFIRM : 1\n");
- printf("CA_MSG_ACKNOWLEDGE : 2\n");
- printf("CA_MSG_RESET : 3\n");
- printf("select : ");
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- gets(buf);
-
- int messageType = buf[0] - '0';
- int responseCode = 231 ;
- if(messageType != 3)
- {
-
- printf("\n=============================================\n");
- printf("\tselect response code\n");
- printf("CA_SUCCESS : 200\n");
- printf("CA_CREATED : 201\n");
- printf("CA_DELETED : 202\n");
- printf("CA_EMPTY : 231\n");
- printf("CA_BAD_REQ : 400\n");
- printf("CA_BAD_OPT : 402\n");
- printf("CA_NOT_FOUND : 404\n");
- printf("CA_RETRANSMIT_TIMEOUT : 531\n");
- printf("select : ");
- scanf("%d", &responseCode);
- }
- CAInfo_t responseData;
- memset(&responseData, 0, sizeof(CAInfo_t));
- responseData.type = messageType;
+ CAInfo_t responseData = { 0 };
+ responseData.type =
+ (info != NULL) ?
+ ((info->type == CA_MSG_CONFIRM) ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM) :
+ CA_MSG_NONCONFIRM;
responseData.messageId = (info != NULL) ? info->messageId : 0;
- if(messageType != 3)
- {
- responseData.token = (info != NULL) ? info->token : "";
- responseData.payload = "response payload";
- }
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = responseCode;
+ responseData.token = (info != NULL) ? info->token : "";
+ responseData.payload = "response payload";
+
+ CAResponseInfo_t responseInfo = { 0 };
+ responseInfo.result = 203;
responseInfo.info = responseData;
- if (CA_TRUE == endpoint->isSecured)
+ if (endpoint->isSecured)
printf("Sending response on secure communication\n");
else
printf("Sending response on non-secure communication\n");
// send request (connectivityType from remoteEndpoint of request Info)
CAResult_t res = CASendResponse(endpoint, &responseInfo);
if (res != CA_STATUS_OK)
-{
+ {
printf("send response error\n");
}
else
printf("=============================================\n");
}
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token)
-{
-
- printf("\n=============================================\n");
-
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
- requestData.token = token;
- requestData.payload = "Temp Json Payload";
-
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
- requestInfo.method = CA_GET;
- requestInfo.info = requestData;
-
- // send request
- endpoint->connectivityType = CA_WIFI;
-
- CAResult_t res = CASendRequest(endpoint, &requestInfo);
- if (res != CA_STATUS_OK)
- {
- printf("send request error\n");
- }
- else
- {
- printf("send request success\n");
- }
-
- printf("=============================================\n");
-
-}
-
int get_secure_information(CAPayload_t payLoad)
{
printf("entering get_secure_information\n");
CAResult_t get_network_type()
{
- char buf[MAX_BUF_LEN];
+ char buf[MAX_BUF_LEN] = { 0 };
printf("\n=============================================\n");
printf("\tselect network type\n");
printf("LE : 3\n");
printf("select : ");
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- if( gets(buf) == NULL)
+ if (CA_STATUS_OK != get_input_data(buf, MAX_BUF_LEN))
+ {
return CA_NOT_SUPPORTED ;
+ }
int number = buf[0] - '0';
}
if (number & CA_ETHERNET)
{
- gSelectedNwType = CA_ETHERNET;
+ g_selected_nw_type = CA_ETHERNET;
return CA_STATUS_OK;
}
if (number & CA_WIFI)
{
- gSelectedNwType = CA_WIFI;
+ g_selected_nw_type = CA_WIFI;
return CA_STATUS_OK;
}
if (number & CA_EDR)
{
- gSelectedNwType = CA_EDR;
+ g_selected_nw_type = CA_EDR;
return CA_STATUS_OK;
}
if (number & CA_LE)
{
- gSelectedNwType = CA_LE;
+ g_selected_nw_type = CA_LE;
return CA_STATUS_OK;
}
return CA_STATUS_FAILED;
}
+
+CAResult_t get_input_data(char *buf, int32_t length)
+{
+ char *p;
+
+ if(!fgets(buf, length, stdin))
+ {
+ printf("fgets error\n");
+ return CA_STATUS_FAILED;
+ }
+
+ if( (p=strchr(buf, '\n')) != NULL )
+ {
+ *p = '\0';
+ }
+
+ return CA_STATUS_OK;
+}
OUT = threadpool
-all:
+all:
$(CC) $(CFLAGS) $(INC_DIR) $(COMPILEFLAGS) $(SRC_DIR)uthreadpool.c $(SRC_DIR)umutex.c $(SRC_DIR)/logger.c $(SRC_DIR)/oic_malloc.c main.c -o $(OUT) $(LDFLAGS)
clean:
rm -f $(OUT)
+
#include "uthreadpool.h"
#include "umutex.h"
-u_thread_pool_t gThreadPoolHandle = NULL;
+u_thread_pool_t g_threadPoolHandle = NULL;
-u_mutex gMutex = NULL;
-u_cond gCond = NULL;
+u_mutex g_mutex = NULL;
+u_cond g_cond = NULL;
+bool g_condFlag = false;
void task(void *data)
{
//Signal the condition that task has been completed
printf("[TASK] Signaling the condition\n");
- u_cond_signal(gCond);
+ u_mutex_lock(g_mutex);
+ g_condFlag = true;
+ u_cond_signal(g_cond);
+ u_mutex_unlock(g_mutex);
}
void testThreadPool(void)
//Initialize the mutex
printf("[testThreadPool] Initializing mutex\n");
- u_mutex_init();
//Initialize the thread pool
printf("[testThreadPool] Initializing thread pool\n");
- if (CA_STATUS_OK != u_thread_pool_init(2, &gThreadPoolHandle))
+ if (CA_STATUS_OK != u_thread_pool_init(2, &g_threadPoolHandle))
{
printf("thread_pool_init failed!\n");
return;
//Create the mutex
printf("[testThreadPool] Creating mutex\n");
- gMutex = u_mutex_new();
- if (NULL == gMutex)
+ g_mutex = u_mutex_new();
+ if (NULL == g_mutex)
{
printf("[testThreadPool] Failed to create mutex!\n");
- u_thread_pool_free(gThreadPoolHandle);
+ u_thread_pool_free(g_threadPoolHandle);
return;
}
//Create the condition
printf("[testThreadPool] Creating Condition\n");
- gCond = u_cond_new();
- if (NULL == gCond)
+ g_cond = u_cond_new();
+ if (NULL == g_cond)
{
printf("[testThreadPool] Failed to create condition!\n");
- u_thread_pool_free(gThreadPoolHandle);
- u_mutex_free(gMutex);
+ u_mutex_free(g_mutex);
+ u_thread_pool_free(g_threadPoolHandle);
return;
}
//Lock the mutex
printf("[testThreadPool] Locking the mutex\n");
- u_mutex_lock(gMutex);
+ u_mutex_lock(g_mutex);
+ g_condFlag = false;
//Add task to thread pool
printf("[testThreadPool] Adding the task to thread pool\n");
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPoolHandle, task, (void *) string))
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPoolHandle, task, (void *) string))
{
printf("[testThreadPool] thread_pool_add_task failed!\n");
- u_thread_pool_free(gThreadPoolHandle);
- u_mutex_unlock(gMutex);
- u_mutex_free(gMutex);
- u_cond_free(gCond);
+ u_thread_pool_free(g_threadPoolHandle);
+ u_mutex_unlock(g_mutex);
+ u_mutex_free(g_mutex);
+ u_cond_free(g_cond);
return;
}
//Wait for the task to be executed
printf("[testThreadPool] Waiting for the task to be completed\n");
- u_cond_wait(gCond, gMutex);
+
+ while (!g_condFlag)
+ {
+ u_cond_wait(g_cond, g_mutex);
+ }
//Unlock the mutex
printf("[testThreadPool] Got the signal and unlock the mutex\n");
- u_mutex_unlock(gMutex);
+ u_mutex_unlock(g_mutex);
printf("[testThreadPool] Task is completed and terminating threadpool\n");
- u_mutex_free(gMutex);
- u_cond_free(gCond);
- u_thread_pool_free(gThreadPoolHandle);
+ u_cond_free(g_cond);
+ u_mutex_free(g_mutex);
+ u_thread_pool_free(g_threadPoolHandle);
printf("Exiting from testThreadPool\n");
}
while (1)
{
int choice = -1;
- scanf("%d", &choice);
-
- switch (choice)
+ if(scanf("%d", &choice) == 1)
{
- case 0:
- printf("Terminating test.....\n");
- return;
- case 1:
- testThreadPool();
- break;
- default:
- printf("Invalid input...\n");
- menu();
- break;
+ switch (choice)
+ {
+ case 0:
+ printf("Terminating test.\n");
+ return;
+ case 1:
+ testThreadPool();
+ break;
+ default:
+ printf("Invalid input.\n");
+ menu();
+ break;
+ }
}
+ else
+ {
+ printf("Invalid input.\n");
+ menu();
+ }
+
+ // clear input buffer
+ while (getchar() != '\n');
}
}
startTesting();
return 0;
}
+
CFLAGS=$(INC_DIRS) -DWITH_POSIX -D__TIZEN__ $(ADAPTER_MACRO)
COMPILEFLAG = `pkg-config --cflags --libs com.oic.ca capi-network-wifi gobject-2.0 glib-2.0 dlog capi-network-bluetooth`
-OBJECTS := interfacesample.o casample.o
+OBJECTS := casample.o
all: $(OBJECTS)
- $(CC) interfacesample.o -o interface_sample /usr/lib/liboicinterface.a -lm -lpthread -lrt -ldl -lstdc++ -lgobject-2.0 -lgio-2.0 -lglib-2.0 -lcapi-network-wifi -ldlog -lcapi-network-bluetooth
$(CC) casample.o -o ca_sample /usr/lib/liboicinterface.a -lm -lpthread -lrt -ldl -lstdc++ -lgobject-2.0 -lgio-2.0 -lglib-2.0 -lcapi-network-wifi -ldlog -lcapi-network-bluetooth
-interfacesample.o: interfacesample.c
- $(CC) $(CFLAGS) $(COMPILEFLAG) -c interfacesample.c -o interfacesample.o
casample.o: casample.c
$(CC) $(CFLAGS) $(COMPILEFLAG) -c casample.c -o casample.o
pack:
#cp -rf sample ./usr/apps/com.samsung.oicca/bin/sample
clean:
- rm -rf *.o interface_sample
rm -rf *.o ca_sample
else ifeq ($(PLATFORM),arduinodue)
$(info *********error**********)
$(error Wrong value for PLATFORM !!)
endif
+
(v) Turn on the Bluetooth.
5) Run the sample as given in Step 8 of "Procedure to Execute Sample App"
+
######################################################################
if target_os == "yocto":
'''
- This code injects Yocto cross-compilation tools+flags into scons'
- build environment in order to invoke the relevant tools while
+ This code injects Yocto cross-compilation tools+flags into scons'
+ build environment in order to invoke the relevant tools while
performing a build.
'''
import os.path
env['TARGET_OS'] = 'linux'
'''
We want to preserve debug symbols to allow BitBake to generate both DEBUG and
- RELEASE packages for OIC.
+ RELEASE packages for OIC.
'''
env['CCFLAGS'].append('-g')
Export('env')
Execute(Delete(dir + '/.sconf_temp'))
Return('env')
+
SConscript('scons/SConscript')
else:
print "Given platform is not supported"
+
#include "cacommon.h"
#include "cainterface.h"
-static GMainLoop *mainloop;
+static GMainLoop *mainloop = NULL;
pthread_t thread;
#define MAX_BUF_LEN 1024
#define MAX_OPT_LEN 16
-#define TRUE 1
-#define FALSE 0
+
/**
* @def RS_IDENTITY
#define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
-int gReceived;
-CABool_t gLocalUnicastPort;
-CABool_t gLocalSecurePort;
-CAConnectivityType_t gSelectedNwType = CA_ETHERNET;
-const char* gMessageType[] = {"CON", "NON", "ACK", "RESET"};
-
-char get_menu();
-void process();
-CAResult_t get_network_type();
-
-CAResult_t initialize();
-void start_listening_server();
-void start_discovery_server();
-void find_resource();
-void send_request();
-void send_request_all();
-void send_response();
-void advertise_resource();
-void send_notification();
-void select_network();
-void unselect_network();
-void handle_request_response();
-void find_fixed_resource();
-void get_network_info();
-
-void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
-void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token);
-void get_resource_uri(char *URI, char *resourceURI, int length);
-int get_secure_information(CAPayload_t payLoad);
-
-static CAToken_t gLastRequestToken = NULL;
-static const char *gSecureInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+int g_received = 0;
+int g_localUnicastPort = 0;
+int g_localSecurePort = 0;
+CAConnectivityType_t g_selectedNwType = CA_ETHERNET;
+const char* g_messageType[] = {"CON", "NON", "ACK", "RESET"};
+
+char PrintOptions();
+void Process();
+CAResult_t GetNetworkType();
+
+CAResult_t Initialize();
+void StartListeningServer();
+void StartDiscoveryServer();
+void FindResource();
+void SendRequest();
+void SendRequestAll();
+void SendResponse();
+void AdvertiseResource();
+void SendNotification();
+void SelectNetwork();
+void UnselectNetwork();
+void HandleRequestResponse();
+void FindFixedResource();
+void GetNetworkInfo();
+
+void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo);
+void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo);
+void SendRequestTemp(CARemoteEndpoint_t *endpoint, CAToken_t token);
+void GetResourceUri(char *URI, char *resourceURI, int length);
+int GetSecureInformation(CAPayload_t payLoad);
+
+static CAToken_t g_lastRequestToken = NULL;
+static const char g_secureInfoData[] = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
"\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
-static const char *gNormalInfoData = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+static const char g_normalInfoData[] = "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
"\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
#ifdef __WITH_DTLS__
static OCDtlsPskCredsBlob *pskCredsBlob = NULL;
-void clearDtlsCredentialInfo()
+
+void ClearDtlsCredentialInfo()
{
printf("clearDtlsCredentialInfo IN\n");
if (pskCredsBlob)
{
printf("CAGetDtlsPskCredentials IN\n");
+ if(!credInfo)
+ {
+ printf("Memory is not allocated for credInfo\n");
+ return;
+ }
+
*credInfo = pskCredsBlob;
printf("CAGetDtlsPskCredentials OUT\n");
}
-int32_t SetCredentials()
+bool SetCredentials()
{
printf("SetCredentials IN\n");
pskCredsBlob = (OCDtlsPskCredsBlob *)malloc(sizeof(OCDtlsPskCredsBlob));
+ if(!pskCredsBlob)
+ {
+ printf("Memory allocation is failed\n");
+ return 0;
+ }
+
memset(pskCredsBlob, 0x0, sizeof(OCDtlsPskCredsBlob));
memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+ if(!pskCredsBlob->creds)
+ {
+ printf("Memory allocation is failed\n");
+ return 0;
+ }
+
+
memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
return 1;
}
#endif
+
void pthread_func()
{
g_main_loop_run(mainloop);
printf("\t\tsample main\n");
printf("=============================================\n");
- CAResult_t res;
+ CAResult_t res = CA_STATUS_FAILED;
/*
* Read DTLS PSK credentials from persistent storage and
* set in the OC stack.
if (SetCredentials() == 0)
{
printf("SetCredentials failed\n");
- return 0;
+ return 1;
}
res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
- if(res != CA_STATUS_OK)
+ if(CA_STATUS_OK != res)
{
printf("Set credential handler fail\n");
- return 0;
+ return 1;
}
#endif
- res = initialize();
- if (res != CA_STATUS_OK)
+ res = Initialize();
+ if (CA_STATUS_OK != res)
{
printf("CAInitialize fail\n");
- return 0;
+ return 1;
}
-#if 0
- // network enable
- // default
- printf("select default network(WIFI)\n");
- res = CASelectNetwork(CA_WIFI);
- if (res != CA_STATUS_OK)
- {
- printf("CASelectNetwork fail\n");
- return 0;
- }
-#endif
-
// set handler.
- CARegisterHandler(request_handler, response_handler);
+ CARegisterHandler(RequestHandler, ResponseHandler);
- process();
+ Process();
- if (gLastRequestToken != NULL)
+ if (g_lastRequestToken != NULL)
{
- CADestroyToken(gLastRequestToken);
+ CADestroyToken(g_lastRequestToken);
}
- gLastRequestToken = NULL;
+ g_lastRequestToken = NULL;
CATerminate();
#ifdef __WITH_DTLS__
- clearDtlsCredentialInfo();
+ ClearDtlsCredentialInfo();
#endif
return 0;
}
-void process()
+void Process()
{
while (1)
{
- char menu = toupper(get_menu());
+ char menu = toupper(PrintOptions());
switch (menu)
{
case 'm': // menu
case 'M':
- continue;
+ break;
+
case 'Q': // quits the sample program
printf("quit..!!\n");
g_main_loop_quit(mainloop);
case 's': // start server
case 'S': // start server
- start_listening_server();
+ StartListeningServer();
break;
case 't': // send request
case 'T':
- send_request_all();
+ SendRequestAll();
break;
case 'c': // start client
- case 'D':
- start_discovery_server();
+ case 'C':
+ StartDiscoveryServer();
break;
- case 'F': // find resource
- find_resource();
+ case 'f': // find resource
+ case 'F':
+ FindResource();
break;
- case 'R': // send request
- send_request();
+ case 'r': // send request
+ case 'R':
+ SendRequest();
break;
- case 'A': // advertise resource
- advertise_resource();
+ case 'a': // advertise resource
+ case 'A':
+ AdvertiseResource();
break;
case 'b': // send notification
case 'B':
- send_notification();
+ SendNotification();
break;
- case 'N': // select network
- select_network();
+
+ case 'n': // select network
+ case 'N':
+ SelectNetwork();
break;
- case 'X': // unselect network
- unselect_network();
+ case 'x': // unselect network
+ case 'X':
+ UnselectNetwork();
break;
- case 'H': // handle request response
- handle_request_response();
+ case 'h': // handle request response
+ case 'H':
+ HandleRequestResponse();
break;
+
case 'y':
case 'Y':
while (1)
{
- gReceived = 0;
- find_fixed_resource();
- while (gReceived == 0)
+ g_received = 0;
+ FindFixedResource();
+ while (g_received == 0)
{
sleep(1);
- handle_request_response();
+ HandleRequestResponse();
}
}
break;
case 'z':
case 'Z':
- start_listening_server();
+ StartListeningServer();
while (1)
{
sleep(1);
- handle_request_response();
+ HandleRequestResponse();
}
break;
case 'g': // get network information
case 'G':
- get_network_info();
+ GetNetworkInfo();
break;
default:
}
-CAResult_t initialize()
+CAResult_t Initialize()
{
+ CAResult_t res = CA_STATUS_FAILED;
mainloop = g_main_loop_new(NULL, FALSE);
- pthread_create (&thread, NULL, (void *) &pthread_func, NULL);
+ if(!mainloop)
+ {
+ printf("g_main_loop_new failed\n");
+ return res;
+ }
- CAResult_t res = CAInitialize();
+ int result = pthread_create(&thread, NULL, (void *) &pthread_func, NULL);
+ if (result < 0)
+ {
+ printf("pthread_create failed in initialize\n");
+ return res;
+ }
+
+ res = CAInitialize();
if (res != CA_STATUS_OK)
{
printf("CAInitialize fail\n");
- return CA_STATUS_FAILED;
}
-
- return CA_STATUS_OK;
+ return res;
}
-void start_listening_server()
+void StartListeningServer()
{
printf("start listening server!!\n");
}
}
-void start_discovery_server()
+void StartDiscoveryServer()
{
printf("start discovery client!!\n");
}
}
-void find_fixed_resource()
+void FindFixedResource()
{
- char buf[MAX_BUF_LEN] =
- { 0, };
- strcpy(buf, "/a/light");
+ char buf[] ="/a/light";
// create token
CAToken_t token = NULL;
printf("find resource to %s URI\n", buf);
}
- // delete token
- /*
- if (token != NULL)
+ //delete token
+ if (token)
{
- CADestroyToken(token);
+ CADestroyToken(token);
}
- */
printf("=============================================\n");
}
-void find_resource()
-{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+void FindResource()
+{
+ char buf[MAX_BUF_LEN] = {0};
printf("\n=============================================\n");
printf("ex) /a/light\n");
printf("reference uri : ");
- gets(buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return;
+ }
// create token
CAToken_t token = NULL;
{
printf("find resource to %s URI\n", buf);
- if (gLastRequestToken != NULL)
+ if (g_lastRequestToken)
{
- CADestroyToken(gLastRequestToken);
+ CADestroyToken(g_lastRequestToken);
}
- gLastRequestToken = token;
+ g_lastRequestToken = token;
}
- // delete token
- /*
- if (token != NULL)
- {
- CADestroyToken(token);
- }
- */
-
printf("=============================================\n");
}
-void send_request()
+void SendRequest()
{
char secureRequest[2] = {0};
- CAResult_t res;
+ CAResult_t res = CA_STATUS_FAILED;
+ char uri[MAX_BUF_LEN] = {'\0'};
- res = get_network_type();
+ res = GetNetworkType();
if (res != CA_STATUS_OK)
{
return;
}
- printf("Do you want to send secure request ?.... enter (0/1): ");
- gets(secureRequest);
+ printf("Do you want to send secure request ?.... enter (0/1): \n");
+ if(!fgets(secureRequest, 1, stdin))
+ {
+ printf("fgets error\n");
+ return;
+ }
+
if ('1' == secureRequest[0])
{
printf("Enter the URI like below....\n");
printf("coaps://10.11.12.13:4545/resource_uri ( for IP secure)\n");
+ printf("uri: ");
}
else
{
printf("Enter the URI like below....\n");
printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n");
printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n");
+ printf("uri: ");
}
- char uri[MAX_BUF_LEN] = {'\0'};
- gets(uri);
+ if(!fgets(uri, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
- if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, gSelectedNwType, &endpoint)
+ if (CA_STATUS_OK != CACreateRemoteEndpoint(uri, g_selectedNwType, &endpoint)
|| !endpoint)
{
printf("Failed to create remote endpoint!\n");
return;
}
- //endpoint->connectivityType = gSelectedNwType;
-
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN]={0};
printf("\n=============================================\n");
printf("0:CON, 1:NON\n");
printf("select message type : ");
- gets(buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
CAMessageType_t msgType = (buf[0] == '0' || buf[0] == '1') ? buf[0] - '0' : 0;
char resourceURI[15] = {0};
printf("URI : %s\n", uri);
- get_resource_uri(uri, resourceURI, 14);
+ GetResourceUri(uri, resourceURI, 14);
// create request data
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ CAInfo_t requestData = {CA_MSG_RESET};
requestData.token = token;
if ('1' == secureRequest[0])
{
- int length = strlen(gSecureInfoData) + strlen(resourceURI) + 1;
+ int length = strlen(g_secureInfoData) + strlen(resourceURI) + 1;
requestData.payload = (CAPayload_t) malloc(length);
- sprintf(requestData.payload, gSecureInfoData, resourceURI, gLocalSecurePort);
+ if(!requestData.payload)
+ {
+ printf("Memory allocation is failed\n");
+ CADestroyToken(token);
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
+ sprintf(requestData.payload, g_secureInfoData, resourceURI, g_localSecurePort);
}
else
{
- int length = strlen(gNormalInfoData) + strlen(resourceURI) + 1;
+ int length = strlen(g_normalInfoData) + strlen(resourceURI) + 1;
requestData.payload = (CAPayload_t) malloc(length);
- sprintf(requestData.payload, gNormalInfoData, resourceURI);
+ if(!requestData.payload)
+ {
+ printf("Memory allocation is failed\n");
+ CADestroyToken(token);
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
+ sprintf(requestData.payload, g_normalInfoData, resourceURI);
}
requestData.type = msgType;
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
requestInfo.method = CA_GET;
requestInfo.info = requestData;
// send request
CASendRequest(endpoint, &requestInfo);
- if (token != NULL)
+ if (token)
{
CADestroyToken(token);
}
- if (requestData.payload != NULL)
+ if (requestData.payload)
{
free(requestData.payload);
}
printf("=============================================\n");
}
-void send_request_all()
+void SendRequestAll()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = {0};
- CAResult_t res;
+ CAResult_t res = CA_STATUS_FAILED;
- res = get_network_type();
+ res = GetNetworkType();
if (res != CA_STATUS_OK)
{
return;
printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
printf("uri : ");
- gets(buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(buf, gSelectedNwType, &endpoint);
+ res = CACreateRemoteEndpoint(buf, g_selectedNwType, &endpoint);
if (res != CA_STATUS_OK)
{
return;
}
-
CAGroupEndpoint_t *group = NULL;
group = (CAGroupEndpoint_t *)malloc(sizeof(CAGroupEndpoint_t));
+ if (NULL == group)
+ {
+ printf("Memory allocation failed!\n");
+ CADestroyRemoteEndpoint(endpoint);
+ return;
+ }
group->connectivityType = endpoint->connectivityType;
group->resourceUri = endpoint->resourceUri;
-
// create token
CAToken_t token = NULL;
res = CAGenerateToken(&token);
printf("generated token %s\n", (token != NULL) ? token : "");
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ CAInfo_t requestData = {CA_MSG_RESET};
requestData.token = token;
requestData.payload = "Temp Json Payload";
requestData.type = CA_MSG_NONCONFIRM;
- CARequestInfo_t requestInfo;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+
+ CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
requestInfo.method = CA_GET;
requestInfo.info = requestData;
printf("=============================================\n");
}
-void advertise_resource()
+void AdvertiseResource()
{
- char buf[MAX_BUF_LEN];
-
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = {0};
printf("\n=============================================\n");
printf("uri : ");
- scanf("%s", buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return;
+ }
int optionNum = 0;
- char optionData[MAX_OPT_LEN];
+ char optionData[MAX_OPT_LEN] = {0};
printf("Option Num : ");
scanf("%d", &optionNum);
- CAHeaderOption_t *headerOpt;
+ CAHeaderOption_t *headerOpt = NULL;
headerOpt = (CAHeaderOption_t *) malloc(sizeof(CAHeaderOption_t) * optionNum);
if (NULL == headerOpt)
{
}
memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
- int i;
+ int i = 0;
for (i = 0 ; i < optionNum ; i++)
{
int optionID = 0;
scanf("%d", &optionID);
headerOpt[i].optionID = optionID;
- memset(optionData, 0, sizeof(char) * MAX_OPT_LEN);
printf("[%d] Option Data : ", i + 1);
scanf("%s", optionData);
- memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
+ int len = strlen(optionData);
+ memcpy(headerOpt[i].optionData, optionData, len + 1);
printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData );
- headerOpt[i].optionLength = (uint16_t)strlen(optionData);
+ headerOpt[i].optionLength = (uint16_t)len;
}
printf("\n=============================================\n");
CAAdvertiseResource(buf, token, headerOpt, (uint8_t)optionNum);
// delete token
- if (token != NULL)
+ if (token)
{
CADestroyToken(token);
}
}
-void send_notification()
+void SendNotification()
{
- char buf[MAX_BUF_LEN];
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+ char buf[MAX_BUF_LEN] = {0};
- CAResult_t res;
+ CAResult_t res = CA_STATUS_FAILED;
- res = get_network_type();
+ res = GetNetworkType();
if (res != CA_STATUS_OK)
{
return;
printf("10:11:12:13:45:45/resource_uri ( for BT )\n");
printf("uri : ");
- gets(buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return;
+ }
// create remote endpoint
CARemoteEndpoint_t *endpoint = NULL;
- res = CACreateRemoteEndpoint(buf, gSelectedNwType, &endpoint);
-
+ res = CACreateRemoteEndpoint(buf, g_selectedNwType, &endpoint);
if (res != CA_STATUS_OK)
{
printf("create remote endpoint error!!\n");
return;
}
- CAInfo_t respondeData;
- memset(&respondeData, 0, sizeof(CAInfo_t));
+ CAInfo_t respondeData = {CA_MSG_RESET};
respondeData.token = "client token";
respondeData.payload = "Temp Notification Data";
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ CAResponseInfo_t responseInfo = {0};
responseInfo.result = CA_SUCCESS;
responseInfo.info = respondeData;
printf("\n=============================================\n");
}
-void select_network()
+void SelectNetwork()
{
- char buf[MAX_BUF_LEN];
+ char buf[MAX_BUF_LEN] = {0};
printf("\n=============================================\n");
printf("\tselect network\n");
printf("LE : 3\n");
printf("select : ");
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- gets(buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return;
+ }
int number = buf[0] - '0';
if (res != CA_STATUS_OK)
{
printf("select network error\n");
- gSelectedNwType = 1 << number;
+ g_selectedNwType = 1 << number;
}
else
{
printf("=============================================\n");
}
-void unselect_network()
+void UnselectNetwork()
{
- char buf[MAX_BUF_LEN];
+ char buf[MAX_BUF_LEN] = {0};
printf("\n=============================================\n");
printf("\tunselect enabled network\n");
printf("LE : 3\n");
printf("select : ");
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- gets(buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return;
+ }
int number = buf[0] - '0';
printf("=============================================\n");
}
-char get_menu()
+char PrintOptions()
{
- char buf[MAX_BUF_LEN];
+ char buf[MAX_BUF_LEN] = {0};
printf("\n=============================================\n");
printf("\t\tMenu\n");
+ printf("\tm : show menu\n");
printf("\ts : start server\n");
- printf("\tD : start client\n");
+ printf("\tc : start client\n");
printf("\tf : find resource\n");
printf("\tr : send request\n");
printf("\tt : send request to all\n");
printf("=============================================\n");
printf("select : ");
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
- gets(buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return '\0';
+ }
return buf[0];
}
-void handle_request_response()
+void HandleRequestResponse()
{
printf("handle_request_response\n");
}
}
-void get_network_info()
+void GetNetworkInfo()
{
- int index;
-
+ int index = 0;
CALocalConnectivity_t *tempInfo = NULL;
uint32_t tempSize = 0;
printf("Port: %d\n", tempInfo[index].addressInfo.IP.port);
printf("Secured: %d\n\n", tempInfo[index].isSecured);
- if (CA_TRUE == tempInfo[index].isSecured)
+ if (true == tempInfo[index].isSecured)
{
- gLocalSecurePort = tempInfo[index].addressInfo.IP.port;
+ g_localSecurePort = tempInfo[index].addressInfo.IP.port;
}
else
{
- gLocalUnicastPort = tempInfo[index].addressInfo.IP.port;
+ g_localUnicastPort = tempInfo[index].addressInfo.IP.port;
}
}
printf("##############################################################");
}
-void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+void RequestHandler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
{
+ printf("##########received request from remote device #############\n");
if (!object)
{
- printf("Remote endpoint is NULL!");
+ printf("Remote endpoint is NULL!\n");
return;
}
if (!requestInfo)
{
- printf("Request info is NULL!");
+ printf("Request info is NULL!\n");
return;
}
- printf("##########received request from remote device #############\n");
printf("Uri: %s\n", object->resourceUri);
printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
object->addressInfo.IP.port, object->isSecured);
printf("Data: %s\n", requestInfo->info.payload);
- printf("Message type: %s\n", gMessageType[requestInfo->info.type]);
- if (gLastRequestToken != NULL && requestInfo->info.token != NULL
- && (strcmp((char *)gLastRequestToken, requestInfo->info.token) == 0))
+ printf("Message type: %s\n", g_messageType[requestInfo->info.type]);
+ if (g_lastRequestToken != NULL && requestInfo->info.token != NULL
+ && (strcmp((char *)g_lastRequestToken, requestInfo->info.token) == 0))
{
printf("token is same. received request of it's own. skip.. \n");
return;
if (requestInfo->info.options)
{
uint32_t len = requestInfo->info.numOptions;
- uint32_t i;
+ uint32_t i = 0;
for (i = 0; i < len; i++)
{
printf("Option %d\n", i + 1);
//Check if this has secure communication information
if (requestInfo->info.payload)
{
- int securePort = get_secure_information(requestInfo->info.payload);
+ int securePort = GetSecureInformation(requestInfo->info.payload);
if (0 < securePort) //Set the remote endpoint secure details and send response
{
printf("This is secure resource...\n");
return;
}
//endpoint->connectivityType = object->connectivityType;
- endpoint->isSecured = CA_TRUE;
+ endpoint->isSecured = true;
object = endpoint;
free(uri);
}
printf("send response with URI\n");
- send_response(object, &requestInfo->info);
+ SendResponse(object, &requestInfo->info);
- gReceived = 1;
+ g_received = 1;
}
-void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+void ResponseHandler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
printf("##########Received response from remote device #############\n");
+ if(!object)
+ {
+ printf("response_handler object is null\n");
+ return;
+ }
+
+ if(!responseInfo)
+ {
+ printf("response_handler responseInfo is null\n");
+ return;
+ }
+
printf("Uri: %s\n", object->resourceUri);
printf("Remote Address: %s Port: %d secured:%d\n", object->addressInfo.IP.ipAddress,
object->addressInfo.IP.port, object->isSecured);
printf("response result : %d\n", responseInfo->result);
printf("Data: %s\n", responseInfo->info.payload);
- printf("Message type: %s\n", gMessageType[responseInfo->info.type]);
- printf("Token: %s\n", responseInfo->info.token);
+ printf("Message type: %s\n", g_messageType[responseInfo->info.type]);
if (responseInfo->info.options)
{
uint32_t len = responseInfo->info.numOptions;
- uint32_t i;
+ uint32_t i = 0;
for (i = 0; i < len; i++)
{
printf("Option %d\n", i + 1);
}
}
printf("############################################################\n");
- gReceived = 1;
+ g_received = 1;
//Check if this has secure communication information
if (responseInfo->info.payload)
{
- int securePort = get_secure_information(responseInfo->info.payload);
+ int securePort = GetSecureInformation(responseInfo->info.payload);
if (0 < securePort) //Set the remote endpoint secure details and send response
{
printf("This is secure resource...\n");
}
}
-void send_response(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
+void SendResponse(CARemoteEndpoint_t *endpoint, CAInfo_t *info)
{
- char buf[MAX_BUF_LEN];
-
printf("entering send_response\n");
- printf("\n=============================================\n");
- printf("\tselect message type\n");
- printf("CA_MSG_CONFIRM : 0\n");
- printf("CA_MSG_NONCONFIRM : 1\n");
- printf("CA_MSG_ACKNOWLEDGE : 2\n");
- printf("CA_MSG_RESET : 3\n");
- printf("select : ");
+ if(!endpoint)
+ {
+ printf("endpoint is null\n");
+ return;
+ }
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- gets(buf);
-
- int messageType = buf[0] - '0';
- int responseCode = 231 ;
- if(messageType != 3)
- {
-
- printf("\n=============================================\n");
- printf("\tselect response code\n");
- printf("CA_SUCCESS : 200\n");
- printf("CA_CREATED : 201\n");
- printf("CA_DELETED : 202\n");
- printf("CA_EMPTY : 231\n");
- printf("CA_BAD_REQ : 400\n");
- printf("CA_BAD_OPT : 402\n");
- printf("CA_NOT_FOUND : 404\n");
- printf("CA_RETRANSMIT_TIMEOUT : 531\n");
- printf("select : ");
- scanf("%d", &responseCode);
- }
- CAInfo_t responseData;
- memset(&responseData, 0, sizeof(CAInfo_t));
- responseData.type = messageType;
- responseData.messageId = (info != NULL) ? info->messageId : 0;
- responseData.token = (info != NULL) ? info->token : "";
+ CAInfo_t responseData = {CA_MSG_RESET};
+ responseData.type =
+ (info != NULL) ?
+ ((info->type == CA_MSG_CONFIRM) ? CA_MSG_ACKNOWLEDGE : CA_MSG_NONCONFIRM) :
+ CA_MSG_NONCONFIRM;
+ responseData.messageId = 0;
+ responseData.token = "";
+ if(info)
+ {
+ responseData.messageId = info->messageId;
+ responseData.token = info->token;
+ }
responseData.payload = "response payload";
- CAResponseInfo_t responseInfo;
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = responseCode;
+ CAResponseInfo_t responseInfo = {0};
+ responseInfo.result = 203;
responseInfo.info = responseData;
- if (CA_TRUE == endpoint->isSecured)
+ if (true == endpoint->isSecured)
+ {
printf("Sending response on secure communication\n");
+ }
else
+ {
printf("Sending response on non-secure communication\n");
+ }
// send request (connectivityType from remoteEndpoint of request Info)
CAResult_t res = CASendResponse(endpoint, &responseInfo);
if (res != CA_STATUS_OK)
-{
- printf("send response error\n");
+ {
+ printf("send response failed\n");
}
else
{
printf("=============================================\n");
}
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token)
+void SendRequestTemp(CARemoteEndpoint_t *endpoint, CAToken_t token)
{
-
printf("\n=============================================\n");
- CAInfo_t requestData;
- memset(&requestData, 0, sizeof(CAInfo_t));
+ if(!endpoint)
+ {
+ printf("endpoint is null\n");
+ return;
+ }
+
+ CAInfo_t requestData ={CA_MSG_RESET};
requestData.token = token;
requestData.payload = "Temp Json Payload";
- CARequestInfo_t requestInfo;
+ CARequestInfo_t requestInfo ={CA_GET, {CA_MSG_RESET}};
memset(&requestInfo, 0, sizeof(CARequestInfo_t));
requestInfo.method = CA_GET;
requestInfo.info = requestData;
CAResult_t res = CASendRequest(endpoint, &requestInfo);
if (res != CA_STATUS_OK)
{
- printf("send request error\n");
+ printf("send request failed\n");
}
else
{
}
-int get_secure_information(CAPayload_t payLoad)
+int GetSecureInformation(CAPayload_t payLoad)
{
printf("entering get_secure_information\n");
return -1;
}
+ if(((endPos - 1) - startPos) > 4)
+ {
+ printf("port length is not proper.Exceeding length 4\n");
+ return -1;
+ }
+
char portStr[4] = {0};
memcpy(portStr, startPos + 1, (endPos - 1) - startPos);
return atoi(portStr);
}
-void get_resource_uri(char *URI, char *resourceURI, int length)
+void GetResourceUri(char *URI, char *resourceURI, int length)
{
char *startPos = URI;
char *temp = NULL;
printf("URI: %s, ResourceURI:%s\n", URI, resourceURI);
}
-CAResult_t get_network_type()
+CAResult_t GetNetworkType()
{
- char buf[MAX_BUF_LEN];
+ char buf[MAX_BUF_LEN] = {0};
printf("\n=============================================\n");
printf("\tselect network type\n");
printf("LE : 3\n");
printf("select : ");
- memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
- gets(buf);
+ if(!fgets(buf, MAX_BUF_LEN, stdin))
+ {
+ printf("fgets error\n");
+ return CA_STATUS_FAILED;
+ }
int number = buf[0] - '0';
{
return CA_NOT_SUPPORTED;
}
+
if (number & CA_ETHERNET)
{
- gSelectedNwType = CA_ETHERNET;
+ g_selectedNwType = CA_ETHERNET;
return CA_STATUS_OK;
}
+
if (number & CA_WIFI)
{
- gSelectedNwType = CA_WIFI;
+ g_selectedNwType = CA_WIFI;
return CA_STATUS_OK;
}
+
if (number & CA_EDR)
{
- gSelectedNwType = CA_EDR;
+ g_selectedNwType = CA_EDR;
return CA_STATUS_OK;
}
+
if (number & CA_LE)
{
- gSelectedNwType = CA_LE;
+ g_selectedNwType = CA_LE;
return CA_STATUS_OK;
}
return CA_STATUS_FAILED;
}
+
<domain name="casample" />
</request>
</manifest>
+
+++ /dev/null
-# all permissions
-#interfacesample system::vconf rwxat
-#interfacesample system::home rwxat
-#interfacesample system::media rwxat
-#interfacesample system::homedir rwxat
-#interfacesample system::share rwxat
-#interfacesample dali rwxat
-#interfacesample sys-assert::core rwxat
-#interfacesample dbus r
-#interfacesample system::media rwxat
-# system and device
-#interfacesample device::hwcodec rw
-#interfacesample device::video r
-#interfacesample device::camera r
-#interfacesample system::crash wx
-casample system::use_internet rw
-# db
-#interfacesample libaccounts-svc::db rw
-#interfacesample ail::db rw
-#interfacesample media-data::db rw
-#interfacesample app-svc::db rw
-#interfacesample email-service::db rw
-#interfacesample cloud-content-sync::db rw
-#others
-#interfacesample media-server rwx
-#interfacesample mdm-server w
-#interfacesample xorg w
-#interfacesample isf rwx
-#interfacesample immvibed rw
-#interfacesample dbus rwx
-#interfacesample dali rx
-#interfacesample data-provider-master r
-#interfacesample smemo rx
-#interfacesample crash-worker rx
-#interfacesample msg-service w
-#interfacesample webkit2-efl rx
-#interfacesample ug-image-viewer-efl rx
-#interfacesample net.wifi-qs rwx
-#interfacesample sys-assert::info wx
-<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns="http://tizen.org/ns/packages" package="com.oic.ca.sample" version="0.1.12" install-location="internal-only">
- <label>casample</label>
- <author email="oic" href="www.iotivity.org">OIC</author>
- <description>casample</description>
+ <label>casample</label>
+ <author email="oic" href="www.iotivity.org">OIC</author>
+ <description>casample</description>
<ui-application appid="com.oic.ca.sample" exec="/usr/apps/com.oic.ca.sample/bin/sample" nodisplay="false" multiple="false" type="capp" taskmanage="true">
- <icon>com.oic.ca.sample.png</icon>
- <label>casample</label>
- <label xml:lang="en-us">casample</label>
- <label xml:lang="nl-nl">casample</label>
+ <icon>com.oic.ca.sample.png</icon>
+ <label>casample</label>
+ <label xml:lang="en-us">casample</label>
+ <label xml:lang="nl-nl">casample</label>
</ui-application>
<privileges>
<privilege>http://tizen.org/privilege/socket</privilege>
</privileges>
</manifest>
+
#!/bin/sh
-if [ "$1" = "WITH_WIFI" ]
-then
- echo "Building Interface Sample for WIFI transport"
- adapterMacro="$adapterMacro -DWIFI_ADAPTER_TEST"
-elif [ "$1" = "WITH_BT" ]
-then
- echo "Building Interface Sample for BT transport"
- adapterMacro="$adapterMacro -DBT_ADAPTER_TEST"
-elif [ "$1" = "WITH_BLE" ]
-then
- echo "Building Interface Sample for BLE transport"
- adapterMacro="$adapterMacro -DBLE_ADAPTER_TEST"
-elif [ "$1" = "" ]
-then
- echo "Building Interface Sample for ALL transports"
- adapterMacro="$adapterMacro -DWIFI_ADAPTER_TEST -DBT_ADAPTER_TEST -DBLE_ADAPTER_TEST -DETHERNET_ADAPTER"
-else
- echo "Please specify valid transport option: WITH_WIFI or WITH_BT or WITH_BLE"
- exit 1
-fi
-
-sed "/ADAPTER_MACRO :=/ c ADAPTER_MACRO :=$adapterMacro" Makefile > Makefile.tmp
-
-rm Makefile
-mv Makefile.tmp Makefile
-dos2unix Makefile
-
git init
gbs build -A armv7l --include-all -B ~/GBS-ROOT-NEW
+
+++ /dev/null
-/******************************************************************
-*
-* Copyright 2014 Samsung Electronics All Rights Reserved.
-*
-*
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*
-******************************************************************/
-
-//***************************************************************
-//
-// This file is for internal test only.
-// Do NOT use this file to test CA on Tizen.
-//
-//***************************************************************
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
-#include <ctype.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <wifi.h>
-#include <glib.h>
-
-#include "cacommon.h"
-#include "caadapterinterface.h"
-#include "uthreadpool.h"
-
-#define MOD_NAME "TizenSample"
-
-#if defined(WIFI_ADAPTER_TEST)
-#include "cawifiadapter.h"
-static u_thread_pool_t gWiFiThreadPool = NULL;
-#endif
-#if defined(BT_ADAPTER_TEST)
-#include "caedradapter.h"
-static u_thread_pool_t gBTThreadPool = NULL;
-#endif
-#if defined(BLE_ADAPTER_TEST)
-#include "caleadapter.h"
-static u_thread_pool_t gLEThreadPool = NULL;
-#endif
-
-static GMainLoop *mainloop = NULL;
-static GIOChannel *channel = NULL;
-static guint g_test_io_watch_id = 0;
-static GError *g_err_Sample = NULL;
-
-//Hardcoded coap data for Test
-static char coapData[500] =
- "{\"oc:\[{href\":\"/a/light\",\"ref\":{\"power\":\"20\",\"state\":\"true\"}}]}";
-
-void testInitializeBTInterface(void);
-void testTerminateBTInterface(void);
-void testInitializeWIFIInterface(void);
-void testTerminateWIFIInterface(void);
-void testInitializeBLEInterface(void);
-void testTerminateBLEInterface(void);
-
-typedef struct ConnectivityHandlerList
-{
- CAConnectivityType_t type;
- CAConnectivityHandler_t handler;
- struct ConnectivityHandlerList *nextHandler;
-} ConnectivityHandlerList;
-
-static ConnectivityHandlerList *gConnectivityHandlers = NULL;
-
-void initializeThreadPool(CAConnectivityType_t type)
-{
-#ifdef BT_ADAPTER_TEST
- if (CA_EDR == type && NULL == gBTThreadPool)
- {
- if (CA_STATUS_OK != u_thread_pool_init(3, &gBTThreadPool))
- {
- printf("Failed to create thread pool for BT adapter!\n");
- return;
- }
- }
-#endif
-#ifdef WIFI_ADAPTER_TEST
- if (CA_WIFI == type && NULL == gWiFiThreadPool)
- {
- if (CA_STATUS_OK != u_thread_pool_init(3, &gWiFiThreadPool))
- {
- printf("Failed to create thread pool for WIFI adapter!\n");
- return;
- }
- }
-#endif
-#ifdef BLE_ADAPTER_TEST
- if (CA_LE == type && NULL == gLEThreadPool)
- {
- if (CA_STATUS_OK != u_thread_pool_init(5, &gLEThreadPool))
- {
- printf("Failed to create thread pool for BLE adapter!\n");
- return;
- }
- }
-#endif
-}
-
-
-void storeInterfaceCallbacks(ConnectivityHandlerList *newHandler)
-{
- printf("storeInterfaceCallbacks Entry in Sample\n");
- newHandler->nextHandler = NULL;
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
-
- if (!tempConnectivityHandlers)
- {
- gConnectivityHandlers = newHandler;
- printf("storeInterfaceCallbacks Exit in Sample\n");
- return;
- }
-
- while (tempConnectivityHandlers->nextHandler)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- tempConnectivityHandlers->nextHandler = newHandler;
- printf("storeInterfaceCallbacks Exit in Sample\n");
-}
-
-void interfaceRegisterCallback(CAConnectivityHandler_t handler,
- CAConnectivityType_t connType)
-{
- printf("interfaceRegisterCallback Entry in Sample\n");
- ConnectivityHandlerList *newConnectivityHandler = (ConnectivityHandlerList *) malloc(sizeof(
- ConnectivityHandlerList));
- if (NULL == newConnectivityHandler)
- {
- printf("Memory allocation failed\n");
- return;
- }
-
- newConnectivityHandler->type = connType;
- newConnectivityHandler->handler = handler;
- storeInterfaceCallbacks(newConnectivityHandler);
- printf("interfaceRegisterCallback Exit in Sample\n");
-}
-
-void networkPacketHandler(CARemoteEndpoint_t *object, void *data, uint32_t dataLength)
-{
- printf("networkPacketHandler Entry in Sample\n");
- if (object == NULL || data == NULL)
- {
- printf("NULL Object\n");
- return;
- }
-
- printf("Data Received from: ");
- if (CA_EDR == object->connectivityType)
- {
- printf(object->addressInfo.BT.btMacAddress);
- }
- else if (CA_LE == object->connectivityType)
- {
- printf(object->addressInfo.LE.leMacAddress);
- }
- else if (CA_WIFI == object->connectivityType || CA_ETHERNET == object->connectivityType)
- {
- printf(object->addressInfo.IP.ipAddress);
- }
-
- printf("\nReceived Data [Length: %d]: %s\n", dataLength, (char *)data);
- printf("networkPacketHandler Exit in Sample\n");
-}
-
-void networkInterfaceCallback(CALocalConnectivity_t *localEndPoint,
- CANetworkStatus_t networkConnectivityState)
-{
- printf("networkInterfaceCallback Entry in Sample\n");
- if (localEndPoint == NULL)
- {
- printf("NULL Object\n");
- return;
- }
-
- if (networkConnectivityState == CA_INTERFACE_UP)
- {
- printf("Network Status is UP\n");
- }
- else
- {
- printf("Network Status is DOWN\n");
- }
-
- printf("Address: ");
- if (CA_EDR == localEndPoint->type)
- {
- printf("%s\n", localEndPoint->addressInfo.BT.btMacAddress);
- }
- else if (CA_LE == localEndPoint->type)
- {
- printf("%s\n", localEndPoint->addressInfo.LE.leMacAddress);
- }
- else if (CA_WIFI == localEndPoint->type || CA_ETHERNET == localEndPoint->type)
- {
- printf("%s\n", localEndPoint->addressInfo.IP.ipAddress);
- }
-
- printf("networkInterfaceCallback Exit in Sample\n");
-}
-
-
-void freeData(void *data)
-{
- printf("freeData Entry in Sample\n");
- if (data)
- {
- free(data);
- }
- printf("freeData Exit in Sample\n");
-}
-
-int16_t selectConnectivityType()
-{
- int32_t cType;
- printf("*******Select the Connectivity Type*******\n");
- printf(" [1] WIFI \n");
- printf(" [2] BT \n");
- printf(" [3] BLE \n");
-
- fflush(stdin);
- scanf("%d", &cType);
- if (cType < 1 && cType > 3)
- {
- printf("Invalid Selection!!!!\n");
- return 0;
- }
- return (int16_t)cType;
-}
-
-int16_t interfaceStartAdapter(CAConnectivityType_t connType)
-{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- printf("None of the interface is initialized\n");
- return 0;
- }
-
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- if (NULL == tempConnectivityHandlers)
- {
- printf( "No interface handler for type %d", connType);
- return 0;
- }
-
- if (CA_STATUS_OK != tempConnectivityHandlers->handler.startAdapter())
- {
- printf("Failed to Start adapter\n");
- return 0;
- }
-
- return 1;
-}
-
-int16_t interfaceMulticastStartServer(CAConnectivityType_t connType, int serverType)
-{
- printf("interfaceMulticastStartServer Starting...\n");
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- printf("None of the interface is initialized\n");
- return 0;
- }
-
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- if (NULL == tempConnectivityHandlers)
- {
- printf( "No interface handler for type %d", connType);
- return 0;
- }
-
- CAAdapterStartDiscoveryServer startServer = NULL;
- switch (serverType)
- {
- case 1: //Discovery server
- startServer = tempConnectivityHandlers->handler.startDiscoverServer;
- break;
- case 2: //Listening server
- startServer = tempConnectivityHandlers->handler.startListenServer;
- break;
- }
-
- if (startServer)
- {
- printf("Invoking start server method\n");
- startServer();
- }
- return 0;
-}
-
-int16_t interfaceSendUnicastData(CAConnectivityType_t connType)
-{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- printf(" None of the interface is initialized \n");
- return 0;
- }
-
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- if (NULL == tempConnectivityHandlers)
- {
- printf( "No interface handler for type %d", connType);
- return 0;
- }
-
- if (CA_WIFI == connType)
- {
- CARemoteEndpoint_t endpoint;
- char remoteIPAddress[CA_IPADDR_SIZE] = {0};
- printf("\nEnter the Remote Endpoint IP: ");
- scanf("%s", remoteIPAddress);
- if (strlen(remoteIPAddress) == 0)
- {
- printf("Invalid device address\n");
- return -1;
- }
- endpoint.connectivityType = CA_WIFI;
- strncpy(endpoint.addressInfo.IP.ipAddress, remoteIPAddress, CA_IPADDR_SIZE);
- endpoint.addressInfo.IP.port = 5683; /* Send the corresponding port here */
-
- int sdatalen = tempConnectivityHandlers->handler.sendData(&endpoint, coapData,
- strlen(coapData));
- if (sdatalen == strlen(coapData))
- {
- printf("Send Unicast data success\n");
- }
- else
- {
- printf("Send Unicast data failed\n");
- }
- }
- else if (CA_EDR == connType)
- {
- //create endpoint
- CARemoteEndpoint_t endpoint;
-
- //Get the device address from user
- char deviceaddress[100] = {0};
- printf("Enter the device address: \n");
- scanf("%s", deviceaddress);
-
- if (strlen(deviceaddress) == 0)
- {
- printf("Invlaid device address\n");
- return -1;
- }
-
- endpoint.connectivityType = CA_EDR;
- strncpy(endpoint.addressInfo.BT.btMacAddress, deviceaddress, CA_MACADDR_SIZE - 1);
- endpoint.addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
- endpoint.resourceUri = NULL;
-
- printf("Sent Unicast data to device: %s\n", endpoint.addressInfo.BT.btMacAddress);
- tempConnectivityHandlers->handler.sendData(&endpoint, coapData, strlen(coapData) + 1);
- }
- else if (CA_LE == connType)
- {
- //create endpoint
- CARemoteEndpoint_t endpoint;
-
- //Get the device address from user
- char deviceaddress[100] = {0};
- printf("Enter the device address: \n");
- scanf("%s", deviceaddress);
-
- if (strlen(deviceaddress) == 0)
- {
- printf("Invlaid device address\n");
- return -1;
- }
-
- //Get the service uuid from user
- char uuid[100] = {0};
- printf("Enter the service uuid: \n");
- scanf("%s", uuid);
-
- if (strlen(uuid) == 0)
- {
- printf("Invlaid service uuid\n");
- return -1;
- }
-
- endpoint.connectivityType = CA_LE;
- strncpy(endpoint.addressInfo.LE.leMacAddress, deviceaddress, CA_MACADDR_SIZE - 1);
- endpoint.addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
- endpoint.resourceUri = strdup(uuid);
-
- tempConnectivityHandlers->handler.sendData(&endpoint, coapData, strlen(coapData));
- printf("Sent Unicast data \n");
- free(endpoint.resourceUri);
- }
-
- return 1;
-}
-
-int16_t interfaceSendMulticastData(CAConnectivityType_t connType)
-{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- printf("None of the interface is initialized\n");
- return 0;
- }
-
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- if (NULL == tempConnectivityHandlers)
- {
- printf( "No interface handler for type %d", connType);
- return 0;
- }
-
- if (connType == CA_WIFI)
- {
- tempConnectivityHandlers->handler.sendDataToAll(coapData,
- strlen(coapData) + 1);
- }
- else if (connType == CA_EDR || connType == CA_LE)
- {
- tempConnectivityHandlers->handler.sendDataToAll(coapData, strlen(coapData));
- }
- return 0;
-}
-
-void interfaceReadData(CAConnectivityType_t connType)
-{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- printf("None of the interface is initialized\n");
- return;
- }
-
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- if (NULL == tempConnectivityHandlers)
- {
- printf( "No interface handler for type %d", connType);
- return;
- }
-
- if (CA_STATUS_OK != tempConnectivityHandlers->handler.readData())
- {
- printf("Failed to Read Data\n");
- return;
- }
-
- printf("Read Data is successfull\n");
- return;
-}
-
-void interfaceGetNetworkInfo(CAConnectivityType_t connType)
-{
- int i = 0;
-
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- printf("None of the interface is initialized\n");
- return;
- }
-
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- if (NULL == tempConnectivityHandlers)
- {
- printf( "No interface handler for type %d", connType);
- return;
- }
-
- //Get the network interface info
- CALocalConnectivity_t *info = NULL;
- uint32_t size = 0;
- if (CA_STATUS_OK != tempConnectivityHandlers->handler.GetnetInfo(&info, &size))
- {
- printf("Failed to get network info\n");
- return;
- }
-
- if (0 >= size || info == NULL)
- {
- printf("No network found !!!\n");
- return;
- }
-
- printf("Network Information: \n");
- for (; i < size; i++)
- {
- if (connType == CA_WIFI)
- {
- printf("Type : %s\n", (connType == CA_ETHERNET) ? "CA_ETHERNET" : "CA_WIFI");
- printf("Address : %s\n", info[i].addressInfo.IP.ipAddress);
- }
- else
- {
- printf("Type : %s\n", (connType == CA_EDR) ? "CA_EDR" : "CA_LE");
- printf("Address : %s\n\n", info[i].addressInfo.BT.btMacAddress);
- }
- }
-}
-
-int16_t interfaceStopAdapter(CAConnectivityType_t connType)
-{
- ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
- if (NULL == tempConnectivityHandlers)
- {
- printf("None of the interface is initialized\n");
- return 0;
- }
-
- while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
- {
- tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
- }
-
- if (NULL == tempConnectivityHandlers)
- {
- printf( "No interface handler for type %d", connType);
- return 0;
- }
-
- if (CA_STATUS_OK != tempConnectivityHandlers->handler.stopAdapter())
- {
- printf("Failed to Stop adapter\n");
- return 0;
- }
-
- printf("Stopped the adapter\n");
- return 1;
-}
-
-void testInitializeInterface()
-{
- printf("testInitializeInterface Entry\n");
-
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
- switch (type)
- {
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- testInitializeWIFIInterface();
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- testInitializeBTInterface();
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- testInitializeBLEInterface();
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
- }
-}
-
-void testTerminateInterface()
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
-#ifdef WIFI_ADAPTER_TEST
- if (1 == type) /* WIFI */
- {
- testTerminateWIFIInterface();
- }
-#endif
-#ifdef BT_ADAPTER_TEST
- if (2 == type) /*BT*/
- {
- testTerminateBTInterface();
- }
-#endif
-#ifdef BLE_ADAPTER_TEST
- if (3 == type) /*BLE*/
- {
- testTerminateBLEInterface();
- }
-#endif
-
- ConnectivityHandlerList *currentConnectivityHandler = gConnectivityHandlers;
- ConnectivityHandlerList *prevConnectivityHandler = NULL;
-
- printf("Linked list delete start\n");
- while (currentConnectivityHandler != NULL)
- {
- printf("Iterating through the list to find the matching interface\n");
- if (currentConnectivityHandler->type == type)
- {
- printf("Matching interface found\n");
- if (prevConnectivityHandler == NULL)
- {
- currentConnectivityHandler = currentConnectivityHandler->nextHandler;
- freeData(gConnectivityHandlers);
- gConnectivityHandlers = NULL;
- printf( "Node deleted with interface type %d", type);
- }
- else
- {
- prevConnectivityHandler->nextHandler = currentConnectivityHandler->nextHandler;
- freeData(currentConnectivityHandler);
- currentConnectivityHandler = prevConnectivityHandler->nextHandler;
- printf( "Node deleted with interface type %d from linked list", type);
- }
- }
- else
- {
- prevConnectivityHandler = currentConnectivityHandler;
- currentConnectivityHandler = currentConnectivityHandler->nextHandler;
- }
- }
- gConnectivityHandlers = NULL;
- return;
-}
-
-void testStartAdapter()
-{
- int type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
- switch (type)
- {
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceStartAdapter(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceStartAdapter(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceStartAdapter(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
- }
-}
-
-void testStartServer(int serverType)
-{
- int type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
- switch (type)
- {
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceMulticastStartServer(CA_WIFI, serverType);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceMulticastStartServer(CA_EDR, serverType);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceMulticastStartServer(CA_LE, serverType);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
- }
-}
-
-void testSendUnicastData()
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
- switch (type)
- {
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceSendUnicastData(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceSendUnicastData(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceSendUnicastData(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
- }
-}
-
-void testSendMulticastData()
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
- switch (type)
- {
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceSendMulticastData(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceSendMulticastData(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceSendMulticastData(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
- }
-}
-
-void testReadData(void)
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
- switch (type)
- {
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceReadData(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceReadData(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceReadData(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
- }
-}
-
-void testGetNetworkInfo(void)
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
- switch (type)
- {
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceGetNetworkInfo(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceGetNetworkInfo(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceGetNetworkInfo(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
- }
-}
-
-void testStopAdapter()
-{
- int16_t type = selectConnectivityType();
- if (0 >= type || 3 < type)
- {
- printf("Invalid selection...\n");
- return;
- }
-
- switch (type)
- {
-#ifdef WIFI_ADAPTER_TEST
- case 1: //WIFI
- {
- interfaceStopAdapter(CA_WIFI);
- }
- break;
-#endif
-#ifdef BT_ADAPTER_TEST
- case 2: //BT
- {
- interfaceStopAdapter(CA_EDR);
- }
- break;
-#endif
-#ifdef BLE_ADAPTER_TEST
- case 3: //BLE
- {
- interfaceStopAdapter(CA_LE);
- }
- break;
-#endif
- default:
- printf("Feature is not enabled or not implemented\n");
- }
-}
-
-#ifdef BT_ADAPTER_TEST
-void testInitializeBTInterface(void)
-{
- printf("Initiazing EDR\n");
-
- printf("Initializing BT Adapter threadpool\n");
- initializeThreadPool(CA_EDR);
-
- //Start bluetooth communication adapter
- CAResult_t err = CAInitializeEDR(interfaceRegisterCallback, networkPacketHandler,
- networkInterfaceCallback, gBTThreadPool);
- if (CA_STATUS_OK != err && CA_ADAPTER_NOT_ENABLED != err)
- {
- printf("Failed to initialize bluetooth communication adapter!\n");
- }
-}
-
-void testTerminateBTInterface(void)
-{
- printf("Terminating EDR\n");
-
- //Terminate the Bluetooth communication adapter
- CATerminateEDR();
-
- printf( "Terminating BT Adapter thread pool");
- u_thread_pool_free(gBTThreadPool);
- gBTThreadPool = NULL;
-}
-#endif //BT_ADAPTER_TEST
-
-#ifdef WIFI_ADAPTER_TEST
-void testInitializeWIFIInterface(void)
-{
- printf("testInitializeWIFIInterface IN\n");
-
- printf("Initializing WIFI adapter threadpool\n");
- initializeThreadPool(CA_WIFI);
-
- //Start Wifi communication adapter
- if (0 != CAInitializeWifi(interfaceRegisterCallback, networkPacketHandler,
- networkInterfaceCallback, gWiFiThreadPool))
- {
- printf("testInitializeWIFIInterface Failed to initialize bluetooth communication adapter\n");
- return;
- }
-
- printf("testInitializeWIFIInterface OUT\n");
-}
-
-void testTerminateWIFIInterface(void)
-{
- printf("testTerminateWIFIInterface IN\n");
-
- // Stop if Wifi communication adapter is running
- interfaceStopAdapter(CA_WIFI);
-
- // Freeing threadpool for wifi communication adapter
- printf( "Terminating WIFI Adapter thread pool");
- u_thread_pool_free(gWiFiThreadPool);
- gWiFiThreadPool = NULL;
-
- //Terminate the Wifi communication adapter
- CATerminateWIfI();
-
-
- printf("testTerminateWIFIInterface OUT\n");
-}
-#endif //WIFI_ADAPTER_TEST
-
-#ifdef BLE_ADAPTER_TEST
-void testInitializeBLEInterface(void)
-{
- printf("testInitializeBLEInterface IN\n");
-
- printf("Initializing BLE adapter threadpool\n");
- initializeThreadPool(CA_LE);
-
- //Start bluetooth communication adapter
- if (0 != CAInitializeLE(interfaceRegisterCallback, networkPacketHandler,
- networkInterfaceCallback, gLEThreadPool))
- {
- printf("testInitializeBLEInterface Failed due to CAInitializeLE\n");
- return;
- }
-
- printf("testInitializeBLEInterface OUT\n");
-}
-
-void testTerminateBLEInterface(void)
-{
- printf("testTerminateBLEInterface IN\n");
-
- //Terminate the BLE server & Client
- CATerminateLE();
-
- printf( "Terminating BLE Adapter thread pool");
- u_thread_pool_free(gLEThreadPool);
- gLEThreadPool = NULL;
-
- printf("testTerminateBLEInterface OUT\n");
-}
-#endif //BLE_ADAPTER_TEST
-
-static void testPrintHelp(void)
-{
- printf(" =====================================================================\n");
- printf("| Welcome to Connectivity Abstraction |\n");
- printf("| - CA Unit Test v1.0 - |\n");
- printf("|---------------------------------------------------------------------|\n");
- printf("| ** Options ** |\n");
- printf("| i - Initialize the Interface |\n");
- printf("| d - Terminate the Interface |\n");
- printf("| a - Start adapter |\n");
- printf("| b - Stop adapter |\n");
- printf("| sd- Start Discovery Server |\n");
- printf("| sl- Start Listening Server |\n");
- printf("| u - Send Unicast Data |\n");
- printf("| m - Send Multicast Data |\n");
- printf("| g - Get Network Info |\n");
- printf("| r - Read data synchronously |\n");
- printf("| x - quit the test. |\n");
- printf("| h - Help menu. |\n");
- printf(" =====================================================================\n");
-}
-
-static gboolean testThread(GIOChannel *source, GIOCondition condition , gpointer data)
-{
- gchar buf[10] = {'\0'};
- gsize read = 0;
-
- if (g_io_channel_read(channel, buf, 10, &read) != G_IO_ERROR_NONE)
- {
- printf("g_io_channel_read error!!!\n");
- return 1;
- }
- buf[read] = '\0';
- g_strstrip(buf);
-
- /*if ((!has_register) && (((buf[0]!= 'i') && (buf[0]!= 'h') && (buf[0]!= 'q')) || (read != 2))) {
- testPrintHelp();
- printf("***Warning***: You should Register firstly!\n");
- return 1;
- }*/
- switch (buf[0])
- {
- case 'i':
- testInitializeInterface();
- break;
- case 'x':
- testTerminateInterface();
- if (g_source_remove(g_test_io_watch_id))
- {
- printf("g_source_remove() OK!!!\n");
- g_io_channel_shutdown(channel, TRUE, &g_err_Sample);
- g_io_channel_unref(channel);
- g_main_loop_quit(mainloop);
- }
- break;
- case 'd':
- testTerminateInterface();
- break;
- case 'a':
- testStartAdapter();
- break;
- case 'b':
- testStopAdapter();
- break;
- case 's':
- if (read == 3)
- {
- if (buf[1] == 'd')
- {
- testStartServer(1);
- }
- if (buf[1] == 'l')
- {
- testStartServer(2);
- }
- }
- break;
- case 'u':
- testSendUnicastData();
- break;
- case 'm':
- testSendMulticastData();
- break;
- case 'r':
- testReadData();
- break;
- case 'g':
- testGetNetworkInfo();
- break;
- case 'h':
- testPrintHelp();
- }
- return 1;
-}
-
-int main(int argc, char *argv[])
-{
- printf("Starting sample\n");
- mainloop = g_main_loop_new(NULL, FALSE);
- channel = g_io_channel_unix_new(0);/* read from stdin */
- g_test_io_watch_id = g_io_add_watch(channel,
- (GIOCondition)(G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL), testThread,
- NULL);
- printf("CM Test Thread created...\n");
- testPrintHelp();
- g_main_loop_run(mainloop);
- return 0;
-}
-
%define PREFIX /usr/apps/com.oic.ca.sample
%define ROOTDIR %{_builddir}/%{name}-%{version}
-Name: com.oic.ca.sample
+Name: com-oic-ca-sample
Version: 0.1
Release: 1
Summary: Tizen adapter interfacesample application
URL: http://slp-source.sec.samsung.net
Source: %{name}-%{version}.tar.gz
-License: Apache License, Version 2.0
-Group: OIC/Application
-#BuildRequires: cmake
+License: Apache-2.0
+Group: Applications/OICSample
BuildRequires: pkgconfig(dlog)
BuildRequires: pkgconfig(glib-2.0)
BuildRequires: boost-devel
BuildRequires: boost-thread
BuildRequires: boost-system
BuildRequires: boost-filesystem
-#BuildRequires: oic-core
BuildRequires: pkgconfig(capi-network-wifi)
BuildRequires: pkgconfig(capi-network-bluetooth)
BuildRequires: scons
-BuildRequires: com.oic.ca
-#BuildRequires: com.samsung.oicca-devel
+BuildRequires: com-oic-ca
+
%description
-SLP interfacesample application
+OIC interfacesample application
%prep
%setup -q
scons TARGET_OS=tizen -c
scons TARGET_OS=tizen TARGET_TRANSPORT=%{TARGET_TRANSPORT}
-#make %{?jobs:-j%jobs}
-
%install
-rm -rf %{buildroot}
-# remove later
-#%make_install
-mkdir -p %{buildroot}/usr/share/license
-mkdir -p %{buildroot}/usr/share/license
-mkdir -p %{buildroot}/usr/share/packages
-mkdir -p %{buildroot}/etc/smack/accesses2.d
+
+mkdir -p %{buildroot}%{_datadir}/packages
+mkdir -p %{buildroot}/%{_sysconfdir}/smack/accesses2.d
mkdir -p %{buildroot}/usr/apps/com.oic.ca.sample/bin/
mkdir -p %{buildroot}/usr/apps/com.oic.ca.sample/bin/internal
-mkdir -p %{buildroot}/usr/lib
-cp -rf %{ROOTDIR}/com.oic.ca.sample.xml %{buildroot}/usr/share/packages
-cp -rf %{ROOTDIR}/com.oic.ca.sample.rule %{buildroot}/etc/smack/accesses2.d
-cp -rf %{ROOTDIR}/scons/interface_sample %{buildroot}/usr/apps/com.oic.ca.sample/bin/internal
+cp -rf %{ROOTDIR}/com.oic.ca.sample.xml %{buildroot}/%{_datadir}/packages
cp -rf %{ROOTDIR}/scons/ca_sample %{buildroot}/usr/apps/com.oic.ca.sample/bin/
%files
%manifest com.oic.ca.sample.manifest
-/etc/smack/accesses2.d/com.oic.ca.sample.rule
%defattr(-,root,root,-)
-%attr(-,inhouse,inhouse)
-/usr/apps/com.oic.ca.sample/bin/internal/interface_sample
/usr/apps/com.oic.ca.sample/bin/ca_sample
-#%{_libdir}/lib*.a*
-/usr/share/packages/com.oic.ca.sample.xml
-#/opt/share/process-info/cmsample.ini
-#/usr/share/license/%{name}
+/%{_datadir}/packages/com.oic.ca.sample.xml
+
+
build_dir = env.get('BUILD_DIR')
sample_dir = build_dir
-env.AppendUnique(CFLAGS = ['-std=c99', '-fPIC', '-D__TIZEN__','-DWITH_POSIX', '-Wall', '-DSLP_SDK_LOG', '-g','-D_GNU_SOURCE','-DTIZEN_DEBUG_ENABLE', '-DTB_LOG'])
+env.AppendUnique(CFLAGS = ['-std=c99', '-fPIC', '-D__TIZEN__','-DWITH_POSIX', '-Wall', '-DSLP_SDK_LOG', '-g','-D_GNU_SOURCE','-DTIZEN_DEBUG_ENABLE', '-DTB_LOG','`pkg-config', '--cflags', '--libs','dlog', 'com.oic.ca', 'capi-network-wifi',
+ 'gobject-2.0','glib-2.0`'])
env.Append(LIBPATH=[root_dir +'/lib/tizen/ble/libs/',])
env.Append(LIBS=[
- '-lm', '-lpthread', '-lrt', '-ldl', '-lstdc++', '-lconnectivity_abstraction', 'coap',
+ '-lm', '-lpthread', '-lrt', '-ldl', '-lstdc++', '-lgobject-2.0', '-lgio-2.0', '-lglib-2.0', '-lcapi-network-wifi', '-ldlog', '-lcapi-network-bluetooth', '-lconnectivity_abstraction', 'coap',
])
-env.ParseConfig("pkg-config --cflags --libs dlog com.oic.ca capi-network-wifi capi-network-bluetooth gobject-2.0 glib-2.0 gio-2.0")
-
env.Prepend(RPATH=[root_dir +'/lib/tizen/ble/libs/',])
if 'ALL' in transport:
env.AppendUnique(CPPDEFINES = ['WIFI_ADAPTER', 'NO_ETHERNET_ADAPTER','EDR_ADAPTER','LE_ADAPTER','BT_ADAPTER_TEST','BLE_ADAPTER_TEST','WIFI_ADAPTER_TEST'])
env.AppendUnique(CPPDEFINES = ['NO_WIFI_ADAPTER'])
-
-
-in_sample_src = [sample_dir + '/interfacesample.c']
ca_sample_src = [sample_dir + '/casample.c']
-
-print " interface sample src %s" % in_sample_src
print " ca sample src %s" % ca_sample_src
-env.Program('interface_sample', [in_sample_src,])
env.Program('ca_sample', [ca_sample_src,])
+
#Getting common source files
env.SConscript('./../common/SConscript')
+if env.get('SECURED') == '1':
+ env.SConscript('./../lib/tinydtls/SConscript')
+
env.AppendUnique(CA_SRC=[ca_path+'adapter_util/caadapterutils.c'])
env.AppendUnique(CA_SRC=[ca_path+'adapter_util/camsgparser.c'])
ca_path + 'canetworkconfigurator_singlethread.c',
ca_path + 'caprotocolmessage_singlethread.c',
ca_path + 'caremotehandler.c',
- ca_path + 'caretransmission_singlethread.cpp',
+ ca_path + 'caretransmission_singlethread.c',
]
else:
ca_common_src = [
calib = env.StaticLibrary('connectivity_abstraction', env.get('CA_SRC'))
env.InstallTarget(calib, 'libconnectivity_abstraction')
-if env.get('SECURED') == '1':
- env.Install(build_dir, './../lib/tinydtls/libtinydtls.a')
#include "cacommon.h"
#include "cawifiinterface.h"
#include "dtls.h"
-
+#include "oic_malloc.h"
/**
* @def NET_DTLS_TAG
#define NET_DTLS_TAG "NET_DTLS"
/**
- * @var gCaDtlsContext
+ * @var g_caDtlsContext
* @brief global context which holds dtls context and cache list information.
*/
-static stCADtlsContext_t *gCaDtlsContext = NULL;
+static stCADtlsContext_t *g_caDtlsContext = NULL;
/**
- * @var gDtlsContextMutex
- * @brief Mutex to synchronize access to gCaDtlsContext.
+ * @var g_dtlsContextMutex
+ * @brief Mutex to synchronize access to g_caDtlsContext.
*/
-static u_mutex gDtlsContextMutex = NULL;
+static u_mutex g_dtlsContextMutex = NULL;
/**
- * @var gDtlsListMutex
+ * @var g_dtlsListMutex
* @brief Mutex to synchronize access to DTLS Cache.
*/
-static u_mutex gDtlsListMutex = NULL;
+static u_mutex g_dtlsListMutex = NULL;
/**
- * @var gGetCredentialsCallback
+ * @var g_getCredentialsCallback
* @brief callback to get DTLS credentials
*/
-static CAGetDTLSCredentialsHandler gGetCredentialsCallback = NULL;
+static CAGetDTLSCredentialsHandler g_getCredentialsCallback = NULL;
static eDtlsRet_t CAAdapterNetDtlsEncryptInternal(const stCADtlsAddrInfo_t *dstSession,
uint8_t *data, uint32_t dataLen)
return DTLS_FAIL;
}
- u_mutex_lock(gDtlsContextMutex);
- if (NULL == gCaDtlsContext)
+ u_mutex_lock(g_dtlsContextMutex);
+ if (NULL == g_caDtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
- u_mutex_unlock(gDtlsContextMutex);
+ u_mutex_unlock(g_dtlsContextMutex);
return DTLS_FAIL;
}
- int32_t retLen = dtls_write(gCaDtlsContext->dtlsContext, (session_t *)dstSession, data,
+ int retLen = dtls_write(g_caDtlsContext->dtlsContext, (session_t *)dstSession, data,
dataLen);
OIC_LOG_V(DEBUG, NET_DTLS_TAG, "dtls_write retun len [%d]", retLen);
+ u_mutex_unlock(g_dtlsContextMutex);
+
if (0 == retLen)
{
// A new DTLS session was initiated by tinyDTLS library and wait for callback.
- u_mutex_unlock(gDtlsContextMutex);
return DTLS_SESSION_INITIATED;
}
- u_mutex_unlock(gDtlsContextMutex);
- if (dataLen == retLen)
+ else if (dataLen == retLen)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
return DTLS_OK;
eDtlsRet_t ret = DTLS_FAIL;
- /// TODO: how to protect gCaDtlsContext as dtls_handle_message is blocking call
- if (dtls_handle_message(gCaDtlsContext->dtlsContext, (session_t *)srcSession, buf, bufLen) == 0)
+ /// TODO: how to protect g_caDtlsContext as dtls_handle_message is blocking call
+ if (dtls_handle_message(g_caDtlsContext->dtlsContext, (session_t *)srcSession, buf, bufLen) == 0)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "dtls_handle_message success");
ret = DTLS_OK;
static void CAFreeCacheMsg(stCACacheMessage_t *msg)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
+ VERIFY_NON_NULL_VOID(msg, NET_DTLS_TAG, "msg");
OICFree(msg->destSession);
OICFree(msg->data);
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
uint32_t list_index = 0;
uint32_t list_length = 0;
- u_mutex_lock(gDtlsListMutex);
- if (NULL == gCaDtlsContext)
+ u_mutex_lock(g_dtlsListMutex);
+ if (NULL == g_caDtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Dtls Context is NULL");
- u_mutex_unlock(gDtlsListMutex);
+ u_mutex_unlock(g_dtlsListMutex);
return;
}
- list_length = u_arraylist_length(gCaDtlsContext->cacheList);
+ list_length = u_arraylist_length(g_caDtlsContext->cacheList);
for (list_index = 0; list_index < list_length; list_index++)
{
- stCACacheMessage_t *msg = (stCACacheMessage_t *)u_arraylist_get(gCaDtlsContext->cacheList,
+ stCACacheMessage_t *msg = (stCACacheMessage_t *)u_arraylist_get(g_caDtlsContext->cacheList,
list_index);
- if (msg == NULL)
+ if (msg != NULL)
{
- continue;
+ CAFreeCacheMsg(msg);
}
- CAFreeCacheMsg(msg);
}
- u_arraylist_free(&gCaDtlsContext->cacheList);
- gCaDtlsContext->cacheList = NULL;
- u_mutex_unlock(gDtlsListMutex);
+ u_arraylist_free(&g_caDtlsContext->cacheList);
+ g_caDtlsContext->cacheList = NULL;
+ u_mutex_unlock(g_dtlsListMutex);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
}
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
- u_mutex_lock(gDtlsListMutex);
- if (NULL == gCaDtlsContext)
+ u_mutex_lock(g_dtlsListMutex);
+ if (NULL == g_caDtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Dtls Context is NULL");
- u_mutex_unlock(gDtlsListMutex);
+ u_mutex_unlock(g_dtlsListMutex);
return CA_STATUS_FAILED;
}
- CAResult_t result = u_arraylist_add(gCaDtlsContext->cacheList, (void *)msg);
+ CAResult_t result = u_arraylist_add(g_caDtlsContext->cacheList, (void *)msg);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "u_arraylist_add failed!");
}
- u_mutex_unlock(gDtlsListMutex);
+ u_mutex_unlock(g_dtlsListMutex);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
return result;
}
-static CABool_t CAIsAddressMatching(const stCADtlsAddrInfo_t *a, const stCADtlsAddrInfo_t *b)
+static bool CAIsAddressMatching(const stCADtlsAddrInfo_t *a, const stCADtlsAddrInfo_t *b)
{
- if (a->size != b->size || a->addr.sa.sa_family != b->addr.sa.sa_family)
- return CA_FALSE;
-
- if ((a->addr.sin.sin_port == b->addr.sin.sin_port) &&
- (memcmp(&a->addr.sin.sin_addr, &b->addr.sin.sin_addr,
- sizeof(struct in_addr)) == 0))
- {
- return CA_TRUE;
- }
- return CA_FALSE;
+ return (a->size == b->size) &&
+ (a->addr.sa.sa_family == b->addr.sa.sa_family) &&
+ (a->addr.sin.sin_port == b->addr.sin.sin_port) &&
+ memcmp(&a->addr.sin.sin_addr, &b->addr.sin.sin_addr, sizeof(struct in_addr)) == 0;
}
static void CASendCachedMsg(const stCADtlsAddrInfo_t *dstSession)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
-
- ///TODO: if dstSession is coming as NULL, what we will do with cached msg.
- //(will be cleared in termination)
VERIFY_NON_NULL_VOID(dstSession, NET_DTLS_TAG, "Param dstSession is NULL");
uint32_t list_index = 0;
uint32_t list_length = 0;
- u_mutex_lock(gDtlsListMutex);
- list_length = u_arraylist_length(gCaDtlsContext->cacheList);
+ u_mutex_lock(g_dtlsListMutex);
+ list_length = u_arraylist_length(g_caDtlsContext->cacheList);
for (list_index = 0; list_index < list_length;)
{
- stCACacheMessage_t *msg = (stCACacheMessage_t *)u_arraylist_get(gCaDtlsContext->cacheList,
+ stCACacheMessage_t *msg = (stCACacheMessage_t *)u_arraylist_get(g_caDtlsContext->cacheList,
list_index);
- if ((NULL != msg) && (CA_TRUE == CAIsAddressMatching(msg->destSession, dstSession)))
+ if ((NULL != msg) && (true == CAIsAddressMatching(msg->destSession, dstSession)))
{
eDtlsRet_t ret = CAAdapterNetDtlsEncryptInternal(msg->destSession,
msg->data, msg->dataLen);
OIC_LOG(ERROR, NET_DTLS_TAG, "CAAdapterNetDtlsEncryptInternal failed.");
}
- if (u_arraylist_remove(gCaDtlsContext->cacheList, list_index))
+ if (u_arraylist_remove(g_caDtlsContext->cacheList, list_index))
{
CAFreeCacheMsg(msg);
// Reduce list length by 1 as we removed one element.
++list_index;
}
}
- u_mutex_unlock(gDtlsListMutex);
+ u_mutex_unlock(g_dtlsListMutex);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
}
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
VERIFY_NON_NULL_RET(session, NET_DTLS_TAG, "Param Session is NULL", 0);
-
OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Decrypted buf len [%d]", bufLen);
stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
uint32_t port = ntohs(addrInfo->addr.sin.sin_port);
eDtlsAdapterType_t type = (eDtlsAdapterType_t)addrInfo->ifIndex;
- u_mutex_lock(gDtlsContextMutex);
- if (NULL == gCaDtlsContext)
+ u_mutex_lock(g_dtlsContextMutex);
+ if (NULL == g_caDtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
- u_mutex_unlock(gDtlsContextMutex);
+ u_mutex_unlock(g_dtlsContextMutex);
return 0;
}
if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type) &&
- (NULL != gCaDtlsContext->adapterCallbacks[type].recvCallback))
+ (NULL != g_caDtlsContext->adapterCallbacks[type].recvCallback))
{
- gCaDtlsContext->adapterCallbacks[type].recvCallback(remoteAddress, port,
- buf, bufLen, CA_TRUE);
+ g_caDtlsContext->adapterCallbacks[type].recvCallback(remoteAddress, port,
+ buf, bufLen, true);
}
else
{
- OIC_LOG_V(DEBUG, NET_DTLS_TAG, "recvCallback Callback or adapter type is wrong [%d]", type );
+ OIC_LOG_V(DEBUG, NET_DTLS_TAG, "recvCallback Callback or adapter type is wrong [%d]", type);
}
- u_mutex_unlock(gDtlsContextMutex);
+ u_mutex_unlock(g_dtlsContextMutex);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
return 0;
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
- VERIFY_NON_NULL_RET(session, NET_DTLS_TAG, "Param Session is NULL", 0);
- VERIFY_NON_NULL_RET(buf, NET_DTLS_TAG, "Param buf is NULL", 0);
+ VERIFY_NON_NULL_RET(session, NET_DTLS_TAG, "Param Session is NULL", -1);
+ VERIFY_NON_NULL_RET(buf, NET_DTLS_TAG, "Param buf is NULL", -1);
if (0 == bufLen)
{
stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
char *remoteAddress = inet_ntoa(addrInfo->addr.sin.sin_addr);
- uint32_t port = ntohs(addrInfo->addr.sin.sin_port);
+ uint16_t port = ntohs(addrInfo->addr.sin.sin_port);
eDtlsAdapterType_t type = (eDtlsAdapterType_t)addrInfo->ifIndex;
- //Mutex is not required for gCaDtlsContext. It will be called in same thread.
+ //Mutex is not required for g_caDtlsContext. It will be called in same thread.
int32_t sentLen = 0;
if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type) &&
- (NULL != gCaDtlsContext->adapterCallbacks[type].sendCallback))
+ (NULL != g_caDtlsContext->adapterCallbacks[type].sendCallback))
{
- sentLen = gCaDtlsContext->adapterCallbacks[type].sendCallback(remoteAddress, port,
+ sentLen = g_caDtlsContext->adapterCallbacks[type].sendCallback(remoteAddress, port,
buf, bufLen);
}
else
int32_t ret = -1;
- VERIFY_NON_NULL_RET(gGetCredentialsCallback, NET_DTLS_TAG, "GetCredential callback", 0);
+ VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_DTLS_TAG, "GetCredential callback", -1);
+ VERIFY_NON_NULL_RET(result, NET_DTLS_TAG, "result", -1);
OCDtlsPskCredsBlob *credInfo = NULL;
- //Retrieve the credentials blob from security module
- // OCGetDtlsPskCredentials(&credInfo);
- gGetCredentialsCallback(&credInfo);
+ // Retrieve the credentials blob from security module
+ // OCGetDtlsPskCredentials(&credInfo);
+ g_getCredentialsCallback(&credInfo);
- VERIFY_NON_NULL_RET(credInfo, NET_DTLS_TAG, "CAGetDtlsPskCredentials credInfo is NULL", 0);
+ VERIFY_NON_NULL_RET(credInfo, NET_DTLS_TAG, "CAGetDtlsPskCredentials credInfo is NULL", -1);
if ((type == DTLS_PSK_HINT) || (type == DTLS_PSK_IDENTITY))
{
CAPacketSendCallback sendCallback, eDtlsAdapterType_t type)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
- u_mutex_lock(gDtlsContextMutex);
- if (NULL == gCaDtlsContext)
+ u_mutex_lock(g_dtlsContextMutex);
+ if (NULL == g_caDtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Context is NULL");
- u_mutex_unlock(gDtlsContextMutex);
+ u_mutex_unlock(g_dtlsContextMutex);
return;
}
if ((0 <= type) && (MAX_SUPPORTED_ADAPTERS > type))
{
- gCaDtlsContext->adapterCallbacks[type].recvCallback = recvCallback;
- gCaDtlsContext->adapterCallbacks[type].sendCallback = sendCallback;
+ g_caDtlsContext->adapterCallbacks[type].recvCallback = recvCallback;
+ g_caDtlsContext->adapterCallbacks[type].sendCallback = sendCallback;
}
- u_mutex_unlock(gDtlsContextMutex);
+ u_mutex_unlock(g_dtlsContextMutex);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
}
void CADTLSSetCredentialsCallback(CAGetDTLSCredentialsHandler credCallback)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
- gGetCredentialsCallback = credCallback;
+ g_getCredentialsCallback = credCallback;
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
}
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
- if (NULL == gDtlsContextMutex)
+ if (NULL == g_dtlsContextMutex)
{
- u_mutex_init();
- gDtlsContextMutex = u_mutex_new();
- VERIFY_NON_NULL_RET(gDtlsContextMutex, NET_DTLS_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
+ g_dtlsContextMutex = u_mutex_new();
+ VERIFY_NON_NULL_RET(g_dtlsContextMutex, NET_DTLS_TAG, "malloc failed",
+ CA_MEMORY_ALLOC_FAILED);
}
else
{
return CA_STATUS_OK;
}
- if (NULL == gDtlsListMutex)
+ if (NULL == g_dtlsListMutex)
{
- gDtlsListMutex = u_mutex_new();
- if (NULL == gDtlsListMutex)
+ g_dtlsListMutex = u_mutex_new();
+ if (NULL == g_dtlsListMutex)
{
- OIC_LOG(ERROR, NET_DTLS_TAG, "gDtlsListMutex malloc failed");
- u_mutex_free(gDtlsContextMutex);
+ OIC_LOG(ERROR, NET_DTLS_TAG, "g_dtlsListMutex malloc failed");
+ u_mutex_free(g_dtlsContextMutex);
return CA_MEMORY_ALLOC_FAILED;
}
}
- u_mutex_lock(gDtlsContextMutex);
- gCaDtlsContext = (stCADtlsContext_t *)OICMalloc(sizeof(stCADtlsContext_t));
+ u_mutex_lock(g_dtlsContextMutex);
+ g_caDtlsContext = (stCADtlsContext_t *)OICCalloc(1, sizeof(stCADtlsContext_t));
- if (NULL == gCaDtlsContext)
+ if (NULL == g_caDtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "Context malloc failed");
- u_mutex_unlock(gDtlsContextMutex);
- u_mutex_free(gDtlsContextMutex);
- u_mutex_free(gDtlsListMutex);
+ u_mutex_free(g_dtlsListMutex);
+ u_mutex_unlock(g_dtlsContextMutex);
+ u_mutex_free(g_dtlsContextMutex);
return CA_MEMORY_ALLOC_FAILED;
}
- memset(gCaDtlsContext, 0x0, sizeof(stCADtlsContext_t));
+ u_mutex_lock(g_dtlsListMutex);
+ g_caDtlsContext->cacheList = u_arraylist_create();
- u_mutex_lock(gDtlsListMutex);
- gCaDtlsContext->cacheList = u_arraylist_create();
-
- if (NULL == gCaDtlsContext->cacheList)
+ if (NULL == g_caDtlsContext->cacheList)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "cacheList initialization failed!");
- u_mutex_unlock(gDtlsListMutex);
- u_mutex_unlock(gDtlsContextMutex);
- u_mutex_free(gDtlsContextMutex);
- u_mutex_free(gDtlsListMutex);
- OICFree(gCaDtlsContext);
- gCaDtlsContext = NULL;
+ u_mutex_unlock(g_dtlsListMutex);
+ u_mutex_free(g_dtlsListMutex);
+ u_mutex_unlock(g_dtlsContextMutex);
+ u_mutex_free(g_dtlsContextMutex);
+ OICFree(g_caDtlsContext);
+ g_caDtlsContext = NULL;
return CA_STATUS_FAILED;
}
- u_mutex_unlock(gDtlsListMutex);
+ u_mutex_unlock(g_dtlsListMutex);
// Initialize clock, crypto and other global vars in tinyDTLS library
dtls_init();
- gCaDtlsContext->dtlsContext = dtls_new_context(gCaDtlsContext);
+ g_caDtlsContext->dtlsContext = dtls_new_context(g_caDtlsContext);
- if (NULL == gCaDtlsContext->dtlsContext)
+ if (NULL == g_caDtlsContext->dtlsContext)
{
OIC_LOG(ERROR, NET_DTLS_TAG, "dtls_new_context failed");
- u_mutex_unlock(gDtlsContextMutex);
+ u_mutex_unlock(g_dtlsContextMutex);
CAAdapterNetDtlsDeInit();
return CA_STATUS_FAILED;
}
- gCaDtlsContext->callbacks.write = CASendSecureData;
- gCaDtlsContext->callbacks.read = CAReadDecryptedPayload;
- gCaDtlsContext->callbacks.event = CAHandleSecureEvent;
- gCaDtlsContext->callbacks.get_psk_info = CAGetPskCredentials;
+ g_caDtlsContext->callbacks.write = CASendSecureData;
+ g_caDtlsContext->callbacks.read = CAReadDecryptedPayload;
+ g_caDtlsContext->callbacks.event = CAHandleSecureEvent;
+ g_caDtlsContext->callbacks.get_psk_info = CAGetPskCredentials;
- dtls_set_handler(gCaDtlsContext->dtlsContext, &(gCaDtlsContext->callbacks));
- u_mutex_unlock(gDtlsContextMutex);
+ dtls_set_handler(g_caDtlsContext->dtlsContext, &(g_caDtlsContext->callbacks));
+ u_mutex_unlock(g_dtlsContextMutex);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
return CA_STATUS_OK;
}
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
- VERIFY_NON_NULL_VOID(gCaDtlsContext, NET_DTLS_TAG, "context is NULL");
+ VERIFY_NON_NULL_VOID(g_caDtlsContext, NET_DTLS_TAG, "context is NULL");
- u_mutex_lock(gDtlsContextMutex);
+ u_mutex_lock(g_dtlsContextMutex);
CAClearCacheList();
- dtls_free_context(gCaDtlsContext->dtlsContext);
- gCaDtlsContext->dtlsContext = NULL;
- OICFree(gCaDtlsContext);
- gCaDtlsContext = NULL;
- u_mutex_unlock(gDtlsContextMutex);
-
- u_mutex_free(gDtlsContextMutex);
- gDtlsContextMutex = NULL;
- u_mutex_free(gDtlsListMutex);
- gDtlsListMutex = NULL;
+ dtls_free_context(g_caDtlsContext->dtlsContext);
+ g_caDtlsContext->dtlsContext = NULL;
+ OICFree(g_caDtlsContext);
+ g_caDtlsContext = NULL;
+ u_mutex_unlock(g_dtlsContextMutex);
+
+ u_mutex_free(g_dtlsContextMutex);
+ g_dtlsContextMutex = NULL;
+ u_mutex_free(g_dtlsListMutex);
+ g_dtlsListMutex = NULL;
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
}
CAResult_t CAAdapterNetDtlsEncrypt(const char *remoteAddress,
- const uint32_t port,
- const void *data,
+ const uint16_t port,
+ void *data,
uint32_t dataLen,
uint8_t *cacheFlag,
eDtlsAdapterType_t adapterType)
return CA_STATUS_FAILED;
}
- OIC_LOG_V(DEBUG, NET_DTLS_TAG, " Data to be encrypted dataLen [%d]", dataLen);
+ OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Data to be encrypted dataLen [%d]", dataLen);
- stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)OICMalloc(sizeof(stCADtlsAddrInfo_t));
+ stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)OICCalloc(1, sizeof(stCADtlsAddrInfo_t));
VERIFY_NON_NULL_RET(addrInfo, NET_DTLS_TAG, "malloc failed" , CA_MEMORY_ALLOC_FAILED);
- memset(addrInfo, 0x0, sizeof(stCADtlsAddrInfo_t));
-
addrInfo->addr.sin.sin_family = AF_INET;
addrInfo->addr.sin.sin_port = htons(port);
// Conversion from ASCII format to Network format
addrInfo->size = sizeof(addrInfo->addr);
addrInfo->ifIndex = adapterType;
- ///TODO: we need to check this memory allocation is needed or not
- uint8_t *buf = (uint8_t *)OICMalloc(sizeof(uint8_t) * (dataLen + 1));
- if (NULL == buf)
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "malloc failed!");
- OICFree(addrInfo);
- return CA_MEMORY_ALLOC_FAILED;
- }
- memset(buf, 0x0, sizeof(uint8_t) * (dataLen + 1));
- memcpy(buf, data, dataLen);
-
- eDtlsRet_t ret = CAAdapterNetDtlsEncryptInternal(addrInfo, buf, dataLen);
+ eDtlsRet_t ret = CAAdapterNetDtlsEncryptInternal(addrInfo, data, dataLen);
if (ret == DTLS_SESSION_INITIATED)
{
- stCACacheMessage_t *message = (stCACacheMessage_t *)OICMalloc(sizeof(stCACacheMessage_t));
+ stCACacheMessage_t *message = (stCACacheMessage_t *)OICCalloc(1, sizeof(stCACacheMessage_t));
if (NULL == message)
{
- OIC_LOG(ERROR, NET_DTLS_TAG, "malloc failed!");
+ OIC_LOG(ERROR, NET_DTLS_TAG, "calloc failed!");
OICFree(addrInfo);
- OICFree(buf);
return CA_MEMORY_ALLOC_FAILED;
}
- memset(message, 0x0, sizeof(stCACacheMessage_t));
- message->data = buf;
+ message->data = (uint8_t *)OICCalloc(dataLen + 1, sizeof(uint8_t));
+ if (NULL == message->data)
+ {
+ OIC_LOG(ERROR, NET_DTLS_TAG, "calloc failed!");
+ OICFree(addrInfo);
+ OICFree(message);
+ return CA_MEMORY_ALLOC_FAILED;
+ }
+ memcpy(message->data, data, dataLen);
message->dataLen = dataLen;
message->destSession = addrInfo;
return result;
}
+ OICFree(addrInfo);
+
if (ret == DTLS_OK)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
- OICFree(addrInfo);
- OICFree(buf);
return CA_STATUS_OK;
}
- OICFree(addrInfo);
- OICFree(buf);
+
OIC_LOG(ERROR, NET_DTLS_TAG, "OUT FAILURE");
return CA_STATUS_FAILED;
}
CAResult_t CAAdapterNetDtlsDecrypt(const char *remoteAddress,
- const uint32_t port,
+ const uint16_t port,
uint8_t *data,
uint32_t dataLen,
eDtlsAdapterType_t adapterType)
{
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
- stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)OICMalloc(sizeof(stCADtlsAddrInfo_t));
-
- VERIFY_NON_NULL_RET(addrInfo, NET_DTLS_TAG, "malloc failed" , CA_MEMORY_ALLOC_FAILED);
+ stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)OICCalloc(1, sizeof(stCADtlsAddrInfo_t));
- memset(addrInfo, 0x0, sizeof(stCADtlsAddrInfo_t));
+ VERIFY_NON_NULL_RET(addrInfo, NET_DTLS_TAG, "calloc failed" , CA_MEMORY_ALLOC_FAILED);
addrInfo->addr.sin.sin_family = AF_INET;
addrInfo->addr.sin.sin_port = htons(port);
+
// Conversion from ASCII format to Network format
if (inet_aton(remoteAddress, &addrInfo->addr.sin.sin_addr) == 0)
{
addrInfo->size = sizeof(addrInfo->addr);
addrInfo->ifIndex = adapterType;
- uint8_t *buf = (uint8_t *)OICMalloc(sizeof(uint8_t) * (dataLen + 1));
- if (NULL == buf)
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "malloc failed!");
- OICFree(addrInfo);
- return CA_MEMORY_ALLOC_FAILED;
- }
- memset(buf, 0x0, sizeof(uint8_t) * (dataLen + 1));
- memcpy(buf, data, dataLen);
+ eDtlsRet_t ret = CAAdapterNetDtlsDecryptInternal(addrInfo, data, dataLen);
- eDtlsRet_t ret = CAAdapterNetDtlsDecryptInternal(addrInfo, buf, dataLen);
+ OICFree(addrInfo);
if (DTLS_OK == ret || DTLS_HS_MSG == ret)
{
OIC_LOG_V(DEBUG, NET_DTLS_TAG, "Successfully Decrypted or Handshake msg recvd [%d]", ret);
- OICFree(buf);
- OICFree(addrInfo);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
return CA_STATUS_OK;
}
- OICFree(buf);
- OICFree(addrInfo);
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT FAILURE");
return CA_STATUS_FAILED;
}
+
#include "caadapterutils.h"
#include <string.h>
+#include <ctype.h>
#include "oic_malloc.h"
#include "oic_string.h"
#define CA_ADAPTER_UTILS_TAG "CA_ADAPTER_UTILS"
+void CALogPDUData(coap_pdu_t *pdu)
+{
+ VERIFY_NON_NULL_VOID(pdu, CA_ADAPTER_UTILS_TAG, "pdu");
+ OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - payload : %s", pdu->data);
+
+ OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - type : %d", pdu->hdr->type);
+
+ OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - code : %d", pdu->hdr->code);
+
+ OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - id : %d", pdu->hdr->id);
+
+ OIC_LOG_V(DEBUG, CA_ADAPTER_UTILS_TAG, "PDU Maker - token : %s", pdu->hdr->token);
+}
+
CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CAConnectivityType_t type,
const char *address)
{
CALocalConnectivity_t *info = (CALocalConnectivity_t *)
- OICMalloc(sizeof(CALocalConnectivity_t));
+ OICCalloc(1, sizeof(CALocalConnectivity_t));
if (NULL == info)
{
OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
return NULL;
}
- memset(info, 0, sizeof(CALocalConnectivity_t));
info->type = type;
if (address && strlen(address))
strncpy(info->addressInfo.IP.ipAddress, address, CA_IPADDR_SIZE - 1);
info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
}
+ else
+ {
+ OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
+ OICFree(info);
+ return NULL;
+ }
}
return info;
}
-CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(CALocalConnectivity_t *connectivity)
+CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(const CALocalConnectivity_t *connectivity)
{
VERIFY_NON_NULL_RET(connectivity, CA_ADAPTER_UTILS_TAG, "connectivity is NULL", NULL);
CALocalConnectivity_t *info = (CALocalConnectivity_t *)
- OICMalloc(sizeof(CALocalConnectivity_t));
+ OICCalloc(1, sizeof(CALocalConnectivity_t));
if (NULL == info)
{
OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
return NULL;
}
- memset(info, 0, sizeof(CALocalConnectivity_t));
info->type = connectivity->type;
if (CA_EDR == info->type && strlen(connectivity->addressInfo.BT.btMacAddress))
info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
info->addressInfo.IP.port = connectivity->addressInfo.IP.port;
}
+ else
+ {
+ OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
+ OICFree(info);
+ return NULL;
+ }
info->isSecured = connectivity->isSecured;
return info;
void CAAdapterFreeLocalEndpoint(CALocalConnectivity_t *localEndpoint)
{
- if (localEndpoint)
- {
- OICFree(localEndpoint);
- }
+ OICFree(localEndpoint);
}
CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CAConnectivityType_t type,
const char *resourceUri)
{
CARemoteEndpoint_t *info = (CARemoteEndpoint_t *)
- OICMalloc(sizeof(CARemoteEndpoint_t));
+ OICCalloc(1, sizeof(CARemoteEndpoint_t));
if (NULL == info)
{
OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
return NULL;
}
- memset(info, 0, sizeof(CARemoteEndpoint_t));
info->connectivityType = type;
if (address && strlen(address))
strncpy(info->addressInfo.BT.btMacAddress, address, CA_MACADDR_SIZE - 1);
info->addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
}
- else if (CA_LE == info->connectivityType)
+ else if (CA_LE == type)
{
strncpy(info->addressInfo.LE.leMacAddress, address, CA_MACADDR_SIZE - 1);
info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
strncpy(info->addressInfo.IP.ipAddress, address, CA_IPADDR_SIZE - 1);
info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
}
+ else
+ {
+ OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "type is not matched with any transport!");
+ OICFree(info);
+ return NULL;
+ }
}
if (resourceUri && strlen(resourceUri))
VERIFY_NON_NULL_RET(remoteEndpoint, CA_ADAPTER_UTILS_TAG, "Remote endpoint is NULL", NULL);
CARemoteEndpoint_t *info = (CARemoteEndpoint_t *)
- OICMalloc(sizeof(CARemoteEndpoint_t));
+ OICCalloc(1, sizeof(CARemoteEndpoint_t));
if (NULL == info)
{
OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
return NULL;
}
- memset(info, 0, sizeof(CARemoteEndpoint_t));
info->connectivityType = remoteEndpoint->connectivityType;
if (CA_EDR == info->connectivityType && strlen(remoteEndpoint->addressInfo.BT.btMacAddress))
info->addressInfo.IP.ipAddress[CA_IPADDR_SIZE - 1] = '\0';
info->addressInfo.IP.port = remoteEndpoint->addressInfo.IP.port;
}
+ else
+ {
+ OIC_LOG(DEBUG, CA_ADAPTER_UTILS_TAG, "Its not matching. May be multicast.");
+ }
+
+ //For Multicast, remote address will be null while resourceUri will have the service UUID
if (remoteEndpoint->resourceUri && strlen(remoteEndpoint->resourceUri))
{
{
if (remoteEndpoint)
{
- if (remoteEndpoint->resourceUri)
- {
- OICFree(remoteEndpoint->resourceUri);
- }
-
+ OICFree(remoteEndpoint->resourceUri);
OICFree(remoteEndpoint);
}
}
-bool CAAdapterIsSameSubnet(const char *ipAddress1, const char *ipAddress2,
- const char *netMask)
+CAResult_t CAParseIPv4AddressInternal(const char *ipAddrStr, uint8_t *ipAddr,
+ size_t ipAddrLen, uint16_t *port)
{
- VERIFY_NON_NULL_RET(ipAddress1, CA_ADAPTER_UTILS_TAG, "First address", false);
- VERIFY_NON_NULL_RET(ipAddress2, CA_ADAPTER_UTILS_TAG, "Second address", false);
- VERIFY_NON_NULL_RET(netMask, CA_ADAPTER_UTILS_TAG, "netMask", false);
-
- int32_t ipList1[8] = {0};
- int32_t ipList2[8] = {0};
- int32_t maskList[8] = {0};
-
- /* Local Loopback Address */
- if (0 == strncmp(ipAddress1, "127.", 4)
- || 0 == strncmp(ipAddress2, "127.", 4))
+ if (!ipAddr || !isdigit(ipAddrStr[0]) || !port)
{
- return true;
+ OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "invalid param");
+ return CA_STATUS_INVALID_PARAM;
}
- char *ipAdrs1 = OICStrdup(ipAddress1);
- if (!ipAdrs1)
+ size_t index = 0;
+ uint8_t dotCount = 0;
+
+ ipAddr[index] = 0;
+ *port = 0;
+ while (*ipAddrStr)
{
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Failed to get dup string!");
- return false;
+ if (isdigit(*ipAddrStr))
+ {
+ if(index >= ipAddrLen)
+ {
+ OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "invalid param");
+ return CA_STATUS_INVALID_PARAM;
+ }
+ ipAddr[index] *= 10;
+ ipAddr[index] += *ipAddrStr - '0';
+ }
+ else if (*ipAddrStr == '.')
+ {
+ index++;
+ dotCount++;
+ ipAddr[index] = 0;
+ }
+ else
+ {
+ break;
+ }
+ ipAddrStr++;
}
- int16_t index = 0;
- int16_t lastDotIndex = 0;
- int16_t ip1TokenCount = 0;
- while ('\0' != ipAdrs1[index])
+ if (*ipAddrStr == ':')
{
- if ('.' == ipAdrs1[index])
+ ipAddrStr++;
+ while (*ipAddrStr)
{
- ipAdrs1[index] = '\0';
- ipList1[ip1TokenCount++] = atoi(ipAdrs1 + lastDotIndex);
- lastDotIndex = index + 1;
+ if (isdigit(*ipAddrStr))
+ {
+ *port *= 10;
+ *port += *ipAddrStr - '0';
+ }
+ else
+ {
+ break;
+ }
+ ipAddrStr++;
}
- index++;
}
- // Add last touple
- ipList1[ip1TokenCount] = atoi(ipAdrs1 + lastDotIndex);
- char *ipAdrs2 = OICStrdup(ipAddress2);
- if (!ipAdrs2)
+ if (dotCount == 3)
{
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Failed to get dup string!");
- OICFree(ipAdrs1);
- return false;
+ return CA_STATUS_OK;
}
+ return CA_STATUS_FAILED;
+}
- index = 0;
- lastDotIndex = 0;
- int16_t ip2TokenCount = 0;
- while ('\0' != ipAdrs2[index])
+bool CAAdapterIsSameSubnet(const char *ipAddress1, const char *ipAddress2,
+ const char *netMask)
+{
+ VERIFY_NON_NULL_RET(ipAddress1, CA_ADAPTER_UTILS_TAG, "First address", false);
+ VERIFY_NON_NULL_RET(ipAddress2, CA_ADAPTER_UTILS_TAG, "Second address", false);
+ VERIFY_NON_NULL_RET(netMask, CA_ADAPTER_UTILS_TAG, "netMask", false);
+
+ uint8_t ipList1[IPV4_ADDR_ONE_OCTECT_LEN] = {0};
+ uint8_t ipList2[IPV4_ADDR_ONE_OCTECT_LEN] = {0};
+ uint8_t maskList[IPV4_ADDR_ONE_OCTECT_LEN] = {0};
+ CAResult_t ret = CA_STATUS_OK;
+
+ /* Local Loopback Address */
+ if (0 == strncmp(ipAddress1, "127.", 4)
+ || 0 == strncmp(ipAddress2, "127.", 4))
{
- if ('.' == ipAdrs2[index])
- {
- ipAdrs2[index] = '\0';
- ipList2[ip2TokenCount++] = atoi(ipAdrs2 + lastDotIndex);
- lastDotIndex = index + 1;
- }
- index++;
+ return true;
}
- // Add last touple
- ipList2[ip2TokenCount] = atoi(ipAdrs2 + lastDotIndex);
- char *nMask = OICStrdup(netMask);
- if (!nMask)
+ uint16_t parsedPort = 0;
+ ret = CAParseIPv4AddressInternal(ipAddress1, ipList1, sizeof(ipList1),
+ &parsedPort);
+ if (ret != CA_STATUS_OK)
{
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Failed to get dup string!");
- OICFree(ipAdrs1);
- OICFree(ipAdrs2);
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "First ip address parse fail %d", ret);
return false;
}
- index = 0;
- lastDotIndex = 0;
- int16_t maskTokenCount = 0;
- while ('\0' != nMask[index])
+ ret = CAParseIPv4AddressInternal(ipAddress2, ipList2, sizeof(ipList2),
+ &parsedPort);
+ if (ret != CA_STATUS_OK)
{
- if ('.' == nMask[index])
- {
- nMask[index] = '\0';
- maskList[maskTokenCount++] = atoi(nMask + lastDotIndex);
- lastDotIndex = index + 1;
- }
- index++;
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Second ip address parse fail %d", ret);
+ return false;
}
- // Add last touple
- maskList[maskTokenCount] = atoi(nMask + lastDotIndex);
-
- OICFree(ipAdrs1);
- OICFree(ipAdrs2);
- OICFree(nMask);
- if (ip1TokenCount < 3 || ip2TokenCount < 3 || maskTokenCount < 3)
+ ret = CAParseIPv4AddressInternal(netMask, maskList, sizeof(maskList),
+ &parsedPort);
+ if (ret != CA_STATUS_OK)
{
- OIC_LOG(ERROR, CA_ADAPTER_UTILS_TAG, "Address or mask is invalid!");
+ OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Net mask parse fail %d", ret);
return false;
}
- if (((ipList1[0]& maskList[0]) == (ipList2[0]& maskList[0]))
- && ((ipList1[1]& maskList[1]) == (ipList2[1]& maskList[1]))
- && ((ipList1[2]& maskList[2]) == (ipList2[2]& maskList[2]))
- && ((ipList1[3]& maskList[3]) == (ipList2[3]& maskList[3])))
- {
- return true;
- }
- return false;
+ return ((ipList1[0] & maskList[0]) == (ipList2[0] & maskList[0]))
+ && ((ipList1[1] & maskList[1]) == (ipList2[1] & maskList[1]))
+ && ((ipList1[2] & maskList[2]) == (ipList2[2] & maskList[2]))
+ && ((ipList1[3] & maskList[3]) == (ipList2[3] & maskList[3]));
}
+
#define CA_MSG_PARSER_TAG "CA_MSG_PARSER"
-
-void printBinaryFormat(char *data)
-{
- OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "IN");
- int i;
- for (i = 0; i < 8; i++)
- {
- OIC_LOG_V(DEBUG, CA_MSG_PARSER_TAG, "c[%d]: %d", i, !!((*data << i) & 0x80));
- }
-
- OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "OUT");
-
-}
+#define MAX_PARSE_DATA_LENGTH 4095
CAResult_t CAGenerateHeader(char *header, uint32_t length)
{
OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "IN");
VERIFY_NON_NULL(header, CA_MSG_PARSER_TAG, "header is NULL");
-
memset(header, 0x0, sizeof(char) * 2);
- *(header + 1) = length & 0xFF;
- length = length >> 8;
- *header = length & 0xFF;
- *header |= 0x40; // 0100 being set as first four bits.
+ if(length > MAX_PARSE_DATA_LENGTH)
+ {
+ OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "Given length is more than 4095.It will be truncated");
+ }
+ //if length is more than 4095 then it will be truncated.
+ header[1] = length & 0xFF;
+ length >>= 8;
+ header[0] = length & 0x0F;
OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "OUT");
return CA_STATUS_OK;
OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "IN");
VERIFY_NON_NULL(header, CA_MSG_PARSER_TAG, "header is NULL");
- uint32_t dataLen = 0;
- char localHeader[CA_HEADER_LENGTH];
- memcpy(localHeader, header, CA_HEADER_LENGTH);
- *localHeader &= 0x0F;
- dataLen = *localHeader & 0xFF;
- dataLen = dataLen << 8;
- dataLen += *(localHeader + 1) & 0xFF;
+ uint32_t dataLen = ((header[0] & 0x0F) << 8) | (header[1] & 0xFF);
OIC_LOG(DEBUG, CA_MSG_PARSER_TAG, "OUT");
return dataLen;
}
+
#Source files to build in Android platform
if target_os == 'android':
- env.AppendUnique(CA_SRC=[src_dir+'android/caedradapter.c',
+ env.AppendUnique(CA_SRC=[src_dir+'caedradapter.c',
])
+
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
#include <stdio.h>
#include <string.h>
#include <jni.h>
#include "oic_malloc.h"
#include "uthreadpool.h" /* for thread pool */
#include "umutex.h"
+#include "uarraylist.h"
#include "caadapterutils.h"
-#include "com_iotivity_jar_CAEDRInterface.h"
//#define DEBUG_MODE
#define TAG PCF("CA_EDR_CLIENT")
static const char *CLASSPATH_BT_ADPATER = "android/bluetooth/BluetoothAdapter";
static const char *CLASSPATH_BT_UUID = "java/util/UUID";
-static const uint32_t STATE_CONNECTED = 1;
-static const uint32_t STATE_DISCONNECTED = 0;
+static const uint32_t MAX_PDU_BUFFER = 1024;
+
+static u_arraylist_t *g_deviceStateList = NULL;
+static u_arraylist_t *g_deviceObjectList = NULL;
-static u_thread_pool_t gThreadPoolHandle = NULL;
+static u_thread_pool_t g_threadPoolHandle = NULL;
static JavaVM *g_jvm;
-static jobject gContext;
+static jobject g_context;
+
+static jbyteArray g_sendBuffer;
+
+/**
+ * @var g_mutexSocketListManager
+ * @brief Mutex to synchronize socket list update
+ */
+static u_mutex g_mutexSocketListManager;
// server socket instance
-static jobject gServerSocketObject = NULL;
+static jobject g_serverSocketObject = NULL;
/**
- * @var gMutexUnicastServer
+ * @var g_mutexUnicastServer
* @brief Mutex to synchronize unicast server
*/
-static u_mutex gMutexUnicastServer = NULL;
+static u_mutex g_mutexUnicastServer = NULL;
/**
- * @var gStopUnicast
+ * @var g_stopUnicast
* @brief Flag to control the Receive Unicast Data Thread
*/
-static bool gStopUnicast = FALSE;
+static bool g_stopUnicast = false;
/**
- * @var gMutexMulticastServer
+ * @var g_mutexMulticastServer
* @brief Mutex to synchronize secure multicast server
*/
-static u_mutex gMutexMulticastServer = NULL;
+static u_mutex g_mutexMulticastServer = NULL;
/**
- * @var gStopMulticast
+ * @var g_stopMulticast
* @brief Flag to control the Receive Multicast Data Thread
*/
-static bool gStopMulticast = FALSE;
+static bool g_stopMulticast = false;
/**
- * @var gStopAccept
+ * @var g_stopAccept
* @brief Flag to control the Accept Thread
*/
-static bool gStopAccept = FALSE;
+static bool g_stopAccept = false;
typedef struct send_data {
char* address;
bool *stopFlag;
} CAAdapterAcceptThreadContext_t;
-/**
- * implement for BT-EDR adapter common method
- */
+
+// TODO: It will be updated when android EDR support is added
CAResult_t CAEDRGetInterfaceInformation(CALocalConnectivity_t **info)
{
- OIC_LOG_V(DEBUG, TAG, "IN - CAEDRGetInterfaceInformation");
-
- CALocalConnectivity_t *netInfo = NULL;
-
- int32_t netInfoSize = 1;
-
- netInfo = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t) * netInfoSize);
- if(NULL == netInfo)
- {
- OIC_LOG_V(ERROR, TAG, "Invalid input..");
- return CA_MEMORY_ALLOC_FAILED;
- }
- memset(netInfo, 0, sizeof(CALocalConnectivity_t) * netInfoSize);
-
- char *macAddress = NULL;
- CAResult_t ret = CAEDRGetInterfaceInfo(&macAddress);
- OIC_LOG_V(ERROR, TAG, "address : %s", macAddress);
- if (CA_STATUS_OK != ret || NULL == macAddress)
- {
- OIC_LOG_V(ERROR, TAG, "Failed to get interface info [%d]", ret);
-
- OICFree(netInfo);
- OICFree(macAddress);
- return ret;
- }
-
- // Create local endpoint using util function
- CALocalConnectivity_t *endpoint = CAAdapterCreateLocalEndpoint(CA_EDR, macAddress);
- if (NULL == endpoint)
- {
- OIC_LOG_V(ERROR, TAG, "Failed to create Local Endpoint!",
- CA_MEMORY_ALLOC_FAILED);
- OICFree(netInfo);
- OICFree(macAddress);
- return CA_MEMORY_ALLOC_FAILED;
- }
-
- // copy unicast server information
- endpoint->isSecured = CA_FALSE;
- memcpy(&netInfo[0], endpoint, sizeof(CALocalConnectivity_t));
- *info = netInfo;
-
- OICFree(macAddress);
- CAAdapterFreeLocalEndpoint(endpoint);
+ OIC_LOG_V(DEBUG, TAG, "IN");
- OIC_LOG_V(DEBUG, TAG, "OUT - CAEDRGetInterfaceInformation");
+ OIC_LOG_V(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
-void CAEDRTerminateClient()
+void CAEDRClientTerminate()
{
OIC_LOG(DEBUG, TAG, "IN");
CAEDRTerminate();
}
CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength)
+ const void *data, uint32_t dataLength, uint32_t *sentLength)
{
OIC_LOG_V(DEBUG, TAG, "IN");
CAEDRSendUnicastMessage(remoteAddress, (const char*) data, dataLength);
}
-CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, void *data,
+CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, const void *data,
uint32_t dataLength, uint32_t *sentLength)
{
OIC_LOG_V(DEBUG, TAG, "IN");
return CA_STATUS_OK;
}
+// TODO: It will be updated when android EDR support is added
void CAEDRClientUnsetCallbacks(void)
{
OIC_LOG_V(DEBUG, TAG, "IN");
OIC_LOG_V(DEBUG, TAG, "OUT");
}
+// TODO: It will be updated when android EDR support is added
void CAEDRClientDisconnectAll(void)
{
OIC_LOG_V(DEBUG, TAG, "IN");
OIC_LOG_V(DEBUG, TAG, "OUT");
}
-CAResult_t CAEDRGetAdapterEnableState(CABool_t *state)
+CAResult_t CAEDRGetAdapterEnableState(bool *state)
{
OIC_LOG_V(DEBUG, TAG, "IN");
-
- jboolean isAttached = FALSE;
+ if (!g_jvm)
+ {
+ OIC_LOG_V(ERROR, TAG, "g_jvm is null");
+ return CA_STATUS_INVALID_PARAM;
+ }
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
if(res != JNI_OK)
{
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return CA_STATUS_FAILED;
+ return CA_STATUS_INVALID_PARAM;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
jboolean ret = CAEDRNativeIsEnableBTAdapter(env);
if(ret)
{
- *state = CA_TRUE;
+ *state = true;
}
else
{
- *state = CA_FALSE;
+ *state = false;
}
if(isAttached)
////////////////////////////////////////////////////////////////////////////////////////////////////
//FIXME getting context
-void CAEDRJniSetContext()
+void CAEDRJniSetContext(jobject context)
{
- OIC_LOG_V(DEBUG, TAG, "CAEDRJniSetContext");
+ OIC_LOG_V(DEBUG, TAG, "caedrSetObject");
+
+ if (!context)
+ {
+ OIC_LOG_V(ERROR, TAG, "context is null");
+ return;
+ }
+ jboolean isAttached = JNI_FALSE;
+ JNIEnv* env;
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
+ if(res != JNI_OK)
+ {
+ OIC_LOG_V(DEBUG, TAG, "CAEDRInitialize - Could not get JNIEnv pointer");
+ res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- gContext = CANativeJNIGetContext();
+ if(res != JNI_OK)
+ {
+ OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ return;
+ }
+ isAttached = JNI_TRUE;
+ }
+
+ g_context = (*env)->NewGlobalRef(env, context);
+
+ if(isAttached)
+ (*g_jvm)->DetachCurrentThread(g_jvm);
}
void CAEDRCreateJNIInterfaceObject(jobject context)
return;
}
- //Create EDRJniInterface instance
- jclass EDRJniInterface = (*env)->FindClass(env, "com/iotivity/jar/CAEDRInterface");
- if (!EDRJniInterface)
+ jobject gApplicationContext = (*env)->CallObjectMethod(env, context,
+ getApplicationContextMethod);
+ OIC_LOG_V(DEBUG, TAG,
+ "[WIFICore] Saving Android application context object %p", gApplicationContext);
+
+ //Create WiFiInterface instance
+ jclass WiFiJniInterface = (*env)->FindClass(env, "com/iotivity/jar/CAEDRInterface");
+ if (!WiFiJniInterface)
{
- OIC_LOG_V(DEBUG, TAG, "[EDRCore] Could not get CAEDRInterface class");
+ OIC_LOG_V(DEBUG, TAG, "[EDRCore] Could not get CAWiFiInterface class");
return;
}
- jmethodID EDRInterfaceConstructorMethod = (*env)->GetMethodID(env,
- EDRJniInterface, "<init>", "(Landroid/content/Context;)V");
- if (!EDRInterfaceConstructorMethod)
+ jmethodID WiFiInterfaceConstructorMethod = (*env)->GetMethodID(env,
+ WiFiJniInterface, "<init>", "(Landroid/content/Context;)V");
+ if (!WiFiInterfaceConstructorMethod)
{
- OIC_LOG_V(DEBUG, TAG, "[EDRCore] Could not get CAEDRInterface constructor method");
+ OIC_LOG_V(ERROR, TAG, "[EDRCore] Could not get CAWiFiInterface constructor method");
return;
}
- (*env)->NewObject(env, EDRJniInterface, EDRInterfaceConstructorMethod, context);
+ (*env)->NewObject(env, WiFiJniInterface, WiFiInterfaceConstructorMethod, gApplicationContext);
+ OIC_LOG_V(DEBUG, TAG, "[EDRCore] Create CAWiFiInterface instance");
OIC_LOG_V(DEBUG, TAG, "[EDRCore] NewObject Success");
}
{
OIC_LOG(DEBUG, TAG, "IN");
- if (gMutexUnicastServer)
+ if (g_mutexUnicastServer)
{
- u_mutex_free(gMutexUnicastServer);
- gMutexUnicastServer = NULL;
+ u_mutex_free(g_mutexUnicastServer);
+ g_mutexUnicastServer = NULL;
}
-#ifdef __WITH_DTLS__
-
-#endif
+ if (g_mutexMulticastServer)
+ {
+ u_mutex_free(g_mutexMulticastServer);
+ g_mutexMulticastServer = NULL;
+ }
- if (gMutexMulticastServer)
+ if(g_mutexSocketListManager)
{
- u_mutex_free(gMutexMulticastServer);
- gMutexMulticastServer = NULL;
+ u_mutex_free(g_mutexSocketListManager);
+ g_mutexSocketListManager = NULL;
}
OIC_LOG(DEBUG, TAG, "OUT");
{
OIC_LOG(DEBUG, TAG, "IN");
- gMutexUnicastServer = u_mutex_new();
- if (!gMutexUnicastServer)
+ g_mutexUnicastServer = u_mutex_new();
+ if (!g_mutexUnicastServer)
{
OIC_LOG(ERROR, TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
-#ifdef __WITH_DTLS__
+ g_mutexMulticastServer = u_mutex_new();
+ if (!g_mutexMulticastServer)
+ {
+ OIC_LOG(ERROR, TAG, "Failed to created mutex!");
-#endif
+ CAEDRDestroyMutex();
+ return CA_STATUS_FAILED;
+ }
- gMutexMulticastServer = u_mutex_new();
- if (!gMutexMulticastServer)
+ g_mutexSocketListManager = u_mutex_new();
+ if (!g_mutexSocketListManager)
{
OIC_LOG(ERROR, TAG, "Failed to created mutex!");
{
OIC_LOG(DEBUG, TAG, "CAEDRInitialize");
- gThreadPoolHandle = handle;
-
- CAEDRCoreJniInit();
-
- CAEDRJniSetContext();
+ g_threadPoolHandle = handle;
// init mutex
CAEDRCreateMutex();
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
jstring jni_address = CAEDRNativeGetLocalDeviceAddress(env);
if(jni_address)
{
const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
- OIC_LOG_V(DEBUG, TAG, "My BT Address is %s ", localAddress);
+ OIC_LOG_V(DEBUG, TAG, "My BT Address is %s", localAddress);
}
CAEDRNativeCreateDeviceStateList();
if(isAttached)
(*g_jvm)->DetachCurrentThread(g_jvm);
- if(gContext)
- {
- //FIXME
- CAEDRCreateJNIInterfaceObject(gContext); /* create java CAEDRInterface instance*/
- }
+ // CAEDRCreateJNIInterfaceObject(gContext); /* create java CAEDRInterface instance*/
OIC_LOG(DEBUG, TAG, "OUT");
}
{
OIC_LOG(DEBUG, TAG, "CAEDRTerminate");
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
- gStopAccept = TRUE;
- gStopMulticast = TRUE;
- gStopUnicast = TRUE;
+ g_stopAccept = true;
+ g_stopMulticast = true;
+ g_stopUnicast = true;
- CAEDRNativeSocketCloseToAll(env);
+ if(isAttached)
+ (*g_jvm)->DetachCurrentThread(g_jvm);
+ if(g_context)
+ {
+ (*env)->DeleteGlobalRef(env, g_context);
+ }
// delete mutex
CAEDRDestroyMutex();
CAEDRNativeRemoveAllDeviceState();
CAEDRNativeRemoveAllDeviceSocket(env);
-
- if(isAttached)
- (*g_jvm)->DetachCurrentThread(g_jvm);
}
-void CAEDRCoreJniInit()
+void CAEDRCoreJniInit(JNIEnv *env, JavaVM *jvm)
{
OIC_LOG_V(DEBUG, TAG, "CAEdrClientJniInit");
- g_jvm = CANativeJNIGetJavaVM();
+ g_jvm = jvm;
+
+ CAEDRServerJniInit(env, jvm);
}
-int32_t CAEDRSendUnicastMessage(const char* address, const char* data, uint32_t dataLen)
+CAResult_t CAEDRSendUnicastMessage(const char* address, const char* data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CAEDRSendUnicastMessage(%s, %s)", address, data);
CAEDRSendUnicastMessageImpl(address, data, dataLen);
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CAEDRSendMulticastMessage(const char* data, uint32_t dataLen)
+CAResult_t CAEDRSendMulticastMessage(const char* data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CAEDRSendMulticastMessage(%s)", data);
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
if(res != JNI_OK)
{
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return 0;
+ return CA_STATUS_INVALID_PARAM;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
CAEDRSendMulticastMessageImpl(env, data, dataLen);
if(isAttached)
{
OIC_LOG_V(DEBUG, TAG, "DetachCurrentThread");
-// (*g_jvm)->DetachCurrentThread(g_jvm);
+ (*g_jvm)->DetachCurrentThread(g_jvm);
}
OIC_LOG_V(DEBUG, TAG, "OUT - CAEDRSendMulticastMessage");
- return 1;
+ return CA_STATUS_OK;
}
CAResult_t CAEDRGetInterfaceInfo(char **address)
return CA_STATUS_OK;
}
-void CAEDRGetLocalAddress(char** address)
+void CAEDRGetLocalAddress(char **address)
{
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
jstring jni_address = CAEDRNativeGetLocalDeviceAddress(env);
*address = (char*)OICMalloc(strlen(localAddress) + 1);
if (*address == NULL)
{
+ if (isAttached)
+ (*g_jvm)->DetachCurrentThread(g_jvm);
return;
}
memcpy(*address, localAddress, strlen(localAddress));
}
OIC_LOG_V(DEBUG, TAG, "Local Address : %s", *address);
- if(isAttached)
+ if (isAttached)
(*g_jvm)->DetachCurrentThread(g_jvm);
}
-int32_t CAEDRSendUnicastMessageImpl(const char* address, const char* data, uint32_t dataLen)
+CAResult_t CAEDRSendUnicastMessageImpl(const char* address, const char* data,
+ uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CAEDRSendUnicastMessageImpl, address: %s, data: %s", address, data);
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
if(res != JNI_OK)
{
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return 0;
+ return CA_STATUS_INVALID_PARAM;
}
isAttached = TRUE;
}
OIC_LOG(DEBUG, TAG, "[EDR][Native] set byteArray for data");
+ if(g_sendBuffer)
+ {
+ (*env)->DeleteGlobalRef(env, g_sendBuffer);
+ }
+ jbyteArray jni_arr = (*env)->NewByteArray(env, dataLen);
+ (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*)data);
+ g_sendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
// get bonded device list
jobjectArray jni_arrayPairedDevices = CAEDRNativeGetBondedDevices(env);
if(!jni_arrayPairedDevices)
{
OIC_LOG_V(DEBUG, TAG, "[EDR][Native] jni_arrayPairedDevices is empty");
- return 0;
+ if (isAttached)
+ (*g_jvm)->DetachCurrentThread(g_jvm);
+ return CA_STATUS_INVALID_PARAM;
}
// Get information from array of devices
jsize length = (*env)->GetArrayLength(env, jni_arrayPairedDevices);
jobject j_obj_device = (*env)->GetObjectArrayElement(env, jni_arrayPairedDevices, i);
jclass jni_cid_BTDevice = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
- jmethodID j_mid_getName = (*env)->GetMethodID(env, jni_cid_BTDevice, "getName", "()Ljava/lang/String;");
- jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice, "getAddress", "()Ljava/lang/String;");
+ jmethodID j_mid_getName = (*env)->GetMethodID(env, jni_cid_BTDevice,
+ "getName", "()Ljava/lang/String;");
+ jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice,
+ "getAddress", "()Ljava/lang/String;");
jstring j_str_name = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getName);
jstring j_str_address = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getAddress);
const char * remoteAddress = (*env)->GetStringUTFChars(env, j_str_address, NULL);
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] getBondedDevices: ~~device address is %s", remoteAddress);
-
+ OIC_LOG_V(DEBUG, TAG,
+ "[EDR][Native] getBondedDevices: ~~device address is %s", remoteAddress);
+
+ if (!remoteAddress) {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+ if (isAttached)
+ (*g_jvm)->DetachCurrentThread(g_jvm);
+ return CA_STATUS_INVALID_PARAM;
+ }
+ if (!address) {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] address is null");
+ if (isAttached)
+ (*g_jvm)->DetachCurrentThread(g_jvm);
+ return CA_STATUS_INVALID_PARAM;
+ }
// find address
if(!strcmp(remoteAddress, address))
{
- CAEDRNativeSendData(env, remoteAddress, data, dataLen, i);
+ CAEDRNativeSendData(env, remoteAddress, data, i);
}
}
- if(isAttached)
+ if (isAttached)
(*g_jvm)->DetachCurrentThread(g_jvm);
- return 1;
+ return CA_STATUS_OK;
}
-int32_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const char* data, uint32_t dataLen)
+CAResult_t CAEDRSendMulticastMessageImpl(JNIEnv *env, const char* data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, send to, data: %s, %d", data, dataLen);
if(!jni_arrayPairedDevices)
{
OIC_LOG_V(DEBUG, TAG, "[EDR][Native] jni_arrayPairedDevices is empty");
- return 0;
+ return CA_STATUS_INVALID_PARAM;
}
// Get information from array of devices
jsize length = (*env)->GetArrayLength(env, jni_arrayPairedDevices);
jobject j_obj_device = (*env)->GetObjectArrayElement(env, jni_arrayPairedDevices, i);
jclass jni_cid_BTDevice = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
- jmethodID j_mid_getName = (*env)->GetMethodID(env, jni_cid_BTDevice, "getName", "()Ljava/lang/String;");
- jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice, "getAddress", "()Ljava/lang/String;");
+ jmethodID j_mid_getName = (*env)->GetMethodID(env, jni_cid_BTDevice,
+ "getName", "()Ljava/lang/String;");
+ jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice,
+ "getAddress", "()Ljava/lang/String;");
jstring j_str_name = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getName);
jstring j_str_address = (*env)->CallObjectMethod(env, j_obj_device, j_mid_getAddress);
const char * remoteAddress = (*env)->GetStringUTFChars(env, j_str_address, NULL);
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] getBondedDevices: ~~device address is %s", remoteAddress);
+ OIC_LOG_V(DEBUG, TAG,
+ "[EDR][Native] getBondedDevices: ~~device address is %s", remoteAddress);
// find address
- CAEDRNativeSendData(env, remoteAddress, data, dataLen, i);
+ CAEDRNativeSendData(env, remoteAddress, data, i);
}
- return 1;
+ return CA_STATUS_OK;
}
/**
* EDR Method
*/
-void CAEDRNativeSendData(JNIEnv *env, const char* address, const char* data, uint32_t dataLength, uint32_t id)
+void CAEDRNativeSendData(JNIEnv *env, const char *address, const char *data, uint32_t id)
{
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btSendData logic start : %s, %d", data, dataLength);
-
- if(!CAEDRNativeIsEnableBTAdapter(env))
- {
- OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
- return;
- }
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData logic start");
if(STATE_DISCONNECTED == CAEDRIsConnectedDevice(address))
{
if(NULL == address)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] remote address is empty");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] remote address is empty");
return;
}
else
jclass jni_cid_BTsocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
if(!jni_cid_BTsocket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: jni_cid_BTsocket is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_cid_BTsocket is null");
return;
}
- jmethodID jni_mid_getOutputStream = (*env)->GetMethodID(env, jni_cid_BTsocket, "getOutputStream", "()Ljava/io/OutputStream;");
+ jmethodID jni_mid_getOutputStream = (*env)->GetMethodID(env,
+ jni_cid_BTsocket, "getOutputStream",
+ "()Ljava/io/OutputStream;");
if(!jni_mid_getOutputStream)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: jni_mid_getOutputStream is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_mid_getOutputStream is null");
return;
}
OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btSendData: Get MethodID for i/o stream..%d", id);
jobject jni_obj_socket = CAEDRNativeGetDeviceSocket(id);
if(!jni_obj_socket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: jni_socket is not available");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_socket is not available");
return;
}
- jobject jni_obj_outputStream = (*env)->CallObjectMethod(env, jni_obj_socket, jni_mid_getOutputStream);
+ jobject jni_obj_outputStream = (*env)->CallObjectMethod(env,
+ jni_obj_socket, jni_mid_getOutputStream);
if(!jni_obj_outputStream)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: jni_obj_outputStream is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_obj_outputStream is null");
return;
}
jclass jni_cid_OutputStream = (*env)->FindClass(env, "java/io/OutputStream");
if(!jni_cid_OutputStream)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: jni_cid_OutputStream is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_cid_OutputStream is null");
return;
}
- jmethodID jni_mid_write = (*env)->GetMethodID(env, jni_cid_OutputStream, "write", "([BII)V");
+ jmethodID jni_mid_write = (*env)->GetMethodID(env,
+ jni_cid_OutputStream, "write", "([BII)V");
if(!jni_mid_write)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: jni_mid_write is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: jni_mid_write is null");
return;
}
jbyteArray jbuf;
- jbuf = (*env)->NewByteArray(env, dataLength);
- (*env)->SetByteArrayRegion(env, jbuf, 0, dataLength, (jbyte*)data);
+ int length = strlen(data);
+ jbuf = (*env)->NewByteArray(env, length);
+ (*env)->SetByteArrayRegion(env, jbuf, 0, length, (jbyte*)data);
- (*env)->CallVoidMethod(env, jni_obj_outputStream, jni_mid_write, jbuf, (jint)0, (jint)dataLength);
+ (*env)->CallVoidMethod(env, jni_obj_outputStream, jni_mid_write,
+ jbuf, (jint) 0, (jint) length);
if((*env)->ExceptionCheck(env))
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: Write Error!!!");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btSendData: Write Error!!!");
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
return;
}
OIC_LOG(DEBUG, TAG, "[EDR][Native] btSendData: Write Success");
+
+ // remove socket to list
+ CAEDRNativeRemoveDeviceSocket(env, jni_obj_socket);
+
+ // update state
+ CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
}
else
{
}
}
-void CAEDRNativeConnect(JNIEnv *env, const char* address, uint32_t id)
+void CAEDRNativeConnect(JNIEnv *env, const char *address, uint32_t id)
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect..");
- if(!CAEDRNativeIsEnableBTAdapter(env))
- {
- OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
- return;
- }
-
jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
if(!jni_cid_BTAdapter)
{
}
// get BTadpater
- jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env,
+ jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
if(!jni_mid_getDefaultAdapter)
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: jni_mid_getDefaultAdapter is null");
return;
}
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env,
+ jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
if(!jni_obj_BTAdapter)
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: jni_obj_BTAdapter is null");
}
// get remote bluetooth device
- jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env, jni_cid_BTAdapter, "getRemoteDevice",
- "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;");
+ jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env,
+ jni_cid_BTAdapter, "getRemoteDevice",
+ "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;");
if(!jni_mid_getRemoteDevice)
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: jni_mid_getRemoteDevice is null");
//jstring jni_address = (*env)->NewStringUTF(env, "B8:5E:7B:54:52:1C");
jstring jni_address = (*env)->NewStringUTF(env, address);
- jobject jni_obj_remoteBTDevice = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_getRemoteDevice, jni_address);
+ jobject jni_obj_remoteBTDevice = (*env)->CallObjectMethod(env,
+ jni_obj_BTAdapter, jni_mid_getRemoteDevice, jni_address);
if(!jni_obj_remoteBTDevice)
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: jni_obj_remoteBTDevice is null");
return;
}
- jmethodID jni_mid_createSocket = (*env)->GetMethodID(env, jni_cid_BluetoothDevice,
- "createInsecureRfcommSocketToServiceRecord","(Ljava/util/UUID;)Landroid/bluetooth/BluetoothSocket;");
+ jmethodID jni_mid_createSocket = (*env)->GetMethodID(env,
+ jni_cid_BluetoothDevice,
+ "createInsecureRfcommSocketToServiceRecord",
+ "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothSocket;");
if(!jni_mid_createSocket) {
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: jni_mid_createSocket is null");
return;
return;
}
- jstring jni_uuid = (*env)->NewStringUTF(env, "00000000-0000-0000-0000-0000cdab0000");
- jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid, jni_mid_fromString, jni_uuid);
+ jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid,
+ jni_mid_fromString, OIC_EDR_SERVICE_ID);
if(!jni_obj_uuid)
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: jni_obj_uuid is null");
return;
}
// create socket
- jobject jni_obj_BTSocket = (*env)->CallObjectMethod(env, jni_obj_remoteBTDevice, jni_mid_createSocket, jni_obj_uuid);
+ jobject jni_obj_BTSocket = (*env)->CallObjectMethod(env,
+ jni_obj_remoteBTDevice, jni_mid_createSocket, jni_obj_uuid);
if(!jni_obj_BTSocket)
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: jni_obj_BTSocket is null");
OIC_LOG(DEBUG, TAG, "[EDR][Native] btConnect: connected");
}
-void CAEDRNativeSocketClose(JNIEnv *env, const char* address, uint32_t id)
+void CAEDRNativeSocketClose(JNIEnv *env, const char *address, uint32_t id)
{
jclass jni_cid_BTSocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
if(!jni_cid_BTSocket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
return;
}
jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_BTSocket, "close", "()V");
if(!jni_mid_close)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: jni_mid_close is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_mid_close is null");
return;
}
jobject jni_obj_socket = CAEDRNativeGetDeviceSocket(id);
if(!jni_obj_socket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: jni_obj_socket is not available");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_obj_socket is not available");
return;
}
OIC_LOG(DEBUG, TAG, "[EDR][Native] close: disconnected");
}
+
+/**
+ * BT State List
+ */
+void CAEDRNativeCreateDeviceStateList()
+{
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeCreateDeviceStateList");
+
+ // create new object array
+ if (g_deviceStateList == NULL)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Create device list");
+
+ g_deviceStateList = u_arraylist_create();
+ }
+}
+
+void CAEDRUpdateDeviceState(CAConnectedState_t state, const char *address)
+{
+ state_t *newstate = (state_t*) OICCalloc(1, sizeof(state_t));
+ if (!newstate) {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] newstate is null");
+ return;
+ }
+ strcpy(newstate->address, address);
+ newstate->state = state;
+
+ CAEDRNativeAddDeviceStateToList(newstate);
+}
+
+void CAEDRNativeAddDeviceStateToList(state_t *state)
+{
+ if(!state)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] device is null");
+ return;
+ }
+
+ if(!g_deviceStateList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdevice_list is null");
+ return;
+ }
+
+ if(CAEDRNativeIsDeviceInList(state->address)) {
+ CAEDRNativeRemoveDevice(state->address); // delete previous state for update new state
+ }
+ u_arraylist_add(g_deviceStateList, state); // update new state
+ OIC_LOG_V(DEBUG, TAG, "Set State Info to List : %d", state->state);
+}
+
+jboolean CAEDRNativeIsDeviceInList(const char* remoteAddress){
+
+ jint index;
+ if (!remoteAddress) {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+ return JNI_TRUE;
+ }
+ for (index = 0; index < u_arraylist_length(g_deviceStateList); index++)
+ {
+ state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+ if(!state)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] state_t object is null");
+ return JNI_TRUE;
+ }
+
+ if(!strcmp(remoteAddress, state->address))
+ {
+ OIC_LOG_V(DEBUG, TAG, "the device is already set");
+ return JNI_TRUE;
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "there are no the device in list.");
+ return JNI_FALSE;
+}
+
+void CAEDRNativeRemoveAllDeviceState()
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveAllDevices");
+
+ if(!g_deviceStateList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+ return;
+ }
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceStateList); index++)
+ {
+ state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+ if(!state)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+ continue;
+ }
+ OICFree(state);
+ }
+
+ OICFree(g_deviceStateList);
+ g_deviceStateList = NULL;
+ return;
+}
+
+void CAEDRNativeRemoveDevice(const char *remoteAddress)
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveDeviceforStateList");
+
+ if(!g_deviceStateList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+ return;
+ }
+ if (!remoteAddress) {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+ return;
+ }
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceStateList); index++)
+ {
+ state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+ if(!state)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
+ continue;
+ }
+
+ if(!strcmp(state->address, remoteAddress))
+ {
+ OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove state : %s", remoteAddress);
+ OICFree(state);
+
+ CAEDRReorderingDeviceList(index);
+ break;
+ }
+ }
+ return;
+}
+
+CAConnectedState_t CAEDRIsConnectedDevice(const char *remoteAddress)
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRIsConnectedDevice");
+
+ if(!g_deviceStateList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+ return STATE_DISCONNECTED;
+ }
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceStateList); index++)
+ {
+ state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+ if(!state)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
+ continue;
+ }
+
+ if(!strcmp(state->address, remoteAddress))
+ {
+ OIC_LOG_V(DEBUG, TAG, "[EDR][Native] check whether it is connected or not");
+
+ return state->state;
+ }
+ }
+ return STATE_DISCONNECTED;
+}
+
+void CAEDRReorderingDeviceList(uint32_t index)
+{
+ if (index >= g_deviceStateList->length)
+ {
+ return;
+ }
+
+ if (index < g_deviceStateList->length - 1)
+ {
+ memmove(&g_deviceStateList->data[index], &g_deviceStateList->data[index + 1],
+ (g_deviceStateList->length - index - 1) * sizeof(void *));
+ }
+
+ g_deviceStateList->size--;
+ g_deviceStateList->length--;
+}
+
+/**
+ * Device Socket Object List
+ */
+void CAEDRNativeCreateDeviceSocketList()
+{
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeCreateDeviceSocketList");
+
+ // create new object array
+ if (g_deviceObjectList == NULL)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Create Device object list");
+
+ g_deviceObjectList = u_arraylist_create();
+ }
+}
+
+void CAEDRNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket)
+{
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] CANativeAddDeviceobjToList");
+
+ if(!deviceSocket)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] Device is null");
+ return;
+ }
+
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+ return;
+ }
+
+ jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
+ if(!jni_remoteAddress)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_remoteAddress is null");
+ return;
+ }
+
+ u_mutex_lock(g_mutexSocketListManager);
+
+ const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+
+ if(!CAEDRNativeIsDeviceSocketInList(env, remoteAddress))
+ {
+ jobject gDeviceSocker = (*env)->NewGlobalRef(env, deviceSocket);
+ u_arraylist_add(g_deviceObjectList, gDeviceSocker);
+ OIC_LOG_V(DEBUG, TAG, "Set Socket Object to Array");
+ }
+
+ u_mutex_unlock(g_mutexSocketListManager);
+}
+
+jboolean CAEDRNativeIsDeviceSocketInList(JNIEnv *env, const char* remoteAddress)
+{
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] CANativeIsDeviceObjInList");
+
+ jint index;
+
+ if (!remoteAddress) {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] remoteAddress is null");
+ return JNI_TRUE;
+ }
+ for (index = 0; index < u_arraylist_length(g_deviceObjectList); index++)
+ {
+
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+ if(!jarrayObj)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+ return JNI_TRUE;
+ }
+
+ jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
+ if(!jni_setAddress)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_setAddress is null");
+ return JNI_TRUE;
+ }
+
+ const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+ if(!setAddress)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] setAddress is null");
+ return JNI_TRUE;
+ }
+
+ if(!strcmp(remoteAddress, setAddress))
+ {
+ OIC_LOG_V(DEBUG, TAG, "the device is already set");
+ return JNI_TRUE;
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "there are no the Device obejct in list. we can add");
+ return JNI_FALSE;
+}
+
+void CAEDRNativeRemoveAllDeviceSocket(JNIEnv *env)
+{
+ OIC_LOG_V(DEBUG, TAG, "CANativeRemoveAllDeviceObjsList");
+
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+ return;
+ }
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceObjectList); index++)
+ {
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+ if(!jarrayObj)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+ return;
+ }
+ (*env)->DeleteGlobalRef(env, jarrayObj);
+ }
+
+ OICFree(g_deviceObjectList);
+ g_deviceObjectList = NULL;
+ return;
+}
+
+void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket)
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveDeviceSocket");
+
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+ return;
+ }
+
+ u_mutex_lock(g_mutexSocketListManager);
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceObjectList); index++)
+ {
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+ if(!jarrayObj)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+ continue;
+ }
+
+ jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
+ if(!jni_setAddress)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_setAddress is null");
+ continue;
+ }
+ const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+
+ jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
+ if(!jni_remoteAddress)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_remoteAddress is null");
+ continue;
+ }
+ const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+
+ if(!strcmp(setAddress, remoteAddress))
+ {
+ OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove object : %s", remoteAddress);
+ (*env)->DeleteGlobalRef(env, jarrayObj);
+
+ CAEDRReorderingDeviceSocketList(index);
+ break;
+ }
+ }
+ u_mutex_unlock(g_mutexSocketListManager);
+
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] there are no target object");
+ return;
+}
+
+jobject CAEDRNativeGetDeviceSocket(uint32_t idx)
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRNativeGetDeviceSocket");
+
+ if(idx < 0)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] index is not available");
+ return NULL;
+ }
+
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+ return NULL;
+ }
+
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, idx);
+ if(!jarrayObj)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jarrayObj is not available");
+ return NULL;
+ }
+ return jarrayObj;
+}
+
+uint32_t CAEDRGetSocketListLength()
+{
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceObjectList is null");
+ return 0;
+ }
+
+ uint32_t length = u_arraylist_length(g_deviceObjectList);
+
+ return length;
+}
+
+void CAEDRReorderingDeviceSocketList(uint32_t index)
+{
+ if (index >= g_deviceObjectList->length)
+ {
+ return;
+ }
+
+ if (index < g_deviceObjectList->length - 1)
+ {
+ memmove(&g_deviceObjectList->data[index], &g_deviceObjectList->data[index + 1],
+ (g_deviceObjectList->length - index - 1) * sizeof(void *));
+ }
+
+ g_deviceObjectList->size--;
+ g_deviceObjectList->length--;
+}
+
void CAEDRInitializeClient(u_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "IN");
CAEDRInitialize(handle);
OIC_LOG(DEBUG, TAG, "OUT");
}
+
+
#include <jni.h>
#include "caedrinterface.h"
-#include "caedrnwmonitor.h"
#include "logger.h"
#include "oic_malloc.h"
#include "uthreadpool.h" /* for thread pool */
#include "uarraylist.h"
#include "caadapterutils.h"
-#include "com_iotivity_jar_CAEDRInterface.h"
-
//#define DEBUG_MODE
#define TAG PCF("CA_EDR_MONITOR")
-#define BT_STATE_ON 12
-#define BT_STATE_OFF 10
-
// temp method
-static JavaVM *g_jvm;
-static jobject gContext;
-static CAEDRNetworkStatusCallback gNetworkChangeCb = NULL;
-
-void CAEDRNetworkMonitorJNISetContext()
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRNetworkMonitorJNISetContext");
- gContext = CANativeJNIGetContext();
-}
-
-//getting jvm
-void CAEDRNetworkMonitorJniInit()
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRNetworkMonitorJniInit");
- g_jvm = CANativeJNIGetJavaVM();
-}
CAResult_t CAEDRInitializeNetworkMonitor()
{
OIC_LOG_V(DEBUG, TAG, "IN");
- CAEDRNetworkMonitorJniInit();
- CANativeJNIGetJavaVM();
-
OIC_LOG_V(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
void CAEDRSetNetworkChangeCallback(
CAEDRNetworkStatusCallback networkChangeCallback)
{
- OIC_LOG_V(DEBUG, TAG, "CAEDRSetNetworkChangeCallback");
- gNetworkChangeCb = networkChangeCallback;
+ OIC_LOG_V(DEBUG, TAG, "IN");
+
+ OIC_LOG_V(DEBUG, TAG, "OUT");
}
void CAEDRTerminateNetworkMonitor(void)
return CA_STATUS_OK;
}
-JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CAEDRInterface_CAEDRStateChangedCallback
-(JNIEnv *env, jobject obj, jint status)
-{
- // STATE_ON:12, STATE_OFF:10
- OIC_LOG_V(DEBUG, TAG, "CAEDRInterface - Network State Changed");
-
- if(gNetworkChangeCb == NULL)
- OIC_LOG_V(DEBUG, TAG, "gNetworkChangeCb is null", status);
-
- if(BT_STATE_ON == status)
- {
- CANetworkStatus_t newStatus = CA_INTERFACE_UP;
- CAEDRServerStartAccpetThread();
- gNetworkChangeCb(newStatus);
- }
- else if(BT_STATE_OFF == status)
- {
- CANetworkStatus_t newStatus = CA_INTERFACE_DOWN;
- CAEDRNativeRemoveAllDeviceSocket(env);
- CAEDRNativeRemoveAllDeviceState(env);
- gNetworkChangeCb(newStatus);
- }
-}
-
-JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CAEDRInterface_CAEDRBondStateChangedCallback
-(JNIEnv *env, jobject obj, jstring addr)
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRInterface - Bond State Changed");
-
- if(addr)
- {
- CAEDRNativeRemoveDeviceSocketBaseAddr(env, addr);
- CAEDRNativeRemoveDevice(env, addr);
- }
-}
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
#include <stdio.h>
#include <string.h>
#include <jni.h>
#include "umutex.h"
#include "uarraylist.h"
#include "caadapterutils.h"
-#include "com_iotivity_jar_CAEDRInterface.h"
//#define DEBUG_MODE
#define TAG PCF("CA_EDR_SERVER")
-static const char *METHODID_OBJECTNONPARAM = "()Landroid/bluetooth/BluetoothAdapter;";
-static const char *CLASSPATH_BT_ADPATER = "android/bluetooth/BluetoothAdapter";
-static const char *CLASSPATH_BT_UUID = "java/util/UUID";
-
-static const uint32_t STATE_CONNECTED = 1;
-static const uint32_t STATE_DISCONNECTED = 0;
+static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
+static const char METHODID_STRINGNONPARAM[] = "()Ljava/lang/String;";
+static const char CLASSPATH_BT_ADPATER[] = "android/bluetooth/BluetoothAdapter";
+static const char CLASSPATH_BT_UUID[] = "java/util/UUID";
static const uint32_t MAX_PDU_BUFFER = 1024;
-static const uint32_t MAX_CONNECTED_BT_SUPPORT_CNT = 7;
-static u_thread_pool_t gThreadPoolHandle = NULL;
+static u_arraylist_t *g_deviceStateList = NULL;
+static u_arraylist_t *g_deviceObjectList = NULL;
+
+static u_thread_pool_t g_threadPoolHandle = NULL;
static JavaVM *g_jvm;
-static jobject gContext;
+
+static jbyteArray g_sendBuffer;
/**
- * @var gMutexSocketListManager
+ * @var g_mMutexSocketListManager
* @brief Mutex to synchronize socket list update
*/
-static u_mutex gMutexSocketListManager;
+static u_mutex g_mutexSocketListManager;
// server socket instance
-static jobject gServerSocketObject = NULL;
+static jobject g_serverSocketObject = NULL;
/**
- * @var gMutexUnicastServer
+ * @var g_mutexUnicastServer
* @brief Mutex to synchronize unicast server
*/
-static u_mutex gMutexUnicastServer = NULL;
+static u_mutex g_mutexUnicastServer = NULL;
/**
- * @var gStopUnicast
+ * @var g_stopUnicast
* @brief Flag to control the Receive Unicast Data Thread
*/
-static bool gStopUnicast = FALSE;
+static bool g_stopUnicast = false;
/**
- * @var gMutexMulticastServer
+ * @var g_mutexMulticastServer
* @brief Mutex to synchronize secure multicast server
*/
-static u_mutex gMutexMulticastServer = NULL;
-
-/**
- * @var gMutexMulticastServer
- * @brief Mutex to synchronize multicast receiver
- */
-static u_mutex gMutexReceiver = NULL;
+static u_mutex g_mutexMulticastServer = NULL;
/**
- * @var gStopMulticast
+ * @var g_stopMulticast
* @brief Flag to control the Receive Multicast Data Thread
*/
-static bool gStopMulticast = FALSE;
+static bool g_stopMulticast = false;
/**
- * @var gStopAccept
+ * @var g_stopAccept
* @brief Flag to control the Accept Thread
*/
-static bool gStopAccept = FALSE;
-
-
-static jobject gInputStream = NULL;
-
-static jobject gSeverSocket = NULL;
+static bool g_stopAccept = false;
typedef struct send_data {
char* address;
bool *stopFlag;
} CAAdapterAcceptThreadContext_t;
+// callback instance
+
/**
- * @var gEDRNetworkChangeCallback
+ * @var g_EDRPacketReceivedCallback
* @brief Maintains the callback to be notified when data received from remote Bluetooth device
*/
-static CAEDRDataReceivedCallback gEDRPacketReceivedCallback = NULL;
+static CAEDRDataReceivedCallback g_EDRPacketReceivedCallback = NULL;
static void CAReceiveHandler(void *data)
{
- OIC_LOG(DEBUG, TAG, "IN - CAReceiveHandler..");
+ OIC_LOG_V(DEBUG, TAG, "start CAReceiveHandler..");
+ OIC_LOG(DEBUG, TAG, "IN");
// Input validation
VERIFY_NON_NULL_VOID(data, TAG, "Invalid thread context");
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *)data;
- while (TRUE != *(ctx->stopFlag))
+ while (true != *(ctx->stopFlag))
{
uint32_t idx;
// if new socket object is added in socket list after below logic is ran.
// new socket will be started to read after next while loop
- uint32_t length = CAEDRGetSocketListLength();
- if(0 == length)
+ uint32_t length = CAEDRServerGetSocketListLength();
+ if (0 == length)
{
OIC_LOG_V(DEBUG, TAG, "socket list is empty");
- sleep(1);
}
- for(idx = 0 ; idx < length ; idx++)
+ for (idx = 0; idx < length; idx++)
{
OIC_LOG_V(DEBUG, TAG, "start CAEDRNativeReadData");
CAEDRNativeReadData(env, idx, ctx->type);
- sleep(1);
}
+
}
if(isAttached)
if(ctx)
OICFree(ctx);
- OIC_LOG(DEBUG, TAG, "OUT - CAReceiveHandler");
+ OIC_LOG(DEBUG, TAG, "OUT");
}
static void CAAcceptHandler(void *data)
{
- int status;
-
+ if (!data)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR] CAAcceptHandler: data is null");
+ return;
+ }
OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread start");
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
jobject jni_obj_BTSeverSocket = CAEDRNativeListen(env);
- if(!jni_obj_BTSeverSocket) {
- OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread: jni_obj_BTSeverSocket is null");
+ if (!jni_obj_BTSeverSocket)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR] AcceptThread: jni_obj_BTSeverSocket is null");
if(isAttached)
(*g_jvm)->DetachCurrentThread(g_jvm);
return;
}
- gSeverSocket = (*env)->NewGlobalRef(env, jni_obj_BTSeverSocket);
-
CAAdapterAcceptThreadContext_t *ctx = (CAAdapterAcceptThreadContext_t *)data;
- if(NULL == ctx)
- {
- OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread: ctx is null");
- return;
- }
-
- // it should be initialized for restart accept thread
- gStopAccept = FALSE;
-
- while (TRUE != *(ctx->stopFlag))
+ while (true != *(ctx->stopFlag))
{
OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread running");
-
- // when BT state is changed with Off. its thread will be stopped
- if(!CAEDRNativeIsEnableBTAdapter(env))
- {
- OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
- gStopAccept = TRUE;
- gSeverSocket = NULL;
- }
- else
- {
- CAEDRNativeAccept(env, gSeverSocket);
- }
+ CAEDRNativeAccept(env, jni_obj_BTSeverSocket);
}
if(isAttached)
return;
}
-/**
- * implement for adapter common method
- */
+
+// adapter common method
+
CAResult_t CAEDRServerStart(const char *serviceUUID, int32_t *serverFD, u_thread_pool_t handle)
{
OIC_LOG_V(DEBUG, TAG, "IN");
CAEDRServerInitialize(handle);
// FIXME
- CAEDRStartUnicastServer(NULL, FALSE);
-
- *serverFD = 1;
+ CAEDRStartUnicastServer(NULL, false);
OIC_LOG_V(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
-CAResult_t CAEDRServerStop(const int32_t serverFD)
+CAResult_t CAEDRServerStop(int serverFD)
{
OIC_LOG_V(DEBUG, TAG, "IN");
CAEDRStopUnicastServer(-1);
CAEDRStopMulticastServer(-1);
- CAEDRServerTerminate();
+
+ g_stopAccept = TRUE;
+ g_stopMulticast = TRUE;
+ g_stopUnicast = TRUE;
+
OIC_LOG_V(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
void CAEDRSetPacketReceivedCallback(CAEDRDataReceivedCallback packetReceivedCallback)
{
- gEDRPacketReceivedCallback = packetReceivedCallback;
+ g_EDRPacketReceivedCallback = packetReceivedCallback;
}
/**
{
OIC_LOG(DEBUG, TAG, "IN");
- if (gMutexUnicastServer)
+ if (g_mutexUnicastServer)
{
- u_mutex_free(gMutexUnicastServer);
- gMutexUnicastServer = NULL;
+ u_mutex_free(g_mutexUnicastServer);
+ g_mutexUnicastServer = NULL;
}
-#ifdef __WITH_DTLS__
-
-#endif
-
- if (gMutexMulticastServer)
+ if (g_mutexMulticastServer)
{
- u_mutex_free(gMutexMulticastServer);
- gMutexMulticastServer = NULL;
+ u_mutex_free(g_mutexMulticastServer);
+ g_mutexMulticastServer = NULL;
}
- if(gMutexSocketListManager)
+ if(g_mutexSocketListManager)
{
- u_mutex_free(gMutexSocketListManager);
- gMutexSocketListManager = NULL;
+ u_mutex_free(g_mutexSocketListManager);
+ g_mutexSocketListManager = NULL;
}
OIC_LOG(DEBUG, TAG, "OUT");
{
OIC_LOG(DEBUG, TAG, "IN");
- gMutexUnicastServer = u_mutex_new();
- if (!gMutexUnicastServer)
+ g_mutexUnicastServer = u_mutex_new();
+ if (!g_mutexUnicastServer)
{
OIC_LOG(ERROR, TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
-#ifdef __WITH_DTLS__
-
-#endif
-
- gMutexMulticastServer = u_mutex_new();
- if (!gMutexMulticastServer)
+ g_mutexMulticastServer = u_mutex_new();
+ if (!g_mutexMulticastServer)
{
OIC_LOG(ERROR, TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
- gMutexSocketListManager = u_mutex_new();
- if (!gMutexSocketListManager)
+ g_mutexSocketListManager = u_mutex_new();
+ if (!g_mutexSocketListManager)
{
OIC_LOG(ERROR, TAG, "Failed to created mutex!");
return CA_STATUS_OK;
}
-void CAEDRServerJniInit()
+void CAEDRServerJniInit(JNIEnv *env, JavaVM* jvm)
{
OIC_LOG_V(DEBUG, TAG, "CAEDRServerJniInit");
- g_jvm = CANativeJNIGetJavaVM();
+ g_jvm = jvm;
}
void CAEDRServerInitialize(u_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "CAEDRServerInitialize");
- gThreadPoolHandle = handle;
-
- CAEDRServerStartAccpetThread();
-
- OIC_LOG(DEBUG, TAG, "OUT");
-}
-
-void CAEDRServerStartAccpetThread()
-{
- CAEDRServerJniInit();
+ g_threadPoolHandle = handle;
// init mutex
CAEDRServerCreateMutex();
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
jstring jni_address = CAEDRNativeGetLocalDeviceAddress(env);
- if(jni_address)
+ if (jni_address)
{
const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
OIC_LOG_V(DEBUG, TAG, "My BT Address is %s", localAddress);
+ (*env)->ReleaseStringUTFChars(env, jni_address, localAddress);
}
- CAEDRNativeCreateDeviceStateList();
- CAEDRNativeCreateDeviceSocketList();
+ CAEDRServerNativeCreateDeviceStateList();
+ CAEDRServerNativeCreateDeviceSocketList();
if(isAttached)
(*g_jvm)->DetachCurrentThread(g_jvm);
return;
}
- ctx->stopFlag = &gStopAccept;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPoolHandle, CAAcceptHandler, (void *)ctx))
+ ctx->stopFlag = &g_stopAccept;
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPoolHandle, CAAcceptHandler, (void *)ctx))
{
OIC_LOG(ERROR, TAG, "Failed to create read thread!");
OICFree((void *)ctx);
return;
}
+
+ OIC_LOG(DEBUG, TAG, "OUT");
}
void CAEDRServerTerminate()
{
OIC_LOG(DEBUG, TAG, "CAEDRServerTerminate");
- jboolean isAttached = FALSE;
+ if (!g_jvm)
+ {
+ return;
+ }
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
if(res != JNI_OK)
OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
- gStopAccept = TRUE;
- gStopMulticast = TRUE;
- gStopUnicast = TRUE;
-
- CAEDRNatvieCloseServerTask(env);
+ if (isAttached)
+ {
+ (*g_jvm)->DetachCurrentThread(g_jvm);
+ }
- CAEDRNativeSocketCloseToAll(env);
+ CAEDRServerNativeRemoveAllDeviceState();
+ CAEDRServerNativeRemoveAllDeviceSocket(env);
// delete mutex
CAEDRServerDestroyMutex();
-
- CAEDRNativeRemoveAllDeviceState();
- CAEDRNativeRemoveAllDeviceSocket(env);
-
- if(isAttached)
- (*g_jvm)->DetachCurrentThread(g_jvm);
}
int32_t CAEDRStartUnicastServer(const char* address, bool isSecured)
{
OIC_LOG_V(DEBUG, TAG, "CAEDRStartUnicastServer(%s)", address);
- u_mutex_lock(gMutexUnicastServer);
+ u_mutex_lock(g_mutexUnicastServer);
/**
* The task to listen for data from unicast is added to the thread pool.
if (!ctx)
{
OIC_LOG(ERROR, TAG, "Out of memory!");
- u_mutex_unlock(gMutexUnicastServer);
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopUnicast;
+ ctx->stopFlag = &g_stopUnicast;
ctx->type = isSecured ? CA_SECURED_UNICAST_SERVER : CA_UNICAST_SERVER;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPoolHandle, CAReceiveHandler, (void *)ctx))
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPoolHandle, CAReceiveHandler, (void *)ctx))
{
OIC_LOG(ERROR, TAG, "Failed to create read thread!");
- u_mutex_unlock(gMutexUnicastServer);
+ u_mutex_unlock(g_mutexUnicastServer);
OICFree((void *)ctx);
return CA_STATUS_FAILED;
}
- u_mutex_unlock(gMutexUnicastServer);
+ u_mutex_unlock(g_mutexUnicastServer);
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, TAG, "CAEDRStartMulticastServer");
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
/**
* The task to listen to data from multicast socket is added to the thread pool.
if (!ctx)
{
OIC_LOG(ERROR, TAG, "Out of memory!");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopMulticast;
+ ctx->stopFlag = &g_stopMulticast;
ctx->type = CA_MULTICAST_SERVER;
- gStopMulticast = FALSE;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPoolHandle, CAReceiveHandler, (void *)ctx))
+ g_stopMulticast = false;
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPoolHandle, CAReceiveHandler, (void *)ctx))
{
OIC_LOG(ERROR, TAG, "thread_pool_add_task failed!");
- gStopMulticast = TRUE;
- u_mutex_unlock(gMutexMulticastServer);
+ g_stopMulticast = true;
+ u_mutex_unlock(g_mutexMulticastServer);
+ OICFree((void *)ctx);
return CA_STATUS_FAILED;
}
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, TAG, "CAEDRStopUnicastServer");
- u_mutex_lock(gMutexUnicastServer);
- gStopUnicast = TRUE;
- u_mutex_unlock(gMutexUnicastServer);
+ u_mutex_lock(g_mutexUnicastServer);
+ g_stopUnicast = true;
+ u_mutex_unlock(g_mutexUnicastServer);
return 0;
}
{
OIC_LOG(DEBUG, TAG, "CAEDRStopMulticastServer");
- u_mutex_lock(gMutexMulticastServer);
- gStopMulticast = true;
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
+ g_stopMulticast = true;
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG_V(INFO, TAG, "Multicast server stopped");
return 0;
}
-uint32_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t type)
+CAResult_t CAEDRNativeReadData(JNIEnv *env, uint32_t id, CAAdapterServerType_t type)
{
- if(!CAEDRNativeIsEnableBTAdapter(env))
- {
- OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
- return 0;
- }
-
if(!((*env)->ExceptionCheck(env)))
{
// check whether this socket object is connected or not.
- jobject jni_obj_socket = CAEDRNativeGetDeviceSocket(id);
+ jobject jni_obj_socket = CAEDRServerNativeGetDeviceSocket(id);
if(!jni_obj_socket)
{
- return 0;
+ return CA_STATUS_INVALID_PARAM;
}
jstring jni_str_address = CAEDRNativeGetAddressFromDeviceSocket(env, jni_obj_socket);
const char* address = (*env)->GetStringUTFChars(env, jni_str_address, NULL);
-
- // check it whether is still connected or not through google api
- jboolean ret = CAEDRIsConnectedForSocket(env, jni_obj_socket);
- if(!ret)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] this device is not connected now...let close socket");
- }
-
- // check it whether is still connected or not through socket state list
- if(STATE_DISCONNECTED == CAEDRIsConnectedDevice(address))
+ if(STATE_DISCONNECTED == CAEDRServerIsConnectedDevice(address))
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData: it is not connected yet..");
-
- // remove socket to list
- // this code is related to below read fail exception code
- CAEDRNativeRemoveDeviceSocket(env, jni_obj_socket);
-
- return 0;
+ return CA_STATUS_FAILED;
}
// start to read through InputStream
jclass jni_cid_BTsocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
- jmethodID jni_mid_getInputStream = (*env)->GetMethodID(env, jni_cid_BTsocket, "getInputStream", "()Ljava/io/InputStream;");
+ jmethodID jni_mid_getInputStream = (*env)->GetMethodID(env,
+ jni_cid_BTsocket, "getInputStream", "()Ljava/io/InputStream;");
OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: get InputStream..%d, %s", id, address);
if(!jni_obj_socket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_obj_socket is not available anymore..");
- return 0;
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_obj_socket is not available anymore..");
+ return CA_STATUS_FAILED;
}
- jobject jni_obj_inputStream = (*env)->CallObjectMethod(env, jni_obj_socket, jni_mid_getInputStream);
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData: ready inputStream...");
-
- gInputStream = (*env)->NewGlobalRef(env, jni_obj_inputStream);
+ jobject jni_obj_inputStream = (*env)->CallObjectMethod(env,
+ jni_obj_socket, jni_mid_getInputStream);
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData: ready inputStream..");
jclass jni_cid_InputStream = (*env)->FindClass(env, "java/io/InputStream");
jmethodID jni_mid_read = (*env)->GetMethodID(env, jni_cid_InputStream, "read", "([BII)I");
if(!jni_obj_socket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_obj_socket is not available anymore...");
- return 0;
- }
-
- nread = (*env)->CallIntMethod(env, gInputStream, jni_mid_read, jbuf, (jint)0, MAX_PDU_BUFFER);
-
- OIC_LOG(DEBUG, TAG, "[EDR][Native] read something from InputStream");
-
- if(-1 == nread)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] read buffer is empty...");
- return 0;
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_obj_socket is not available anymore...");
+ return CA_STATUS_FAILED;
}
- if((*env)->ExceptionCheck(env))
+ while ((nread = (*env)->CallIntMethod(env, jni_obj_inputStream,
+ jni_mid_read, jbuf, (jint)0, MAX_PDU_BUFFER)) != -1)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData: read Error!!!");
- (*env)->ExceptionDescribe(env);
- (*env)->ExceptionClear(env);
-
- // update state to disconnect
- // the socket will be close next read thread routine
- CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
- return 0;
- }
-
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: reading");
- jbyte* buf = (*env)->GetByteArrayElements(env, jbuf, NULL);
- if (buf == NULL)
- {
- return 0;
- }
-
- jint length = strlen((char*)buf);
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: read %s, %d", buf, length);
+ if((*env)->ExceptionCheck(env))
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btReadData: read Error!!!");
+ (*env)->ExceptionDescribe(env);
+ (*env)->ExceptionClear(env);
+ return CA_STATUS_FAILED;
+ }
+ OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: reading");
+ jbyte* buf = (*env)->GetByteArrayElements(env, jbuf, NULL);
+ jint length = strlen((char*)buf);
+ OIC_LOG_V(DEBUG, TAG, "[EDR][Native] btReadData: read %s", buf);
+ if (buf == NULL)
+ {
+ return CA_STATUS_FAILED;
+ }
- char responseData[MAX_PDU_BUFFER];
- memset(responseData, 0, MAX_PDU_BUFFER);
- strncpy(responseData, (char*)buf, length);
- responseData[length] = '\0';
+ switch (type)
+ {
+ case CA_UNICAST_SERVER:
+ case CA_MULTICAST_SERVER:
+ // Notify data to upper layer
+ if (g_EDRPacketReceivedCallback)
+ {
+ uint32_t sentLength = 0;
+ OIC_LOG_V(DEBUG, TAG, "[EDR][Native] data will be sent \
+ to callback routine: %s, %d", buf, length);
+ g_EDRPacketReceivedCallback(address, (void*)buf, length, &sentLength);
+ }
+ break;
+
+ default:
+ // Should never occur
+ OIC_LOG_V(DEBUG, TAG, "Invalid server type");
+ return CA_STATUS_FAILED;
+ }
+ (*env)->ReleaseByteArrayElements(env, jbuf, buf, 0);
- switch (type)
- {
- case CA_UNICAST_SERVER:
- case CA_MULTICAST_SERVER:
- // Notify data to upper layer
- if (gEDRPacketReceivedCallback)
- {
- // u_mutex_lock(gMutexSocketListManager);
- uint32_t sentLength = 0;
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] data will be sent to callback routine: %s, %d", responseData, length);
-// sleep(3);
- gEDRPacketReceivedCallback(address, (void*)responseData, length, &sentLength);
- // u_mutex_unlock(gMutexSocketListManager);
- }
- break;
-#ifdef __WITH_DTLS__
- case CA_SECURED_UNICAST_SERVER:
- break;
-#endif //__WITH_DTLS__
- default:
- // Should never occur
- OIC_LOG_V(DEBUG, TAG, "Invalid server type");
- return 0;
+ // close socket after data was sent
+ CAEDRNativeServerSocketClose(env, address, id);
+ break;
}
- (*env)->ReleaseByteArrayElements(env, jbuf, buf, 0);
}
else
{
(*env)->ExceptionDescribe(env);
(*env)->ExceptionClear(env);
OIC_LOG(DEBUG, TAG, "[EDR][Native] btReadData: env error!!");
- return 0;
- }
-
- return 1;
-}
-
-jboolean CAEDRIsConnectedForSocket(JNIEnv *env, jobject socket)
-{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRIsConnectedForSocket...");
-
- if(!CAEDRNativeIsEnableBTAdapter(env))
- {
- OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
- return FALSE;
- }
-
- if(!socket)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRIsConnectedForSocket - socket is null");
- return FALSE;
- }
-
- jclass jni_cid_BTsocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
- if(!jni_cid_BTsocket)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRIsConnectedForSocket - jni_cid_BTsocket is null");
- return FALSE;
- }
-
- jmethodID jni_mid_isConnected = (*env)->GetMethodID(env, jni_cid_BTsocket, "isConnected", "()Z");
- if(!jni_mid_isConnected)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRIsConnectedForSocket - jni_mid_isConnected is null.");
- return FALSE;
- }
-
- jboolean jni_isConnected = (*env)->CallBooleanMethod(env, socket, jni_mid_isConnected);
-
- return jni_isConnected;
-}
-
-void CANativeStartListenTask(JNIEnv *env)
-{
- jobject jni_obj_BTSeverSocket = CAEDRNativeListen(env);
- if(!jni_obj_BTSeverSocket) {
- OIC_LOG(DEBUG, TAG, "[EDR] AcceptThread: jni_obj_BTSeverSocket is null");
- return;
+ return CA_STATUS_FAILED;
}
- gSeverSocket = (*env)->NewGlobalRef(env, jni_obj_BTSeverSocket);
+ return CA_STATUS_OK;
}
jobject CAEDRNativeListen(JNIEnv *env)
{
- if(!CAEDRNativeIsEnableBTAdapter(env))
- {
- OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
- return NULL;
- }
-
OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen");
jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
if(!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen: jni_cid_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_cid_BTAdapter is null");
return NULL;
}
// get BTadpater
- jmethodID jni_mid_getDefaultAdapter =(*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env,
+ jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
if(!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen: jni_cid_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_cid_BTAdapter is null");
return NULL;
}
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env,
+ jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
if(!jni_obj_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen: jni_obj_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_BTAdapter is null");
return NULL;
}
// get listen method ID
jmethodID jni_mid_listen = (*env)->GetMethodID(env, jni_cid_BTAdapter,
- "listenUsingInsecureRfcommWithServiceRecord","(Ljava/lang/String;Ljava/util/UUID;)Landroid/bluetooth/BluetoothServerSocket;");
+ "listenUsingInsecureRfcommWithServiceRecord",
+ "(Ljava/lang/String;Ljava/util/UUID;)Landroid/bluetooth/BluetoothServerSocket;");
if(!jni_mid_listen)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen: jni_mid_listen is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_listen is null");
return NULL;
}
// listenUsingInsecureRfcommWithServiceRecord / listenUsingRfcommWithServiceRecord
jclass jni_cid_uuid = (*env)->FindClass(env, CLASSPATH_BT_UUID);
if(!jni_cid_uuid)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen: jni_mid_listen is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_listen is null");
return NULL;
}
- jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(env, jni_cid_uuid, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
+ jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(env, jni_cid_uuid,
+ "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
if(!jni_mid_fromString)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen: jni_mid_fromString is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_mid_fromString is null");
return NULL;
}
-// jstring uuid = (*env)->NewStringUTF(env, "0000111f-0000-1000-8000-00805f9b8033");
- jstring jni_uuid = (*env)->NewStringUTF(env, "00000000-0000-0000-0000-0000cdab0000");
- jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid, jni_mid_fromString, jni_uuid);
+ jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid,
+ jni_mid_fromString, OIC_EDR_SERVICE_ID);
if(!jni_obj_uuid)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen: jni_obj_uuid is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_uuid is null");
return NULL;
}
// create socket
jstring jni_name = (*env)->NewStringUTF(env, "BluetoothTestSecure");
- jobject jni_obj_BTSeverSocket = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_listen, jni_name, jni_obj_uuid);
+ if (!jni_name)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_name is null");
+ return NULL;
+ }
+ jobject jni_obj_BTSeverSocket = (*env)->CallObjectMethod(env,
+ jni_obj_BTAdapter, jni_mid_listen, jni_name, jni_obj_uuid);
if(!jni_obj_BTSeverSocket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btListen: jni_obj_BTSeverSocket is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btListen: jni_obj_BTSeverSocket is null");
return NULL;
}
- gServerSocketObject = (*env)->NewGlobalRef(env, jni_obj_BTSeverSocket);
+ g_serverSocketObject = (*env)->NewGlobalRef(env, jni_obj_BTSeverSocket);
return jni_obj_BTSeverSocket;
}
{
if(severSocketObject != NULL)
{
- jclass jni_cid_BTServerSocket = (*env)->FindClass(env, "android/bluetooth/BluetoothServerSocket");
+ jclass jni_cid_BTServerSocket = (*env)->FindClass(env,
+ "android/bluetooth/BluetoothServerSocket");
if(!jni_cid_BTServerSocket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: jni_cid_BTServerSocket is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_cid_BTServerSocket is null");
return;
}
- jmethodID jni_mid_accept = (*env)->GetMethodID(env, jni_cid_BTServerSocket, "accept", "()Landroid/bluetooth/BluetoothSocket;");
+ jmethodID jni_mid_accept = (*env)->GetMethodID(env,
+ jni_cid_BTServerSocket, "accept",
+ "(I)Landroid/bluetooth/BluetoothSocket;");
if(!jni_mid_accept)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: jni_mid_accept is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_mid_accept is null");
return;
}
OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: initiating accept...");
jobject jni_obj_BTSocket = NULL;
- jni_obj_BTSocket = (*env)->CallObjectMethod(env, severSocketObject, jni_mid_accept);
+ jni_obj_BTSocket = (*env)->CallObjectMethod(env, severSocketObject, jni_mid_accept, 1000);
if(!jni_obj_BTSocket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: jni_obj_BTSocket is null");
-
- if((*env)->ExceptionCheck(env))
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: socket might closed or timeout!!!");
- (*env)->ExceptionDescribe(env);
- (*env)->ExceptionClear(env);
- return;
- }
+ OIC_LOG(ERROR, TAG, "[EDR][Native] btAccept: jni_obj_BTSocket is null");
+ return;
}
// get remote address
// set socket to list
jobject jni_socket = (*env)->NewGlobalRef(env, jni_obj_BTSocket);
- CAEDRNativeAddDeviceSocketToList(env, jni_socket);
+ CAEDRServerNativeAddDeviceSocketToList(env, jni_socket);
OIC_LOG(DEBUG, TAG, "[EDR][Native] btAccept: Accepted!!");
// update state
- CAEDRUpdateDeviceState(STATE_CONNECTED, address);
+ CAEDRServerUpdateDeviceState(STATE_CONNECTED, address);
+ (*env)->ReleaseStringUTFChars(env, j_str_address, address);
}
else
{
}
}
-void CAEDRNativeServerSocketClose(JNIEnv *env, const char* address, uint32_t id)
+void CAEDRNativeServerSocketClose(JNIEnv *env, const char *address, uint32_t id)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeServerSocketClose");
-
- if(!CAEDRNativeIsEnableBTAdapter(env))
- {
- OIC_LOG(DEBUG, TAG, "BT adpater is not enable");
- return;
- }
jclass jni_cid_BTSocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
if(!jni_cid_BTSocket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
return;
}
jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_BTSocket, "close", "()V");
if(!jni_mid_close)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: jni_mid_close is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_mid_close is null");
return;
}
- jobject jni_obj_socket = CAEDRNativeGetDeviceSocket(id);
+ jobject jni_obj_socket = CAEDRServerNativeGetDeviceSocket(id);
if(!jni_obj_socket)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: jni_obj_socket is not available");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] close: jni_obj_socket is not available");
return;
}
}
// remove socket to list
- CAEDRNativeRemoveDeviceSocket(env, jni_obj_socket);
+ CAEDRServerNativeRemoveDeviceSocket(env, jni_obj_socket);
// update state
- CAEDRUpdateDeviceState(STATE_DISCONNECTED, address);
+ CAEDRServerUpdateDeviceState(STATE_DISCONNECTED, address);
OIC_LOG(DEBUG, TAG, "[EDR][Native] close: disconnected");
}
/**
- * InputStream & BluetoothServerSocket will be close for Terminating
+ * BT State List
*/
-void CAEDRNatvieCloseServerTask(JNIEnv* env)
+void CAEDRServerNativeCreateDeviceStateList()
{
- if(gInputStream)
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeCreateDeviceStateList");
+
+ // create new object array
+ if (g_deviceStateList == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "InputStream will be close");
- jclass jni_cid_InputStream = (*env)->FindClass(env, "java/io/InputStream");
- jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_InputStream, "close", "()V");
- (*env)->CallVoidMethod(env, gInputStream, jni_mid_close);
- (*env)->DeleteGlobalRef(env, gInputStream);
+ OIC_LOG_V(DEBUG, TAG, "Create device list");
+
+ g_deviceStateList = u_arraylist_create();
+ if (g_deviceStateList == NULL)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Create device list is null");
+ }
+ }
+}
+
+void CAEDRServerUpdateDeviceState(uint32_t state, const char *address)
+{
+ state_t *newstate = (state_t*) OICCalloc(1, sizeof(state_t));
+ if (!newstate) {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] newstate is null");
+ return;
}
+ strcpy(newstate->address, address);
+ newstate->state = state;
+
+ CAEDRServerNativeAddDeviceStateToList(newstate);
+}
- if(gSeverSocket)
+void CAEDRServerNativeAddDeviceStateToList(state_t *state)
+{
+ if(!state)
{
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] Accept Resource will be close");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] device is null");
+ return;
+ }
- jclass jni_cid_BTServerSocket = (*env)->FindClass(env, "android/bluetooth/BluetoothServerSocket");
- if(!jni_cid_BTServerSocket)
+ if(!g_deviceStateList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdevice_list is null");
+ return;
+ }
+
+ if(!CAEDRServerNativeIsDeviceInList(state->address)) {
+ CAEDRServerNativeRemoveDevice(state->address); // delete previous state for update new state
+ u_arraylist_add(g_deviceStateList, state); // update new state
+ OIC_LOG_V(DEBUG, TAG, "Set State to Connected State List");
+ }
+}
+
+jboolean CAEDRServerNativeIsDeviceInList(const char* remoteAddress){
+
+ if (!remoteAddress) {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] remoteAddress is null");
+ return JNI_TRUE;
+ }
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceStateList); index++)
+ {
+ state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+ if(!state)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_cid_BTServerSocket is null");
- return;
+ OIC_LOG(ERROR, TAG, "[EDR][Native] state_t object is null");
+ return JNI_TRUE;
}
- jmethodID jni_mid_accept = (*env)->GetMethodID(env, jni_cid_BTServerSocket, "close", "()V");
- if(!jni_mid_accept)
+ if(!strcmp(remoteAddress, state->address))
+ {
+ OIC_LOG_V(DEBUG, TAG, "the device is already set");
+ return JNI_TRUE;
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "there are no the device in list.");
+ return JNI_FALSE;
+}
+
+void CAEDRServerNativeRemoveAllDeviceState()
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveAllDevices");
+
+ if(!g_deviceStateList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+ return;
+ }
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceStateList); index++)
+ {
+ state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+ if(!state)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
+ continue;
+ }
+ OICFree(state);
+ }
+
+ OICFree(g_deviceStateList);
+ g_deviceStateList = NULL;
+ return;
+}
+
+void CAEDRServerNativeRemoveDevice(const char *remoteAddress)
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveDevice");
+
+ if(!g_deviceStateList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+ return;
+ }
+ if (!remoteAddress) {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] remoteAddress is null");
+ return;
+ }
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceStateList); index++)
+ {
+ state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+ if(!state)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
+ continue;
+ }
+
+ if(!strcmp(state->address, remoteAddress))
+ {
+ OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove object : %s", remoteAddress);
+ OICFree(state);
+
+ CAEDRServerReorderingDeviceList(index);
+ break;
+ }
+ }
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] there are no target object");
+ return;
+}
+
+jboolean CAEDRServerIsConnectedDevice(const char *remoteAddress)
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRServerIsConnectedDevice");
+
+ if(!g_deviceStateList)
+ {
+ OIC_LOG(ERROR, TAG, "[EDR][Native] gdeviceStateList is null");
+ return JNI_FALSE;
+ }
+ if (!remoteAddress) {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] remoteAddress is null");
+ return JNI_FALSE;
+ }
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceStateList); index++)
+ {
+ state_t* state = (state_t*) u_arraylist_get(g_deviceStateList, index);
+ if(!state)
+ {
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
+ continue;
+ }
+
+ if(!strcmp(state->address, remoteAddress))
+ {
+ OIC_LOG_V(DEBUG, TAG, "[EDR][Native] check whether it is connected or not");
+
+ return state->state;
+ }
+ }
+ OIC_LOG(DEBUG, TAG, "[EDR][Native] there are no target object");
+ return JNI_FALSE;
+}
+
+void CAEDRServerReorderingDeviceList(uint32_t index)
+{
+ if (index >= g_deviceStateList->length)
+ {
+ return;
+ }
+
+ if (index < g_deviceStateList->length - 1)
+ {
+ memmove(&g_deviceStateList->data[index], &g_deviceStateList->data[index + 1],
+ (g_deviceStateList->length - index - 1) * sizeof(void *));
+ }
+
+ g_deviceStateList->size--;
+ g_deviceStateList->length--;
+}
+
+/**
+ * Device Socket Object List
+ */
+void CAEDRServerNativeCreateDeviceSocketList()
+{
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] CAEDRServerNativeCreateDeviceSocketList");
+
+ // create new object array
+ if (g_deviceObjectList == NULL)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Create Device object list");
+
+ g_deviceObjectList = u_arraylist_create();
+ if (g_deviceObjectList == NULL)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Create Device object list is null");
+ }
+ }
+}
+
+void CAEDRServerNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket)
+{
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] CAEDRServerNativeAddDeviceSocketToList");
+
+ if(!deviceSocket)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] Device is null");
+ return;
+ }
+
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] gdeviceObjectList is null");
+ return;
+ }
+
+ jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
+ if(!jni_remoteAddress)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_remoteAddress is null");
+ return;
+ }
+
+ u_mutex_lock(g_mutexSocketListManager);
+
+ const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+
+ if(!CAEDRServerNativeIsDeviceSocketInList(env, remoteAddress))
+ {
+ jobject gDeviceSocket = (*env)->NewGlobalRef(env, deviceSocket);
+ u_arraylist_add(g_deviceObjectList, gDeviceSocket);
+ OIC_LOG_V(DEBUG, TAG, "Set Object to Array as Element");
+ }
+
+ (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+ u_mutex_unlock(g_mutexSocketListManager);
+}
+
+jboolean CAEDRServerNativeIsDeviceSocketInList(JNIEnv *env, const char* remoteAddress)
+{
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeIsDeviceObjInList");
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceObjectList); index++)
+ {
+
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+ if(!jarrayObj)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
+ return JNI_TRUE;
+ }
+
+ jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
+ if(!jni_setAddress)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_setAddress is null");
+ return JNI_TRUE;
+ }
+
+ const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+ if (!setAddress || !remoteAddress) {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] setAddress or remoteAddress is null");
+ return JNI_TRUE;
+ }
+ if(!strcmp(remoteAddress, setAddress))
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_mid_accept is null");
+ OIC_LOG_V(DEBUG, TAG, "the device is already set");
+ return JNI_TRUE;
+ }
+ else
+ {
+ continue;
+ }
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "there are no the Device obejct in list. we can add");
+ return JNI_FALSE;
+}
+
+void CAEDRServerNativeRemoveAllDeviceSocket(JNIEnv *env)
+{
+ OIC_LOG_V(DEBUG, TAG, "CANativeRemoveAllDeviceObjsList");
+
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] gdeviceObjectList is null");
+ return;
+ }
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceObjectList); index++)
+ {
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+ if(!jarrayObj)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
return;
}
- (*env)->CallVoidMethod(env, gSeverSocket, jni_mid_accept);
- (*env)->DeleteGlobalRef(env, gSeverSocket);
+ (*env)->DeleteGlobalRef(env, jarrayObj);
+ }
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close accept obj");
+ OICFree(g_deviceObjectList);
+ g_deviceObjectList = NULL;
+ return;
+}
+
+void CAEDRServerNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket)
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRServerNativeRemoveDeviceSocket");
+
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] gdeviceObjectList is null");
+ return;
}
+
+ u_mutex_lock(g_mutexSocketListManager);
+
+ jint index;
+ for (index = 0; index < u_arraylist_length(g_deviceObjectList); index++)
+ {
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, index);
+ if(!jarrayObj)
+ {
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
+ continue;
+ }
+
+ jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
+ if(!jni_setAddress)
+ {
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
+ continue;
+ }
+ const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
+ (*env)->ReleaseStringUTFChars(env, jni_setAddress, setAddress);
+
+ jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
+ if(!jni_remoteAddress)
+ {
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_remoteAddress is null");
+ continue;
+ }
+ const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+ (*env)->ReleaseStringUTFChars(env, jni_remoteAddress, remoteAddress);
+
+ if (!setAddress || !remoteAddress) {
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] setAddress or remoteAddress is null");
+ continue;
+ }
+ if(!strcmp(setAddress, remoteAddress))
+ {
+ OIC_LOG_V(DEBUG, TAG, "[BLE][Native] remove object : %s", remoteAddress);
+ (*env)->DeleteGlobalRef(env, jarrayObj);
+
+ CAEDRServerReorderingDeviceSocketList(index);
+ break;
+ }
+ }
+ u_mutex_unlock(g_mutexSocketListManager);
+
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] there are no target object");
+ return;
+}
+
+jobject CAEDRServerNativeGetDeviceSocket(uint32_t idx)
+{
+ OIC_LOG_V(DEBUG, TAG, "CAEDRServerNativeGetDeviceSocket");
+
+ if(idx < 0)
+ {
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] index is not available");
+ return NULL;
+ }
+
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] gdeviceObjectList is null");
+ return NULL;
+ }
+
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceObjectList, idx);
+ if(!jarrayObj)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is not available");
+ return NULL;
+ }
+ return jarrayObj;
+}
+
+uint32_t CAEDRServerGetSocketListLength()
+{
+ if(!g_deviceObjectList)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] gdeviceObjectList is null");
+ return 0;
+ }
+
+ uint32_t length = u_arraylist_length(g_deviceObjectList);
+
+ return length;
+}
+
+void CAEDRServerReorderingDeviceSocketList(uint32_t index)
+{
+ if (index >= g_deviceObjectList->length)
+ {
+ return;
+ }
+
+ if (index < g_deviceObjectList->length - 1)
+ {
+ memmove(&g_deviceObjectList->data[index], &g_deviceObjectList->data[index + 1],
+ (g_deviceObjectList->length - index - 1) * sizeof(void *));
+ }
+
+ g_deviceObjectList->size--;
+ g_deviceObjectList->length--;
}
-void CAEDRServerSetPacketReceivedCallback(CAEDRDataReceivedCallback packetReceivedCallback)
+void CAEDRServerSetPacketReceivedCallback
+ (CAEDRDataReceivedCallback packetReceivedCallback)
{
- gEDRPacketReceivedCallback = packetReceivedCallback;
+ g_EDRPacketReceivedCallback = packetReceivedCallback;
}
+
+
+/******************************************************************
+*
+* Copyright 2014 Samsung Electronics All Rights Reserved.
+*
+*
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*
+******************************************************************/
+
#include <jni.h>
#include <stdio.h>
#include <android/log.h>
#include "uthreadpool.h"
#include "uarraylist.h"
+#define ERROR_CODE (-1)
#define TAG PCF("CA_EDR_UTILS")
static const char *METHODID_OBJECTNONPARAM = "()Landroid/bluetooth/BluetoothAdapter;";
static const char *METHODID_STRINGNONPARAM = "()Ljava/lang/String;";
static const char *CLASSPATH_BT_ADPATER = "android/bluetooth/BluetoothAdapter";
-static u_arraylist_t *gdeviceStateList = NULL;
-static u_arraylist_t *gdeviceObjectList = NULL;
+/**
+ * BT common
+ */
// get address from bluetooth socket
jstring CAEDRNativeGetAddressFromDeviceSocket(JNIEnv *env, jobject bluetoothSocketObj)
jclass jni_cid_BTSocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
if(!jni_cid_BTSocket)
{
- OIC_LOG_V(DEBUG, TAG, "[EDR] getRemoteAddress: jni_cid_BTSocket is null");
+ OIC_LOG_V(ERROR, TAG, "[EDR] getRemoteAddress: jni_cid_BTSocket is null");
return NULL;
}
- jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env, jni_cid_BTSocket, "getRemoteDevice",
- "()Landroid/bluetooth/BluetoothDevice;");
+ jmethodID jni_mid_getRemoteDevice = (*env)->GetMethodID(env,
+ jni_cid_BTSocket, "getRemoteDevice",
+ "()Landroid/bluetooth/BluetoothDevice;");
if(!jni_mid_getRemoteDevice)
{
- OIC_LOG_V(DEBUG, TAG, "[EDR] getRemoteAddress: jni_mid_getRemoteDevice is null");
+ OIC_LOG_V(ERROR, TAG, "[EDR] getRemoteAddress: jni_mid_getRemoteDevice is null");
return NULL;
}
- jobject jni_obj_remoteBTDevice = (*env)->CallObjectMethod(env, bluetoothSocketObj, jni_mid_getRemoteDevice);
+ jobject jni_obj_remoteBTDevice = (*env)->CallObjectMethod(env,
+ bluetoothSocketObj, jni_mid_getRemoteDevice);
if(!jni_obj_remoteBTDevice)
{
- OIC_LOG_V(DEBUG, TAG, "[EDR] getRemoteAddress: jni_obj_remoteBTDevice is null");
+ OIC_LOG_V(ERROR, TAG, "[EDR] getRemoteAddress: jni_obj_remoteBTDevice is null");
return NULL;
}
jclass jni_cid_BTDevice = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
- jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice, "getAddress", "()Ljava/lang/String;");
+ if(!jni_cid_BTDevice)
+ {
+ OIC_LOG_V(ERROR, TAG, "[EDR] getRemoteAddress: jni_cid_BTDevice is null");
+ return NULL;
+ }
+ jmethodID j_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTDevice,
+ "getAddress", "()Ljava/lang/String;");
+ if(!j_mid_getAddress)
+ {
+ OIC_LOG_V(ERROR, TAG, "[EDR] getRemoteAddress: j_mid_getAddress is null");
+ return NULL;
+ }
jstring j_str_address = (*env)->CallObjectMethod(env, jni_obj_remoteBTDevice, j_mid_getAddress);
- if(j_str_address)
+ if(!j_str_address)
{
- const char * address = (*env)->GetStringUTFChars(env, j_str_address, NULL);
- OIC_LOG_V(DEBUG, TAG, "[EDR] getRemoteAddress: ~~ remote device address is %s", address);
-// (*env)->ReleaseStringUTFChars(env, j_str_address, address);
- } else {
+ OIC_LOG_V(ERROR, TAG, "[EDR] getRemoteAddress: j_str_address is null");
return NULL;
}
+
return j_str_address;
}
jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
if(!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getAddress: jni_cid_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_cid_BTAdapter is null");
return NULL;
}
- jmethodID jni_mid_getDefaultAdapter =
- (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env,
+ jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
if(!jni_mid_getDefaultAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getAddress: jni_mid_getDefaultAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_mid_getDefaultAdapter is null");
return NULL;
}
- jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTAdapter, "getAddress", METHODID_STRINGNONPARAM);
+ jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTAdapter,
+ "getAddress", METHODID_STRINGNONPARAM);
if(!jni_mid_getAddress)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getAddress: jni_mid_getAddress is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_mid_getAddress is null");
return NULL;
}
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env,
+ jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
if(!jni_obj_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getAddress: jni_obj_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_obj_BTAdapter is null");
return NULL;
}
- jstring jni_str_address = (jstring)(*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_getAddress);
+ jstring jni_str_address = (jstring)(*env)->CallObjectMethod(env,
+ jni_obj_BTAdapter, jni_mid_getAddress);
if(!jni_str_address)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getAddress: jni_str_address is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getAddress: jni_str_address is null");
return NULL;
}
jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
if(!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getBondedDevices: jni_cid_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_cid_BTAdapter is null");
return NULL;
}
- jmethodID jni_mid_getDefaultAdapter =
- (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env,
+ jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env,
+ jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
if(!jni_obj_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getBondedDevices: bluetooth adapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: bluetooth adapter is null");
return NULL;
}
"getBondedDevices", "()Ljava/util/Set;");
if(!jni_mid_getBondedDevices)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getBondedDevices: jni_mid_getBondedDevicesr is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_mid_getBondedDevicesr is null");
return NULL;
}
- jobject jni_obj_setPairedDevices = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_getBondedDevices);
+ jobject jni_obj_setPairedDevices = (*env)->CallObjectMethod(env,
+ jni_obj_BTAdapter, jni_mid_getBondedDevices);
if(!jni_obj_setPairedDevices)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getBondedDevices: jni_obj_setPairedDevices is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_obj_setPairedDevices is null");
return NULL;
}
// Convert the set to an object array
// object[] array = Set<BluetoothDevice>.toArray();
jclass jni_cid_Set = (*env)->FindClass(env, "java/util/Set");
- jmethodID jni_mid_toArray = (*env)->GetMethodID(env, jni_cid_Set, "toArray", "()[Ljava/lang/Object;");
+ jmethodID jni_mid_toArray = (*env)->GetMethodID(env, jni_cid_Set, "toArray",
+ "()[Ljava/lang/Object;");
if(!jni_mid_toArray)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getBondedDevices: jni_mid_toArray is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_mid_toArray is null");
return NULL;
}
jni_obj_setPairedDevices, jni_mid_toArray));
if(!jni_arrayPairedDevices)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getBondedDevices: jni_arrayPairedDevices is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getBondedDevices: jni_arrayPairedDevices is null");
return NULL;
}
jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
if(!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] getBTStateOnInfo: jni_cid_BTAdapter is null");
- return -1;
+ OIC_LOG(ERROR, TAG, "[EDR][Native] getBTStateOnInfo: jni_cid_BTAdapter is null");
+ return ERROR_CODE;
}
jfieldID jni_fid_stateon = (*env)->GetStaticFieldID(env, jni_cid_BTAdapter, "STATE_ON", "I");
if (jni_fid_stateon == 0)
{
OIC_LOG(DEBUG, TAG, "[EDR][Native] get_field_state is 0");
- return -1;
+ return ERROR_CODE;
}
jint jni_int_val = (*env)->GetStaticIntField(env, jni_cid_BTAdapter, jni_fid_stateon);
jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
if(!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_cid_BTAdapter: jni_cid_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_BTAdapter: jni_cid_BTAdapter is null");
return FALSE;
}
- jmethodID jni_mid_getDefaultAdapter =
- (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env,
+ jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
if(!jni_mid_getDefaultAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_mid_getDefaultAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_getDefaultAdapter is null");
return FALSE;
}
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env,
+ jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
if(!jni_obj_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_obj_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_obj_BTAdapter is null");
return FALSE;
}
"()Z");
if(!jni_mid_isEnable)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_mid_isEnable is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_isEnable is null");
return FALSE;
}
jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
if(!jni_cid_device_list)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_cid_device_list is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_cid_device_list is null");
return NULL;
}
"()Ljava/lang/String;");
if(!jni_mid_getAddress)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_mid_getAddress is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_mid_getAddress is null");
return NULL;
}
- jstring jni_address = (jstring)(*env)->CallObjectMethod(env, bluetoothDevice, jni_mid_getAddress);
+ jstring jni_address = (jstring)(*env)->CallObjectMethod(env,
+ bluetoothDevice, jni_mid_getAddress);
if(!jni_address)
{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jni_address is null");
+ OIC_LOG(ERROR, TAG, "[EDR][Native] jni_address is null");
return NULL;
}
return jni_address;
}
-
-/**
- * BT State List
- */
-void CAEDRNativeCreateDeviceStateList()
-{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeCreateDeviceStateList");
-
- // create new object array
- if (gdeviceStateList == NULL)
- {
- OIC_LOG_V(DEBUG, TAG, "Create device list");
-
- gdeviceStateList = u_arraylist_create();
- }
-}
-
-void CAEDRUpdateDeviceState(uint32_t state, const char* address)
-{
- state_t *newstate = (state_t*) OICMalloc( sizeof(state_t) );
- memset(newstate->address, 0, CA_MACADDR_SIZE);
- strcpy(newstate->address, address);
- newstate->state = state;
-
- CAEDRNativeAddDeviceStateToList(newstate);
-}
-
-void CAEDRNativeAddDeviceStateToList(state_t* state)
-{
- if(!state)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] device is null");
- return;
- }
-
- if(!gdeviceStateList)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] gdevice_list is null");
- return;
- }
-
- if(CAEDRNativeIsDeviceInList(state->address)) {
- CAEDRNativeRemoveDevice(state->address); // delete previous state for update new state
- }
- u_arraylist_add(gdeviceStateList, state); // update new state
- OIC_LOG_V(DEBUG, TAG, "Set State Info to List : %d", state->state);
-}
-
-jboolean CAEDRNativeIsDeviceInList(const char* remoteAddress){
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceStateList); index++)
- {
- state_t* state = (state_t*) u_arraylist_get(gdeviceStateList, index);
- if(!state)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
- return TRUE;
- }
-
- if(!strcmp(remoteAddress, state->address))
- {
- OIC_LOG_V(DEBUG, TAG, "the device is already set");
- return TRUE;
- }
- else
- {
- continue;
- }
- }
-
- OIC_LOG_V(DEBUG, TAG, "there are no the device in list.");
- return FALSE;
-}
-
-void CAEDRNativeRemoveAllDeviceState()
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveAllDevices");
-
- if(!gdeviceStateList)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] gdeviceStateList is null");
- return;
- }
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceStateList); index++)
- {
- state_t* state = (state_t*) u_arraylist_get(gdeviceStateList, index);
- if(!state)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] jarrayObj is null");
- continue;
- }
- OICFree(state);
- }
-
- OICFree(gdeviceStateList);
- gdeviceStateList = NULL;
- return;
-}
-
-void CAEDRNativeRemoveDevice(const char* remoteAddress)
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveDeviceforStateList");
-
- if(!gdeviceStateList)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] gdeviceStateList is null");
- return;
- }
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceStateList); index++)
- {
- state_t* state = (state_t*) u_arraylist_get(gdeviceStateList, index);
- if(!state)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
- continue;
- }
-
- if(!strcmp(state->address, remoteAddress))
- {
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] remove state : %s", remoteAddress);
- OICFree(state);
-
- CAEDRReorderingDeviceList(index);
- break;
- }
- }
- return;
-}
-
-jboolean CAEDRIsConnectedDevice(const char* remoteAddress)
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRIsConnectedDevice");
-
- if(!gdeviceStateList)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] gdeviceStateList is null");
- return FALSE;
- }
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceStateList); index++)
- {
- state_t* state = (state_t*) u_arraylist_get(gdeviceStateList, index);
- if(!state)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] state_t object is null");
- continue;
- }
-
- if(!strcmp(state->address, remoteAddress))
- {
- OIC_LOG_V(DEBUG, TAG, "[EDR][Native] check whether it is connected or not");
-
- return state->state;
- }
- }
- return FALSE;
-}
-
-void CAEDRReorderingDeviceList(uint32_t index)
-{
- if (index >= gdeviceStateList->length)
- {
- return;
- }
-
- if (index < gdeviceStateList->length - 1)
- {
- memmove(&gdeviceStateList->data[index], &gdeviceStateList->data[index + 1],
- (gdeviceStateList->length - index - 1) * sizeof(void *));
- }
-
- gdeviceStateList->size--;
- gdeviceStateList->length--;
-}
-
-/**
- * Device Socket Object List
- */
-void CAEDRNativeCreateDeviceSocketList()
-{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] CAEDRNativeCreateDeviceSocketList");
-
- // create new object array
- if (gdeviceObjectList == NULL)
- {
- OIC_LOG_V(DEBUG, TAG, "Create Device object list");
-
- gdeviceObjectList = u_arraylist_create();
- }
-}
-
-void CAEDRNativeAddDeviceSocketToList(JNIEnv *env, jobject deviceSocket)
-{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeAddDeviceobjToList");
-
- if(!deviceSocket)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] Device is null");
- return;
- }
-
- if(!gdeviceObjectList)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceObjectList is null");
- return;
- }
-
- jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
- if(!jni_remoteAddress)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_remoteAddress is null");
- return;
- }
-
- const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
-
- if(!CAEDRNativeIsDeviceSocketInList(env, remoteAddress))
- {
- jobject gDeviceSocker = (*env)->NewGlobalRef(env, deviceSocket);
- u_arraylist_add(gdeviceObjectList, gDeviceSocker);
- OIC_LOG_V(DEBUG, TAG, "Set Socket Object to Array");
- }
-}
-
-jboolean CAEDRNativeIsDeviceSocketInList(JNIEnv *env, const char* remoteAddress)
-{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeIsDeviceObjInList");
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceObjectList); index++)
- {
-
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceObjectList, index);
- if(!jarrayObj)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
- return TRUE;
- }
-
- jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
- if(!jni_setAddress)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
- return TRUE;
- }
-
- const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
-
- if(!strcmp(remoteAddress, setAddress))
- {
- OIC_LOG_V(DEBUG, TAG, "the device is already set");
- return TRUE;
- }
- else
- {
- continue;
- }
- }
-
- OIC_LOG_V(DEBUG, TAG, "there are no the Device obejct in list. we can add");
- return FALSE;
-}
-
-void CAEDRNativeSocketCloseToAll(JNIEnv *env)
-{
- OIC_LOG(DEBUG, TAG, "[EDR][Native] CAEDRNativeSocketCloseToAll");
-
- if(!gdeviceObjectList)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceObjectList is null");
- return;
- }
-
- jclass jni_cid_BTSocket = (*env)->FindClass(env, "android/bluetooth/BluetoothSocket");
- if(!jni_cid_BTSocket)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: jni_cid_BTSocket is null");
- return;
- }
-
- jmethodID jni_mid_close = (*env)->GetMethodID(env, jni_cid_BTSocket, "close", "()V");
- if(!jni_mid_close)
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: jni_mid_close is null");
- return;
- }
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceObjectList); index++)
- {
- jobject jni_obj_socket = (jobject) u_arraylist_get(gdeviceObjectList, index);
- if(!jni_obj_socket)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] socket obj is null");
- return;
- }
-
- (*env)->CallVoidMethod(env, jni_obj_socket, jni_mid_close);
-
- if((*env)->ExceptionCheck(env))
- {
- OIC_LOG(DEBUG, TAG, "[EDR][Native] close: close is Failed!!!");
- (*env)->ExceptionDescribe(env);
- (*env)->ExceptionClear(env);
- return;
- }
- }
-}
-
-void CAEDRNativeRemoveAllDeviceSocket(JNIEnv *env)
-{
- OIC_LOG_V(DEBUG, TAG, "CANativeRemoveAllDeviceObjsList");
-
- if(!gdeviceObjectList)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceObjectList is null");
- return;
- }
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceObjectList); index++)
- {
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceObjectList, index);
- if(!jarrayObj)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
- return;
- }
- (*env)->DeleteGlobalRef(env, jarrayObj);
- }
-
- OICFree(gdeviceObjectList);
- gdeviceObjectList = NULL;
- return;
-}
-
-void CAEDRNativeRemoveDeviceSocket(JNIEnv *env, jobject deviceSocket)
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveDeviceSocket");
-
- if(!gdeviceObjectList)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceObjectList is null");
- return;
- }
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceObjectList); index++)
- {
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceObjectList, index);
- if(!jarrayObj)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
- continue;
- }
-
- jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
- if(!jni_setAddress)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
- continue;
- }
- const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
-
- jstring jni_remoteAddress = CAEDRNativeGetAddressFromDeviceSocket(env, deviceSocket);
- if(!jni_remoteAddress)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_remoteAddress is null");
- continue;
- }
- const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
-
- if(!strcmp(setAddress, remoteAddress))
- {
- OIC_LOG_V(DEBUG, TAG, "[BLE][Native] remove object : %s", remoteAddress);
- (*env)->DeleteGlobalRef(env, jarrayObj);
-
- CAEDRReorderingDeviceSocketList(index);
- break;
- }
- }
-
- OIC_LOG(DEBUG, TAG, "[BLE][Native] there are no target object");
- return;
-}
-
-void CAEDRNativeRemoveDeviceSocketBaseAddr(JNIEnv *env, jstring address)
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRNativeRemoveDeviceSocket");
-
- if(!gdeviceObjectList)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceObjectList is null");
- return;
- }
-
- jint index;
- for (index = 0; index < u_arraylist_length(gdeviceObjectList); index++)
- {
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceObjectList, index);
- if(!jarrayObj)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
- continue;
- }
-
- jstring jni_setAddress = CAEDRNativeGetAddressFromDeviceSocket(env, jarrayObj);
- if(!jni_setAddress)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
- continue;
- }
- const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
- const char* remoteAddress = (*env)->GetStringUTFChars(env, address, NULL);
-
- if(!strcmp(setAddress, remoteAddress))
- {
- OIC_LOG_V(DEBUG, TAG, "[BLE][Native] remove object : %s", remoteAddress);
- (*env)->DeleteGlobalRef(env, jarrayObj);
-
- CAEDRReorderingDeviceSocketList(index);
- break;
- }
- }
-
- OIC_LOG(DEBUG, TAG, "[BLE][Native] there are no target object");
- return;
-}
-
-jobject CAEDRNativeGetDeviceSocket(uint32_t idx)
-{
- OIC_LOG_V(DEBUG, TAG, "CAEDRNativeGetDeviceSocket");
-
- if(!gdeviceObjectList)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceObjectList is null");
- return NULL;
- }
-
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceObjectList, idx);
- if(!jarrayObj)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is not available");
- return NULL;
- }
- return jarrayObj;
-}
-
-uint32_t CAEDRGetSocketListLength()
-{
- if(!gdeviceObjectList)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceObjectList is null");
- return 0;
- }
-
- uint32_t length = u_arraylist_length(gdeviceObjectList);
-
- return length;
-}
-
-void CAEDRReorderingDeviceSocketList(uint32_t index)
-{
- if (index >= gdeviceObjectList->length)
- {
- return;
- }
-
- if (index < gdeviceObjectList->length - 1)
- {
- memmove(&gdeviceObjectList->data[index], &gdeviceObjectList->data[index + 1],
- (gdeviceObjectList->length - index - 1) * sizeof(void *));
- }
-
- gdeviceObjectList->size--;
- gdeviceObjectList->length--;
-}
#include "logger.h"
#include "camsgparser.h"
#include "caqueueingthread.h"
+#include "oic_malloc.h"
/**
* @var EDR_ADAPTER_TAG
#define EDR_ADAPTER_TAG "CA_EDR_ADAPTER"
/**
- * @var gEDRThreadPool
+ * @var g_edrThreadPool
* @brief Reference to threadpool.
*/
-static u_thread_pool_t gEDRThreadPool = NULL;
+static u_thread_pool_t g_edrThreadPool = NULL;
/**
- * @var gSendQueueHandle
+ * @var g_sendQueueHandle
* @brief Queue handle for Send Data
*/
-static CAQueueingThread_t *gSendQueueHandle = NULL;
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
/**
- * @var gRecvQueueHandle
+ * @var g_recvQueueHandle
* @brief Queue handle for Receive Data
*/
-static CAQueueingThread_t *gRecvQueueHandle = NULL;
+static CAQueueingThread_t *g_recvQueueHandle = NULL;
/**
- * @var isHeaderAvailable
+ * @var g_isHeaderAvailable
* @brief to differentiate btw header and data packet.
*/
-static CABool_t isHeaderAvailable = CA_FALSE;
+static bool g_isHeaderAvailable = false;
/**
- * @var gAdapterState
+ * @var g_adapterState
* @brief Storing Adapter state information
*/
-static CABool_t gAdapterState = CA_TRUE;
+static bool g_adapterState = true;
/**
- * @var gNetworkPacketReceivedCallback
+ * @var g_networkPacketReceivedCallback
* @brief Maintains the callback to be notified on receival of network packets from other
* Bluetooth devices.
*/
-static CANetworkPacketReceivedCallback gNetworkPacketReceivedCallback = NULL;
+static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
/**
- * @var gNetworkChangeCallback
+ * @var g_networkChangeCallback
* @brief Maintains the callback to be notified on local bluetooth adapter status change.
*/
-static CANetworkChangeCallback gNetworkChangeCallback = NULL;
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
/**
- * @var gLocalConnectivity
+ * @var g_localConnectivity
* @brief Information of local Bluetooth adapter.
*/
-static CALocalConnectivity_t *gLocalConnectivity = NULL;
+static CALocalConnectivity_t *g_localConnectivity = NULL;
/**
- * @var gServerId
+ * @var g_serverId
* @brief Storing RfcommserverUUID
*/
-static int32_t gServerId = -1;
+static int g_serverId = -1;
/**
- * @var gServerState
+ * @var g_serverState
* @brief Storing Rfcommserver state information
*/
-static CABool_t gServerState = CA_FALSE;
+static bool g_serverState = false;
static CAResult_t CAStartServer(void);
static CAResult_t CAEDRInitializeQueueHandlers(void);
void CAAdapterDataSendHandler(void *context);
void CAAdapterDataReceiverHandler(void *context);
CAResult_t CAAdapterStopQueue();
-void CAAdapterRecvData(const char *remoteAddress, void *data,
+void CAAdapterRecvData(const char *remoteAddress, const void *data,
uint32_t dataLength, uint32_t *sentLength);
void CAEDRNotifyNetworkStatus(CANetworkStatus_t status);
void CAEDROnNetworkStatusChanged(void *context);
CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength);
+ const void *data, uint32_t dataLength, uint32_t *sentLength);
CAEDRNetworkEvent *CAEDRCreateNetworkEvent(CALocalConnectivity_t *connectivity,
CANetworkStatus_t status);
CAResult_t CAEDRClientSendData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength);
+ const void *data, uint32_t dataLength, uint32_t *sentLength);
/**
* @fn CACreateEDRData
* @brief Helper function to create CAEDRData
*/
-static CAEDRData *CACreateEDRData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+static CAEDRData *CACreateEDRData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
/**
VERIFY_NON_NULL(packetReceivedCallback, EDR_ADAPTER_TAG, "data receive callback is NULL");
VERIFY_NON_NULL(networkStateChangeCallback, EDR_ADAPTER_TAG,
"network state change callback is NULL");
- VERIFY_NON_NULL(handle, EDR_ADAPTER_TAG, "Thread pool hanlde is NULL");
+ VERIFY_NON_NULL(handle, EDR_ADAPTER_TAG, "Thread pool handle is NULL");
// Register the callbacks
- gEDRThreadPool = handle;
- gNetworkPacketReceivedCallback = packetReceivedCallback;
- gNetworkChangeCallback = networkStateChangeCallback;
+ g_edrThreadPool = handle;
+ g_networkPacketReceivedCallback = packetReceivedCallback;
+ g_networkChangeCallback = networkStateChangeCallback;
// Initialize EDR Network Monitor
CAResult_t err = CAEDRInitializeNetworkMonitor();
CAConnectivityHandler_t handler;
handler.startAdapter = CAStartEDR;
handler.startListenServer = CAStartEDRListeningServer;
- handler.startDiscoverServer = CAStartEDRDiscoveryServer;
+ handler.startDiscoveryServer = CAStartEDRDiscoveryServer;
handler.sendData = CASendEDRUnicastData;
handler.sendDataToAll = CASendEDRMulticastData;
handler.GetnetInfo = CAGetEDRInterfaceInformation;
}
// Get Bluetooth adapter state
- CABool_t adapterState = CA_FALSE;
+ bool adapterState = false;
if (CA_STATUS_OK != CAEDRGetAdapterEnableState(&adapterState))
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to get adapter enable state");
return CA_STATUS_FAILED;
}
- if (CA_FALSE == adapterState)
+ if (false == adapterState)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
- gAdapterState = CA_FALSE;
+ g_adapterState = false;
return CA_STATUS_OK;
}
return CAStartServer();
}
-uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
CAResult_t err = CA_STATUS_OK;
// Input validation
- VERIFY_NON_NULL_RET(remoteEndpoint, EDR_ADAPTER_TAG, "Remote endpoint is null", 0);
- VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", 0);
+ VERIFY_NON_NULL_RET(remoteEndpoint, EDR_ADAPTER_TAG, "Remote endpoint is null", -1);
+ VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", -1);
if (0 == strlen(remoteEndpoint->addressInfo.BT.btMacAddress))
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid input: EDR Address is empty!");
- return 0;
+ return -1;
}
if (0 == dataLength)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
- return 0;
+ return -1;
}
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "CASendEDRUnicastData : %s", data);
-
uint32_t sentLength = 0;
const char *serviceUUID = OIC_EDR_SERVICE_ID;
const char *address = remoteEndpoint->addressInfo.BT.btMacAddress;
dataLength, &sentLength)))
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Send unicast data failed!, error num [%d]", err);
- return 0;
+ return -1;
}
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
return sentLength;
}
-uint32_t CASendEDRMulticastData(void *data, uint32_t dataLength)
+int32_t CASendEDRMulticastData(const void *data, uint32_t dataLength)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN - CASendEDRMulticastData");
CAResult_t err = CA_STATUS_OK;
// Input validation
- VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", 0);
+ VERIFY_NON_NULL_RET(data, EDR_ADAPTER_TAG, "Data is null", -1);
if (0 == dataLength)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
- return 0;
+ return -1;
}
uint32_t sentLen = 0;
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Send multicast data failed!, error num [%d]",
err);
- return 0;
+ return -1;
}
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT - CASendEDRMulticastData");
return sentLen;
}
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
// Stop RFComm server if it is running
- if (-1 != gServerId)
+ if (-1 != g_serverId)
{
- CAEDRServerStop(gServerId);
- gServerId = -1;
+ CAEDRServerStop(g_serverId);
+ g_serverId = -1;
}
// Stop network monitor
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- // Stop EDR adapter
- CAStopEDR();
-
// Terminate EDR Network Monitor
CAEDRTerminateNetworkMonitor();
- // Terminate BT Client
- CAEDRTerminateClient();
-
// Terminate Send/Receive data messages queues
CAAdapterTerminateQueues();
- gNetworkPacketReceivedCallback = NULL;
- gNetworkChangeCallback = NULL;
+ g_networkPacketReceivedCallback = NULL;
+ g_networkChangeCallback = NULL;
// Terminate thread pool
- gEDRThreadPool = NULL;
+ g_edrThreadPool = NULL;
+
+ // Terminate BT Client
+ CAEDRClientTerminate();
+
+ // Terminate BT Server
+ CAEDRServerTerminate();
// Free LocalConnectivity information
- CAAdapterFreeLocalEndpoint(gLocalConnectivity);
- gLocalConnectivity = NULL;
+ CAAdapterFreeLocalEndpoint(g_localConnectivity);
+ g_localConnectivity = NULL;
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
CAResult_t err = CA_STATUS_OK;
- if (CA_FALSE == gAdapterState)
+ if (false == g_adapterState)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
- // Setting gServerState for starting Rfcommserver when adapter starts
- gServerState = TRUE;
+ // Setting g_serverState for starting Rfcommserver when adapter starts
+ g_serverState = TRUE;
return CA_STATUS_OK;
}
- if (-1 < gServerId)
+ if (-1 < g_serverId)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Server is already in running state.");
return CA_STATUS_OK;
}
- if (CA_STATUS_OK != (err = CAEDRServerStart(OIC_EDR_SERVICE_ID, &gServerId, gEDRThreadPool)))
+ if (CA_STATUS_OK != (err = CAEDRServerStart(OIC_EDR_SERVICE_ID, &g_serverId, g_edrThreadPool)))
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to start RFCOMM server!, error num [%d]",
err);
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
// Check if the message queue is already initialized
- if (gSendQueueHandle)
+ if (g_sendQueueHandle)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Already queue is initialized!");
return CA_STATUS_OK;
}
- gSendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
- if (!gSendQueueHandle)
+ g_sendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_sendQueueHandle)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(gSendQueueHandle, gEDRThreadPool,
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_edrThreadPool,
CAAdapterDataSendHandler, CAEDRDataDestroyer))
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Initialize send queue thread");
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
// Check if the message queue is already initialized
- if (gRecvQueueHandle)
+ if (g_recvQueueHandle)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Already queue is initialized!");
return CA_STATUS_OK;
}
- gRecvQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
- if (!gRecvQueueHandle)
+ g_recvQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_recvQueueHandle)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(gRecvQueueHandle, gEDRThreadPool,
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_recvQueueHandle, g_edrThreadPool,
CAAdapterDataReceiverHandler, CAEDRDataDestroyer))
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Initialize send queue thread");
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- if (gSendQueueHandle)
+ if (g_sendQueueHandle)
{
- CAQueueingThreadDestroy(gSendQueueHandle);
- gSendQueueHandle = NULL;
+ CAQueueingThreadDestroy(g_sendQueueHandle);
+ g_sendQueueHandle = NULL;
}
- if (gRecvQueueHandle)
+ if (g_recvQueueHandle)
{
- CAQueueingThreadDestroy(gRecvQueueHandle);
- gRecvQueueHandle = NULL;
+ CAQueueingThreadDestroy(g_recvQueueHandle);
+ g_recvQueueHandle = NULL;
}
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
void CAAdapterDataSendHandler(void *context)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN - CAAdapterDataSendHandler");
CAEDRData *message = (CAEDRData *) context;
if (message == NULL)
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to get message!");
return;
}
+
const char *remoteAddress = NULL;
const char *serviceUUID = NULL;
uint32_t sentLength = 0;
+ if(NULL == message->remoteEndpoint)
+ {
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "remoteEndpoint is not available");
+ }
+
remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
serviceUUID = message->remoteEndpoint->resourceUri;
- char *dataSegment = NULL;
- uint32_t dataSegmentLength = message->dataLen + CA_HEADER_LENGTH;
- int32_t datalen = message->dataLen;
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "checking for fragmentation and the dataLen is %d",
- datalen);
-
+ message->dataLen);
- char *header = (char *) OICMalloc(sizeof(char) * CA_HEADER_LENGTH);
+ char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
VERIFY_NON_NULL_VOID(header, EDR_ADAPTER_TAG, "Malloc failed");
- dataSegment = (char *) OICMalloc(sizeof(char) * dataSegmentLength);
+ char* dataSegment = (char *) OICCalloc(message->dataLen + CA_HEADER_LENGTH, sizeof(char));
if (NULL == dataSegment)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Malloc failed");
return;
}
- memset(header, 0x0, sizeof(char) * CA_HEADER_LENGTH);
- memset(dataSegment, 0x0, dataSegmentLength);
-
CAResult_t result = CAGenerateHeader(header, message->dataLen);
if (CA_STATUS_OK != result )
{
}
}
- // Free message
- //CAFreeEDRData(message);
-
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
CAResult_t CAEDRClientSendData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength)
+ const void *data, uint32_t dataLength, uint32_t *sentLength)
{
+
// Send the first segment with the header.
- if (strlen(remoteAddress)) //Unicast data
+ if ((NULL != remoteAddress) && (0 < strlen(remoteAddress))) //Unicast data
{
if (CA_STATUS_OK != CAEDRClientSendUnicastData(remoteAddress, serviceUUID,
data, dataLength, sentLength))
}
return CA_STATUS_OK;
}
+
void CAAdapterDataReceiverHandler(void *context)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN_CAAdapterDataReceiverHandler");
-
CAEDRData *message = (CAEDRData *) context;
if (message == NULL)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to get message!");
return;
}
- const char *remoteAddress = NULL;
- const char *serviceUUID = NULL;
+
static uint32_t recvDataLen = 0;
static uint32_t totalDataLen = 0;
static char *defragData = NULL;
static CARemoteEndpoint_t *remoteEndpoint = NULL;
- if (!isHeaderAvailable)
+ if (!g_isHeaderAvailable)
{
- char *header = (char *) OICMalloc(sizeof(char) * CA_HEADER_LENGTH);
-
- if (NULL == header)
+ totalDataLen = CAParseHeader((char*)message->data);
+ if (totalDataLen == 0)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Out of memory (header)!");
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "totalDataLen is zero");
return;
}
- memcpy(header, (char *)message->data, CA_HEADER_LENGTH);
- totalDataLen = CAParseHeader(header);
+
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Total data to be accumulated [%d] bytes",
totalDataLen);
- defragData = NULL;
- if (totalDataLen == 0)
+
+ defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
+ if (!defragData)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, " totalDataLen is zero");
- OICFree(header);
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "defragData is null");
return;
}
- defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
- OICFree(header);
- remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
- serviceUUID = message->remoteEndpoint->resourceUri;
+ const char *remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
+ const char *serviceUUID = message->remoteEndpoint->resourceUri;
remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
serviceUUID);
memcpy(defragData + recvDataLen, message->data + CA_HEADER_LENGTH,
message->dataLen - CA_HEADER_LENGTH);
recvDataLen += message->dataLen - CA_HEADER_LENGTH;
- isHeaderAvailable = CA_TRUE;
+ g_isHeaderAvailable = true;
}
else
{
memcpy(defragData + recvDataLen, message->data, message->dataLen);
recvDataLen += message->dataLen ;
}
- //CAFreeEDRData(message);
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Sending data up !");
- gNetworkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
- recvDataLen = 0;
- totalDataLen = 0;
- remoteEndpoint = NULL;
- isHeaderAvailable = CA_FALSE;
+ if (totalDataLen == recvDataLen)
+ {
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Sending data up !");
+ g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
+ recvDataLen = 0;
+ totalDataLen = 0;
+ remoteEndpoint = NULL;
+ g_isHeaderAvailable = false;
+ }
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT_CAAdapterDataReceiverHandler");
}
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
// Start send queue thread
- if (CA_STATUS_OK != CAQueueingThreadStart(gSendQueueHandle))
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Start Send Data Thread");
CAEDRClientUnsetCallbacks();
}
// Start receive queue thread
- if (CA_STATUS_OK != CAQueueingThreadStart(gRecvQueueHandle))
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_recvQueueHandle))
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Failed to Start Receive Data Thread");
CAEDRClientUnsetCallbacks();
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
//Stop send queue thread
- CAQueueingThreadStop(gSendQueueHandle);
+ CAQueueingThreadStop(g_sendQueueHandle);
//Stop receive queue thread
- CAQueueingThreadStop(gRecvQueueHandle);
+ CAQueueingThreadStop(g_recvQueueHandle);
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
-void CAAdapterRecvData(const char *remoteAddress, void *data,
+void CAAdapterRecvData(const char *remoteAddress, const void *data,
uint32_t dataLength, uint32_t *sentLength)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- if (CA_FALSE == gAdapterState)
+ if (false == g_adapterState)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
*sentLength = 0;
// Add message to data queue
CAEDRData *edrData = CACreateEDRData(remoteEndpoint, data, dataLength);
- CAQueueingThreadAddData(gRecvQueueHandle, edrData, sizeof(CARemoteEndpoint_t));
+ CAQueueingThreadAddData(g_recvQueueHandle, edrData, sizeof(CARemoteEndpoint_t));
*sentLength = dataLength;
// Free remote endpoint
}
CAResult_t CAAdapterSendData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength)
+ const void *data, uint32_t dataLength, uint32_t *sentLength)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN - CAAdapterSendData");
- if (CA_FALSE == gAdapterState)
+ if (false == g_adapterState)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
*sentLength = 0;
// Add message to data queue
CAEDRData *edrData = CACreateEDRData(remoteEndpoint, data, dataLength);
- CAQueueingThreadAddData(gSendQueueHandle, edrData, sizeof(CARemoteEndpoint_t));
+ CAQueueingThreadAddData(g_sendQueueHandle, edrData, sizeof(CAEDRData));
*sentLength = dataLength;
// Free remote endpoint
CAAdapterFreeRemoteEndpoint(remoteEndpoint);
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT - CAAdapterSendData");
return CA_STATUS_OK;
}
void CAEDRNotifyNetworkStatus(CANetworkStatus_t status)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "CAEDRNotifyNetworkStatus, status:%d", status);
+ OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
// Create localconnectivity
- if (NULL == gLocalConnectivity)
+ if (NULL == g_localConnectivity)
{
- CAEDRGetInterfaceInformation(&gLocalConnectivity);
+ CAEDRGetInterfaceInformation(&g_localConnectivity);
}
if(CA_INTERFACE_UP == status)
{
- if(CA_FALSE == gAdapterState)
+ if(false == g_adapterState)
{
// Get Bluetooth adapter state
- CABool_t adapterState = CA_FALSE;
+ bool adapterState = false;
if (CA_STATUS_OK != CAEDRGetAdapterEnableState(&adapterState))
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to get adapter enable state");
return;
}
- if (CA_FALSE== adapterState)
+ if (false== adapterState)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth adapter is disabled!");
- gAdapterState = CA_FALSE;
+ g_adapterState = false;
return;
}
CAEDRClientSetCallbacks();
- gAdapterState = CA_TRUE;
+ g_adapterState = true;
CAAdapterStartQueue();
// starting RFCommServer
- if(CA_TRUE == gServerState)
+ if(true == g_serverState)
{
CAStartServer();
- gServerState = CA_FALSE;
+ g_serverState = false;
}
}
}
else
{
- gAdapterState = CA_FALSE;
+ g_adapterState = false;
}
// Notity to upper layer
- if (gNetworkChangeCallback && gLocalConnectivity && gEDRThreadPool)
+ if (g_networkChangeCallback && g_localConnectivity && g_edrThreadPool)
{
// Add notification task to thread pool
- CAEDRNetworkEvent *event = CAEDRCreateNetworkEvent(gLocalConnectivity, status);
+ CAEDRNetworkEvent *event = CAEDRCreateNetworkEvent(g_localConnectivity, status);
if (NULL != event)
{
- if (CA_STATUS_OK != u_thread_pool_add_task(gEDRThreadPool, CAEDROnNetworkStatusChanged,
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_edrThreadPool, CAEDROnNetworkStatusChanged,
event))
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to create threadpool!");
CAEDRNetworkEvent *networkEvent = (CAEDRNetworkEvent *) context;
// Notity to upper layer
- if (gNetworkChangeCallback)
+ if (g_networkChangeCallback)
{
- gNetworkChangeCallback(networkEvent->info, networkEvent->status);
+ g_networkChangeCallback(networkEvent->info, networkEvent->status);
}
// Free the created Network event
}
}
-CAEDRData *CACreateEDRData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+CAEDRData *CACreateEDRData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength)
{
CAEDRData *edrData = (CAEDRData *) OICMalloc(sizeof(CAEDRData));
}
edrData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
- edrData->data = (void *)OICMalloc(dataLength);
+ edrData->data = OICMalloc(dataLength);
if (NULL == edrData->data)
{
OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Memory allocation failed!");
CAFreeEDRData(edrdata);
}
+
#define TAG PCF("CA")
-static CANetworkPacketReceivedCallback gEDRReceivedCallback = NULL;
-static u_thread_pool_t gThreadPoolHandle = NULL;
+static CANetworkPacketReceivedCallback g_edrReceivedCallback = NULL;
+static u_thread_pool_t g_threadPoolHandle = NULL;
CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
- CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
- u_thread_pool_t handle)
+ CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
+ u_thread_pool_t handle)
{
OIC_LOG_V(DEBUG, TAG, "CAInitializeEDR");
- gEDRReceivedCallback = reqRespCallback;
- gThreadPoolHandle = handle;
+ g_edrReceivedCallback = reqRespCallback;
+ g_threadPoolHandle = handle;
// register handlers
CAConnectivityHandler_t handler;
handler.startAdapter = CAStartEDR;
handler.startListenServer = CAStartEDRListeningServer;
- handler.startDiscoverServer = CAStartEDRDiscoveryServer;
+ handler.startDiscoveryServer = CAStartEDRDiscoveryServer;
handler.sendData = CASendEDRUnicastData;
handler.sendDataToAll = CASendEDRMulticastData;
handler.GetnetInfo = CAGetEDRInterfaceInformation;
return CA_STATUS_OK;
}
-uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+int32_t CASendEDRUnicastData(const CARemoteEndpoint_t *endpoint, const void *data,
+ uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CASendEDRUnicastData");
- return 0;
+ return -1;
}
-uint32_t CASendEDRMulticastData(void *data, uint32_t dataLen)
+int32_t CASendEDRMulticastData(const void *data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CASendEDRMulticastData");
- return 0;
+ return -1;
}
CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
{
OIC_LOG_V(DEBUG, TAG, "CATerminateEDR");
}
+
#include "caedrdevicelist.h"
/**
- * @var gEDRDeviceListMutex
+ * @var g_edrDeviceListMutex
* @brief Mutex to synchronize the access to Bluetooth device information list.
*/
-static u_mutex gEDRDeviceListMutex = NULL;
+static u_mutex g_edrDeviceListMutex = NULL;
/**
- * @var gEDRDeviceList
+ * @var g_edrDeviceList
* @brief Peer Bluetooth device information list.
*/
-static EDRDeviceList *gEDRDeviceList = NULL;
+static EDRDeviceList *g_edrDeviceList = NULL;
/**
* @var gEDRNetworkChangeCallback
* @brief Maintains the callback to be notified when data received from remote Bluetooth device
*/
-static CAEDRDataReceivedCallback gEDRPacketReceivedCallback = NULL;
+static CAEDRDataReceivedCallback g_edrPacketReceivedCallback = NULL;
/**
* @fn CAEDRManagerInitializeMutex
* @fn CAEDRSocketConnectionStateCallback
* @brief This callback is registered to receive bluetooth RFCOMM connection state changes.
*/
-static void CAEDRSocketConnectionStateCallback(int result, bt_socket_connection_state_e state,
+static void CAEDRSocketConnectionStateCallback(int result,
+ bt_socket_connection_state_e state,
bt_socket_connection_s *connection, void *userData);
/**
void CAEDRSetPacketReceivedCallback(CAEDRDataReceivedCallback packetReceivedCallback)
{
- gEDRPacketReceivedCallback = packetReceivedCallback;
+ g_edrPacketReceivedCallback = packetReceivedCallback;
}
void CAEDRSocketConnectionStateCallback(int result, bt_socket_connection_state_e state,
{
case BT_SOCKET_CONNECTED:
{
- u_mutex_lock(gEDRDeviceListMutex);
- if (CA_STATUS_OK != CAGetEDRDevice(gEDRDeviceList, connection->remote_address,
- &device))
+ u_mutex_lock(g_edrDeviceListMutex);
+ CAResult_t res = CAGetEDRDevice(g_edrDeviceList, connection->remote_address,
+ &device);
+ if (CA_STATUS_OK != res)
{
// Create the deviceinfo and add to list
- if (CA_STATUS_OK != CACreateAndAddToDeviceList(&gEDRDeviceList,
- connection->remote_address, OIC_EDR_SERVICE_ID, &device))
+ res = CACreateAndAddToDeviceList(&g_edrDeviceList,
+ connection->remote_address, OIC_EDR_SERVICE_ID, &device);
+ if (CA_STATUS_OK != res)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed add device to list!");
- u_mutex_unlock(gEDRDeviceListMutex);
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed add device to list ret[%d]", res);
+ u_mutex_unlock(g_edrDeviceListMutex);
+ return;
+ }
+
+ if(!device)
+ {
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+ u_mutex_unlock(g_edrDeviceListMutex);
return;
}
device->socketFD = connection->socket_fd;
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
return;
}
+ if(!device)
+ {
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+ u_mutex_unlock(g_edrDeviceListMutex);
+ return;
+ }
device->socketFD = connection->socket_fd;
while (device->pendingDataList)
{
uint32_t sentData = 0;
EDRData *edrData = device->pendingDataList->data;
- if (CA_STATUS_OK != CAEDRSendData(device->socketFD, edrData->data,
- edrData->dataLength, &sentData))
+ res = CAEDRSendData(device->socketFD, edrData->data,
+ edrData->dataLength, &sentData);
+ if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to send pending data [%s]",
device->remoteAddress);
// Remove the data which send from pending list
CARemoveEDRDataFromList(&device->pendingDataList);
}
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
}
break;
case BT_SOCKET_DISCONNECTED:
{
- u_mutex_lock(gEDRDeviceListMutex);
- CARemoveEDRDeviceFromList(&gEDRDeviceList, connection->remote_address);
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_lock(g_edrDeviceListMutex);
+ CARemoveEDRDeviceFromList(&g_edrDeviceList, connection->remote_address);
+ u_mutex_unlock(g_edrDeviceListMutex);
}
break;
}
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Device discovered [%s]!",
discoveryInfo->remote_name);
- if (CA_TRUE == CAEDRIsServiceSupported((const char **)discoveryInfo->service_uuid,
+ if (true == CAEDRIsServiceSupported((const char **)discoveryInfo->service_uuid,
discoveryInfo->service_count,
OIC_EDR_SERVICE_ID))
{
// Check if the deivce is already in the list
- u_mutex_lock(gEDRDeviceListMutex);
- if (CA_STATUS_OK == CAGetEDRDevice(gEDRDeviceList, discoveryInfo->remote_address,
- &device))
+ u_mutex_lock(g_edrDeviceListMutex);
+ if (CA_STATUS_OK == CAGetEDRDevice(g_edrDeviceList,
+ discoveryInfo->remote_address, &device))
{
- device->serviceSearched = 1;
- u_mutex_unlock(gEDRDeviceListMutex);
+ if(!device)
+ {
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+ u_mutex_unlock(g_edrDeviceListMutex);
+ return;
+ }
+ device->serviceSearched = true;
+ u_mutex_unlock(g_edrDeviceListMutex);
return;
}
// Create the deviceinfo and add to list
- if (CA_STATUS_OK != CACreateAndAddToDeviceList(&gEDRDeviceList,
- discoveryInfo->remote_address, OIC_EDR_SERVICE_ID, &device))
+ CAResult_t res = CACreateAndAddToDeviceList(&g_edrDeviceList,
+ discoveryInfo->remote_address, OIC_EDR_SERVICE_ID, &device);
+ if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to add device to list!");
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
return;
}
- device->serviceSearched = 1;
- u_mutex_unlock(gEDRDeviceListMutex);
+ if(!device)
+ {
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+ u_mutex_unlock(g_edrDeviceListMutex);
+ return;
+ }
+ device->serviceSearched = true;
+ u_mutex_unlock(g_edrDeviceListMutex);
}
else
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
-void CAEDRServiceSearchedCallback(int32_t result, bt_device_sdp_info_s *sdpInfo, void *userData)
+void CAEDRServiceSearchedCallback(int32_t result,
+ bt_device_sdp_info_s *sdpInfo,void *userData)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
return;
}
- u_mutex_lock(gEDRDeviceListMutex);
+ u_mutex_lock(g_edrDeviceListMutex);
EDRDevice *device = NULL;
- if (CA_STATUS_OK == CAGetEDRDevice(gEDRDeviceList, sdpInfo->remote_address, &device)
- && NULL != device)
+ CAResult_t res = CAGetEDRDevice(g_edrDeviceList, sdpInfo->remote_address, &device);
+ if (CA_STATUS_OK == res && NULL != device)
{
- if (1 == device->serviceSearched)
+ if (device->serviceSearched)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Service is already searched for this device!");
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
return;
}
- if (CA_TRUE == CAEDRIsServiceSupported((const char **)sdpInfo->service_uuid,
+ if (true == CAEDRIsServiceSupported((const char **)sdpInfo->service_uuid,
sdpInfo->service_count, OIC_EDR_SERVICE_ID))
{
- device->serviceSearched = 1;
- if (CA_STATUS_OK != CAEDRClientConnect(sdpInfo->remote_address, OIC_EDR_SERVICE_ID))
+ device->serviceSearched = true;
+ res = CAEDRClientConnect(sdpInfo->remote_address, OIC_EDR_SERVICE_ID);
+ if (CA_STATUS_OK != res)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to make rfcomm connection!");
// Remove the device from device list
- CARemoveEDRDeviceFromList(&gEDRDeviceList, sdpInfo->remote_address);
+ CARemoveEDRDeviceFromList(&g_edrDeviceList, sdpInfo->remote_address);
}
}
else
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Device does not contain OIC service!");
// Remove device from list as it does not support OIC service
- CARemoveEDRDeviceFromList(&gEDRDeviceList, sdpInfo->remote_address);
+ CARemoveEDRDeviceFromList(&g_edrDeviceList, sdpInfo->remote_address);
}
}
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- bt_error_e err = BT_ERROR_NONE;
+
bool isDiscoveryStarted = false;
// Check the device discovery state
- if (BT_ERROR_NONE != (err = bt_adapter_is_discovering(&isDiscoveryStarted)))
+ bt_error_e err = bt_adapter_is_discovering(&isDiscoveryStarted);
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
err);
//Start device discovery if its not started
if (false == isDiscoveryStarted)
{
- if (BT_ERROR_NONE != (err = bt_adapter_start_device_discovery()))
+ err = bt_adapter_start_device_discovery();
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Device discovery failed!, error num [%x]",
err);
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- bt_error_e err = BT_ERROR_NONE;
-
+ bt_error_e err = bt_device_cancel_service_search();
// Stop ongoing service search
- if (BT_ERROR_NONE != (err = bt_device_cancel_service_search()))
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Get bonded device failed!, error num [%x]",
err);
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- bt_error_e err = BT_ERROR_NONE;
bool isDiscoveryStarted = false;
-
+ bt_error_e err = bt_adapter_is_discovering(&isDiscoveryStarted);
// Check the device discovery state
- if (BT_ERROR_NONE != (err = bt_adapter_is_discovering(&isDiscoveryStarted)))
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
err);
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- bt_error_e err = BT_ERROR_NONE;
-
// Input validation
VERIFY_NON_NULL(remoteAddress, EDR_ADAPTER_TAG, "Remote address is null");
- if (0 == strlen(remoteAddress))
+ if (!remoteAddress[0])
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Remote address is empty!");
return CA_STATUS_INVALID_PARAM;
}
+ bt_error_e err = bt_device_start_service_search(remoteAddress);
// Start searching for OIC service
- if (BT_ERROR_NONE != (err = bt_device_start_service_search(remoteAddress)))
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Get bonded device failed!, error num [%x]",
err);
bt_socket_set_data_received_cb(CAEDRDataRecvCallback, NULL);
// Start device discovery
- if( CA_STATUS_OK != CAEDRStartDeviceDiscovery())
+ CAResult_t result = CAEDRStartDeviceDiscovery();
+ if(CA_STATUS_OK != result)
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "Failed to Start Device discovery");
return CA_STATUS_FAILED;
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- u_mutex_init();
-
- if (!gEDRDeviceListMutex)
+ if (!g_edrDeviceListMutex)
{
- gEDRDeviceListMutex = u_mutex_new();
+ g_edrDeviceListMutex = u_mutex_new();
}
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- if (gEDRDeviceListMutex)
+ if (g_edrDeviceListMutex)
{
- u_mutex_free(gEDRDeviceListMutex);
- gEDRDeviceListMutex = NULL;
+ u_mutex_free(g_edrDeviceListMutex);
+ g_edrDeviceListMutex = NULL;
}
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
-void CAEDRTerminateClient()
+void CAEDRClientTerminate()
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
// Free EDRDevices list
- if (gEDRDeviceListMutex)
+ if (g_edrDeviceListMutex)
{
- u_mutex_lock(gEDRDeviceListMutex);
- CADestroyEDRDeviceList(&gEDRDeviceList);
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_lock(g_edrDeviceListMutex);
+ CADestroyEDRDeviceList(&g_edrDeviceList);
+ u_mutex_unlock(g_edrDeviceListMutex);
}
// Free the mutex
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- u_mutex_lock(gEDRDeviceListMutex);
+ u_mutex_lock(g_edrDeviceListMutex);
- EDRDeviceList *cur = gEDRDeviceList;
+ EDRDeviceList *cur = g_edrDeviceList;
while (cur != NULL)
{
EDRDevice *device = cur->device;
if (device && 0 <= device->socketFD)
{
- if (CA_STATUS_OK != CAEDRClientDisconnect(device->socketFD))
+ CAResult_t result = CAEDRClientDisconnect(device->socketFD);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to disconnect with client :%s",
device->remoteAddress);
}
}
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
CAResult_t CAEDRClientSendUnicastData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength)
+ const void *data, uint32_t dataLength, uint32_t *sentLength)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
}
// Check the connection existence with remote device
- u_mutex_lock(gEDRDeviceListMutex);
- if (CA_STATUS_OK != CAGetEDRDevice(gEDRDeviceList, remoteAddress, &device))
+ u_mutex_lock(g_edrDeviceListMutex);
+ CAResult_t result = CAGetEDRDevice(g_edrDeviceList, remoteAddress, &device);
+ if (CA_STATUS_OK != result)
{
// Create new device and add to list
- if (CA_STATUS_OK != CACreateAndAddToDeviceList(&gEDRDeviceList, remoteAddress,
- OIC_EDR_SERVICE_ID, &device))
+ result = CACreateAndAddToDeviceList(&g_edrDeviceList, remoteAddress,
+ OIC_EDR_SERVICE_ID, &device);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed create device and add to list!");
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
return CA_STATUS_FAILED;
}
// Start the OIC service search newly created device
- if (CA_STATUS_OK != CAEDRStartServiceSearch(remoteAddress))
+ result = CAEDRStartServiceSearch(remoteAddress);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to initiate service search!");
// Remove device from list
- CARemoveEDRDeviceFromList(&gEDRDeviceList, remoteAddress);
+ CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
return CA_STATUS_FAILED;
}
}
- u_mutex_unlock(gEDRDeviceListMutex);
+
+ if(!device)
+ {
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "EDRDevice is null!");
+ // Remove device from list
+ CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
+
+ u_mutex_unlock(g_edrDeviceListMutex);
+ return CA_STATUS_FAILED;
+ }
+
+ u_mutex_unlock(g_edrDeviceListMutex);
if (-1 == device->socketFD)
{
// Adding to pending list
- if (CA_STATUS_OK != CAAddEDRDataToList(&device->pendingDataList, data,
- dataLength))
+ result = CAAddEDRDataToList(&device->pendingDataList, data,
+ dataLength);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to add data to pending list!");
//Remove device from list
- CARemoveEDRDeviceFromList(&gEDRDeviceList, remoteAddress);
+ CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
return CA_STATUS_FAILED;
}
// Make a rfcomm connection with remote BT Device
- if (1 == device->serviceSearched &&
+ if (device->serviceSearched &&
CA_STATUS_OK != CAEDRClientConnect(remoteAddress, serviceUUID))
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to make RFCOMM connection!");
//Remove device from list
- CARemoveEDRDeviceFromList(&gEDRDeviceList, remoteAddress);
+ CARemoveEDRDeviceFromList(&g_edrDeviceList, remoteAddress);
return CA_STATUS_FAILED;
}
*sentLength = dataLength;
}
else
{
- if (CA_STATUS_OK != CAEDRSendData(device->socketFD, data, dataLength, sentLength))
+ result = CAEDRSendData(device->socketFD, data, dataLength, sentLength);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to send data!");
return CA_STATUS_FAILED;
return CA_STATUS_OK;
}
-CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, void *data,
+CAResult_t CAEDRClientSendMulticastData(const char *serviceUUID, const void *data,
uint32_t dataLength, uint32_t *sentLength)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
*sentLength = dataLength;
// Send the packet to all OIC devices
- u_mutex_lock(gEDRDeviceListMutex);
- EDRDeviceList *curList = gEDRDeviceList;
+ u_mutex_lock(g_edrDeviceListMutex);
+ EDRDeviceList *curList = g_edrDeviceList;
+ CAResult_t result = CA_STATUS_FAILED;
while (curList != NULL)
{
EDRDevice *device = curList->device;
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN1");
// Check if the device service search is finished
- if (0 == device->serviceSearched)
+ if (false == device->serviceSearched)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Device services are still unknown!");
continue;
}
// Adding to pendding list
- if (CA_STATUS_OK != CAAddEDRDataToList(&device->pendingDataList, data,
- dataLength))
+ result = CAAddEDRDataToList(&device->pendingDataList, data,
+ dataLength);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to add data to pending list !");
continue;
}
// Make a rfcomm connection with remote BT Device
- if (CA_STATUS_OK != CAEDRClientConnect(device->remoteAddress, device->serviceUUID))
+ result = CAEDRClientConnect(device->remoteAddress, device->serviceUUID);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to make RFCOMM connection !");
else
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN3");
- if (CA_STATUS_OK != CAEDRSendData(device->socketFD, data, dataLength, sentLength))
+ result = CAEDRSendData(device->socketFD, data, dataLength, sentLength);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to send data to [%s] !",
device->remoteAddress);
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN4");
}
}
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- bt_error_e err = BT_ERROR_NONE;
- int32_t addressLen = 0;
-
VERIFY_NON_NULL(remoteAddress, EDR_ADAPTER_TAG, "Remote address is null");
VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "Service UUID is null");
- addressLen = strlen(remoteAddress);
+ size_t addressLen = strlen(remoteAddress);
if (0 == addressLen || CA_MACADDR_SIZE - 1 != addressLen)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid input: Invalid remote address");
return CA_STATUS_INVALID_PARAM;
}
- if (0 == strlen(serviceUUID))
+ if (!serviceUUID[0])
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid input: Empty service uuid");
return CA_STATUS_INVALID_PARAM;
}
- if (BT_ERROR_NONE != (err = bt_socket_connect_rfcomm(remoteAddress, serviceUUID)))
+ bt_error_e err = bt_socket_connect_rfcomm(remoteAddress, serviceUUID);
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
"Failed to connect!, address [%s] error num [%x]",
return CA_STATUS_INVALID_PARAM;
}
- bt_error_e err = BT_ERROR_NONE;
- if (BT_ERROR_NONE != (err = bt_socket_disconnect_rfcomm(clientID)))
+ bt_error_e err = bt_socket_disconnect_rfcomm(clientID);
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed close rfcomm client socket!, error num [%x]",
err);
}
// Get EDR device from list
- u_mutex_lock(gEDRDeviceListMutex);
- if (CA_STATUS_OK != CAGetEDRDeviceBySocketId(gEDRDeviceList, data->socket_fd, &device))
+ u_mutex_lock(g_edrDeviceListMutex);
+ CAResult_t result = CAGetEDRDeviceBySocketId(g_edrDeviceList, data->socket_fd, &device);
+ if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Could not find the device!");
- u_mutex_unlock(gEDRDeviceListMutex);
+ u_mutex_unlock(g_edrDeviceListMutex);
+ return;
+ }
+ u_mutex_unlock(g_edrDeviceListMutex);
+
+ if (!device)
+ {
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "There is no device!");
return;
}
- u_mutex_unlock(gEDRDeviceListMutex);
uint32_t sentLength = 0;
- gEDRPacketReceivedCallback(device->remoteAddress, data->data,
+ g_edrPacketReceivedCallback(device->remoteAddress, data->data,
(uint32_t)data->data_size, &sentLength);
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
+
******************************************************************/
/**
- * @file cabtdevicelist.c
+ * @file caedrdevicelist.c
* @brief This file provides APIs to access the discovered bluetooth device list
*/
* @brief Creates #EDRDevice for specified remote address and uuid.
*
*/
-static CAResult_t CACreateEDRDevice(const char *deviceAddress, const char *uuid, EDRDevice **device);
+static CAResult_t CACreateEDRDevice(const char *deviceAddress,
+ const char *uuid,EDRDevice **device);
/**
CAResult_t CACreateAndAddToDeviceList(EDRDeviceList **deviceList, const char *deviceAddress,
const char *uuid, EDRDevice **device)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
VERIFY_NON_NULL(deviceAddress, EDR_ADAPTER_TAG, "Remote address is null");
VERIFY_NON_NULL(device, EDR_ADAPTER_TAG, "Device is null");
-
- if (CA_STATUS_OK != CACreateEDRDevice(deviceAddress, uuid, device) || NULL == *device)
+ CAResult_t result = CACreateEDRDevice(deviceAddress, uuid, device);
+ if (CA_STATUS_OK != result || NULL == *device)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid or Not bonded device!");
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid or Not bonded device ret[%d]", result);
return CA_STATUS_FAILED;
}
-
- if (CA_STATUS_OK != CAAddEDRDeviceToList(deviceList, *device))
+ result = CAAddEDRDeviceToList(deviceList, *device);
+ if (CA_STATUS_OK != result)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to add in list!");
+ OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to add in list ret[%d]", result);
//Remove created EDRDevice
CADestroyEDRDevice(*device);
return CA_STATUS_FAILED;
}
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CACreateEDRDevice(const char *deviceAddress, const char *uuid, EDRDevice **device)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
VERIFY_NON_NULL(deviceAddress, EDR_ADAPTER_TAG, "Remote address is null");
VERIFY_NON_NULL(uuid, EDR_ADAPTER_TAG, "uuid is null");
}
//Copy bluetooth address
- if (strlen(deviceAddress))
+ if (deviceAddress[0])
{
(*device)->remoteAddress = strndup(deviceAddress, strlen(deviceAddress));
if (NULL == (*device)->remoteAddress)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Out of memory (remote address)!");
+ OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Out of memory (remote address)!");
OICFree(*device);
*device = NULL;
(*device)->socketFD = -1;
(*device)->pendingDataList = NULL;
- (*device)->serviceSearched = 0;
+ (*device)->serviceSearched = false;
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAAddEDRDeviceToList(EDRDeviceList **deviceList, EDRDevice *device)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
VERIFY_NON_NULL(device, EDR_ADAPTER_TAG, "Device is null");
*deviceList = node;
}
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
-CAResult_t CAGetEDRDevice(EDRDeviceList *deviceList, const char *deviceAddress, EDRDevice **device)
+CAResult_t CAGetEDRDevice(EDRDeviceList *deviceList,
+ const char *deviceAddress, EDRDevice **device)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
VERIFY_NON_NULL(deviceAddress, EDR_ADAPTER_TAG, "Remote address is null");
curNode = curNode->next;
}
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT [Device not found!]");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT [Device not found!]");
return CA_STATUS_FAILED;
}
-CAResult_t CAGetEDRDeviceBySocketId(EDRDeviceList *deviceList, int32_t socketID, EDRDevice **device)
+CAResult_t CAGetEDRDeviceBySocketId(EDRDeviceList *deviceList,
+ int32_t socketID, EDRDevice **device)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
VERIFY_NON_NULL(device, EDR_ADAPTER_TAG, "Device is null");
curNode = curNode->next;
}
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_STATUS_FAILED;
}
-CAResult_t CARemoveEDRDeviceFromList(EDRDeviceList **deviceList, const char *deviceAddress)
+CAResult_t CARemoveEDRDeviceFromList(EDRDeviceList **deviceList,
+ const char *deviceAddress)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
VERIFY_NON_NULL(deviceList, EDR_ADAPTER_TAG, "Device list is null");
VERIFY_NON_NULL(deviceAddress, EDR_ADAPTER_TAG, "Remote address is null");
}
}
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Device not in the list !");
+ OIC_LOG(ERROR, EDR_ADAPTER_TAG, "OUT Device not in the list !");
return CA_STATUS_FAILED;
}
void CADestroyEDRDeviceList(EDRDeviceList **deviceList)
{
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+ VERIFY_NON_NULL_VOID(deviceList, EDR_ADAPTER_TAG, "deviceList is null");
+
while (*deviceList)
{
EDRDeviceList *curNode = *deviceList;
CADestroyEDRDevice(curNode->device);
OICFree(curNode);
}
+
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
void CADestroyEDRDevice(EDRDevice *device)
{
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
if (device)
{
OICFree(device->remoteAddress);
CADestroyEDRDataList(&device->pendingDataList);
OICFree(device);
}
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
}
-CAResult_t CAAddEDRDataToList(EDRDataList **dataList, void *data, uint32_t dataLength)
+CAResult_t CAAddEDRDataToList(EDRDataList **dataList, const void *data, uint32_t dataLength)
{
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
VERIFY_NON_NULL(dataList, EDR_ADAPTER_TAG, "Data list is null");
VERIFY_NON_NULL(data, EDR_ADAPTER_TAG, "Data is null");
if (0 == dataLength)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
+ OIC_LOG(ERROR, EDR_ADAPTER_TAG, "Invalid input: data length is zero!");
return CA_STATUS_INVALID_PARAM;
}
EDRDataList *pending_data = (EDRDataList *) OICMalloc(sizeof(EDRDataList));
if (NULL == pending_data)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data list)!");
+ OIC_LOG(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data list)!");
return CA_MEMORY_ALLOC_FAILED;
}
pending_data->data = (EDRData *) OICMalloc(sizeof(EDRData));
if (NULL == pending_data->data)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data node)!");
+ OIC_LOG(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data node)!");
OICFree(pending_data);
return CA_MEMORY_ALLOC_FAILED;
pending_data->data->data = (void *) OICMalloc(dataLength); //data
if (NULL == pending_data->data->data)
{
- OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data)!");
+ OIC_LOG(ERROR, EDR_ADAPTER_TAG, "OICMalloc failed (data)!");
OICFree(pending_data->data);
OICFree(pending_data);
curNode->next = pending_data;
}
- OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
+ VERIFY_NON_NULL_VOID(dataList, EDR_ADAPTER_TAG, "Data list is null");
+
while (*dataList)
{
EDRDataList *curNode = *dataList;
{
char *remoteAddress; /**< Address of peer Bluetooth device. */
char *serviceUUID; /**< OIC service UUID running in peer Bluetooth device. */
- int32_t socketFD; /**< RfComm connection socket FD. */
+ int socketFD; /**< RfComm connection socket FD. */
EDRDataList *pendingDataList;/**< List of data needs to send to peer Bluetooth device. */
- uint32_t serviceSearched; /**< Flag to indicate the status of service search. */
+ bool serviceSearched; /**< Flag to indicate the status of service search. */
} EDRDevice;
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
* @retval #CA_STATUS_FAILED Device is not found in the list
*/
-CAResult_t CAGetEDRDevice(EDRDeviceList *deviceList, const char *deviceAddress, EDRDevice **device);
+CAResult_t CAGetEDRDevice(EDRDeviceList *deviceList,
+ const char *deviceAddress, EDRDevice **device);
/**
* @brief Get the device from list which matches specified RFCOMM socket id.
* @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
* @retval #CA_STATUS_FAILED Device is not found in the list
*/
-CAResult_t CARemoveEDRDeviceFromList(EDRDeviceList **deviceList, const char *deviceAddress);
+CAResult_t CARemoveEDRDeviceFromList(EDRDeviceList **deviceList,
+ const char *deviceAddress);
/**
* @brief Destroy the specified device list. Removes and delete all the devices in the list.
* @retval #CA_STATUS_INVALID_PARAM Invalid input parameters
* @retval #CA_MEMORY_ALLOC_FAILED Memory allocation failed
*/
-CAResult_t CAAddEDRDataToList(EDRDataList **dataList, void *data, uint32_t dataLength);
+CAResult_t CAAddEDRDataToList(EDRDataList **dataList, const void *data, uint32_t dataLength);
/**
* @brief Remove and delete data from front end of list.
} /* extern "C" */
#endif
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
#endif //__CA_EDR_DEVICE_LIST_H_
+
******************************************************************/
/**
- * @file cabtendpoint.c
+ * @file caedrendpoint.c
* @brief This file provides the APIs to send data on established RFCOMM connections.
*/
#include "caedrutils.h"
#include "logger.h"
-CAResult_t CAEDRSendData(const int32_t serverFD, const void *data, const uint32_t dataLength,
+CAResult_t CAEDRSendData(int serverFD, const void *data, uint32_t dataLength,
uint32_t *sentDataLen)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
return CA_STATUS_INVALID_PARAM;
}
- int32_t dataLen = 0;
- dataLen = bt_socket_send_data(serverFD, (const char *)data, dataLength);
+ int dataLen = bt_socket_send_data(serverFD, (const char *)data, dataLength);
if (dataLen == -1)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "sending data failed!, soketid [%d]", serverFD);
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
+
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAEDRSendData(const int32_t serverFD, const void *data, const uint32_t dataLength,
+CAResult_t CAEDRSendData(int serverFD, const void *data, uint32_t dataLength,
uint32_t *sentDataLength);
#ifdef __cplusplus
#endif //__CA_EDR_ENDPOINT_H_
+
#include "caqueueingthread.h"
/**
- * @var gEDRNetworkChangeCallback
+ * @var g_edrNetworkChangeCallback
* @brief Maintains the callback to be notified on local bluetooth adapter status change.
*/
-static CAEDRNetworkStatusCallback gEDRNetworkChangeCallback = NULL;
+static CAEDRNetworkStatusCallback g_edrNetworkChangeCallback = NULL;
/**
* @fn CAEDRAdapterStateChangeCallback
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
// Initialize Bluetooth service
- int32_t err = bt_initialize();
-
+ int err = bt_initialize();
if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth initialization failed!, error num [%x]",
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- gEDRNetworkChangeCallback = NULL;
+ g_edrNetworkChangeCallback = NULL;
// Terminate Bluetooth service
bt_deinitialize();
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- int32_t ret = bt_adapter_set_state_changed_cb(CAEDRAdapterStateChangeCallback, NULL);
+ int ret = bt_adapter_set_state_changed_cb(CAEDRAdapterStateChangeCallback, NULL);
if(BT_ERROR_NONE != ret)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "bt_adapter_set_state_changed_cb failed");
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
// Unset bluetooth adapter callbacks
- int32_t ret = bt_adapter_unset_state_changed_cb();
+ int ret = bt_adapter_unset_state_changed_cb();
if(BT_ERROR_NONE != ret)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "bt_adapter_set_state_changed_cb failed");
void CAEDRSetNetworkChangeCallback(
CAEDRNetworkStatusCallback networkChangeCallback)
{
- gEDRNetworkChangeCallback = networkChangeCallback;
+ g_edrNetworkChangeCallback = networkChangeCallback;
}
CAResult_t CAEDRGetInterfaceInformation(CALocalConnectivity_t **info)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- int32_t err = BT_ERROR_NONE;
- char *localAddress = NULL;
-
// Input validation
VERIFY_NON_NULL(info, EDR_ADAPTER_TAG, "LocalConnectivity info is null");
// Get the bluetooth adapter local address
- if (BT_ERROR_NONE != (err = bt_adapter_get_address(&localAddress)))
+ char *localAddress = NULL;
+ int err = bt_adapter_get_address(&localAddress);
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG,
"Getting local adapter address failed!, error num [%x]",
return CA_STATUS_OK;
}
-CAResult_t CAEDRGetAdapterEnableState(CABool_t *state)
+CAResult_t CAEDRGetAdapterEnableState(bool *state)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
// Input validation
VERIFY_NON_NULL(state, EDR_ADAPTER_TAG, "state holder is NULL!");
- bt_error_e err = BT_ERROR_NONE;
- bt_adapter_state_e adapterState;
+ bt_adapter_state_e adapterState;
+ int err = bt_adapter_get_state(&adapterState);
// Get Bluetooth adapter state
- if (BT_ERROR_NONE != (err = bt_adapter_get_state(&adapterState)))
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Bluetooth get state failed!, error num [%x]",
err);
return CA_STATUS_FAILED;
}
- *state = CA_FALSE;
+ *state = false;
if (BT_ADAPTER_ENABLED == adapterState)
{
- *state = CA_TRUE;
+ *state = true;
}
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
if (BT_ADAPTER_ENABLED == adapterState)
{
// Notity to upper layer
- if (gEDRNetworkChangeCallback)
+ if (g_edrNetworkChangeCallback)
{
- gEDRNetworkChangeCallback(CA_INTERFACE_UP);
+ g_edrNetworkChangeCallback(CA_INTERFACE_UP);
}
}
else if (BT_ADAPTER_DISABLED == adapterState)
{
// Notity to upper layer
- if (gEDRNetworkChangeCallback)
+ if (g_edrNetworkChangeCallback)
{
- gEDRNetworkChangeCallback(CA_INTERFACE_DOWN);
+ g_edrNetworkChangeCallback(CA_INTERFACE_DOWN);
}
}
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
-}
\ No newline at end of file
+}
******************************************************************/
/**
- * @file cabtserver.c
- * @brief This file provides the APIs to start and stop RFCOMM server.
+ * @file caedrserver.c
+ * @brief This file provides the APIs to start and stop RFCOMM server.
*/
#include "cacommon.h"
#include "caedrdevicelist.h"
-static int32_t gMaxPendingConnections = 10;
+static int32_t g_maxPendingConnections = 10;
-CAResult_t CAEDRServerStart(const char *serviceUUID, int32_t *serverFD, u_thread_pool_t handle)
+CAResult_t CAEDRServerStart(const char *serviceUUID, int *serverFD, u_thread_pool_t handle)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- bt_error_e err = BT_ERROR_NONE;
- bool isRunning = false;
- int32_t socketFD;
-
VERIFY_NON_NULL(serviceUUID, EDR_ADAPTER_TAG, "Service UUID is null");
VERIFY_NON_NULL(serverFD, EDR_ADAPTER_TAG, "Server fd holder is null");
- if (0 >= strlen(serviceUUID))
+ if (!serviceUUID[0])
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Invalid input: Empty service uuid!");
return CA_STATUS_INVALID_PARAM;
}
- if (BT_ERROR_NONE != bt_adapter_is_service_used(serviceUUID, &isRunning))
+ bool isRunning = false;
+ bt_error_e err = bt_adapter_is_service_used(serviceUUID, &isRunning);
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG,
- "Unable to find whether service is already running or not!");
+ "Unable to find whether service is already running or not! erorr num[%x]", err);
return CA_STATUS_FAILED;
}
- if (true == isRunning)
+ if (isRunning)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Service is already running with this UUID!");
return CA_SERVER_STARTED_ALREADY;
}
- // Registers a rfcomm socket with a specific service_uuid .
- if (BT_ERROR_NONE != (err = bt_socket_create_rfcomm(serviceUUID, &socketFD)))
+ int socketFD = 0;
+ // Registers a rfcomm socket with a specific service_uuid.
+ err = bt_socket_create_rfcomm(serviceUUID, &socketFD);
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed to create rfcomm socket!, error num [%x]",
err);
}
// Start listening and accepting
- if (BT_ERROR_NONE != (err = bt_socket_listen_and_accept_rfcomm(socketFD,
- gMaxPendingConnections)))
+ err = bt_socket_listen_and_accept_rfcomm(socketFD,
+ g_maxPendingConnections);
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed in listen rfcomm socket!, error num [%x]",
err);
return CA_STATUS_OK;
}
-CAResult_t CAEDRServerStop(const int32_t serverFD)
+CAResult_t CAEDRServerStop(int serverFD)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
- bt_error_e err = BT_ERROR_NONE;
- if (BT_ERROR_NONE != (err = bt_socket_destroy_rfcomm(serverFD)))
+ bt_error_e err = bt_socket_destroy_rfcomm(serverFD);
+ if (BT_ERROR_NONE != err)
{
OIC_LOG_V(ERROR, EDR_ADAPTER_TAG, "Failed close server socket!, error num [%x]",
err);
return CA_STATUS_OK;
}
+void CAEDRServerTerminate()
+{
+ // This is just a dummy
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "CAEDRServerTerminate");
+}
+
CAResult_t CAEDRManagerReadData(void)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
return CA_NOT_SUPPORTED;
}
+
******************************************************************/
/**
- * @file cabtutils.c
+ * @file caedrutils.c
* @brief This file provides helper functions for EDR adapter.
*/
#include "caedrutils.h"
-#include "logger.h"
#include <bluetooth.h>
-CABool_t CAEDRIsServiceSupported(const char **serviceUUID, const int32_t serviceCount,
+#include "logger.h"
+
+bool CAEDRIsServiceSupported(const char **serviceUUID, int32_t serviceCount,
const char *matchService)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "IN");
if (NULL == serviceUUID || 0 == serviceCount || NULL == matchService)
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Invalid input");
- return CA_FALSE;
+ return false;
}
for (int i = 0; i < serviceCount; i++)
if (!strcasecmp(serviceUUID[i], matchService))
{
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "Service found !");
- return CA_TRUE;
+ return true;
}
}
OIC_LOG_V(DEBUG, EDR_ADAPTER_TAG, "OUT");
- return CA_FALSE;
+ return false;
}
+
* @param serviceCount [IN] Size of the service UUIDs array.
* @param matchService [IN] Service UUID to be checked in the given array of service UUIDs
*
- * @return CA_TRUE if match service UUID found otherwise CA_FALSE.
+ * @return true if match service UUID found otherwise false.
*
*/
-CABool_t CAEDRIsServiceSupported(const char **serviceUUID, const int32_t serviceCount,
+bool CAEDRIsServiceSupported(const char **serviceUUID, int32_t serviceCount,
const char *matchService);
#ifdef __cplusplus
#endif //__CA_EDR_UTILS_H_
+
if target_os == 'tizen':
env.PrependUnique(CPPPATH = [src_dir + 'tizen'])
env.PrependUnique(CFLAGS = ['-I'+ './con/lib/tizen/ble/inc'])
+ env.PrependUnique(CFLAGS = ['-I'+ './con/lib/tizen/ble/inc/mobile'])
env.AppendUnique(CA_SRC=[src_dir+'tizen/cableclient.c',
src_dir+'tizen/cableserver.c',
src_dir+'tizen/cableutil.c',
#include "caleadapter.h"
#include "calecore.h"
#include "caleserver.h"
+#include "calenwmonitor.h"
#include "logger.h"
#include "caadapterutils.h"
+#include "oic_malloc.h"
#define TAG PCF("CA_LE_ADAPTER")
// GATT server type
-static jboolean gIsBluetoothGattServer;
+static jboolean g_isBluetoothGattServer;
// received packet callback
static CANetworkPacketReceivedCallback gLEReceivedCallback = NULL;
if (endpoint == NULL)
{
OIC_LOG(DEBUG, TAG, "CALEPacketReceiveCallback, Memory allocation failed !");
- OICFree((char*)address);
return;
}
{
strcpy((char*) endpoint->addressInfo.BT.btMacAddress, address);
}
- OICFree((char*)address);
// set connectivity type
endpoint->connectivityType = CA_LE;
if (gLENetworkChangeCallback != NULL)
{
CANetworkStatus_t netStatus = CA_INTERFACE_DOWN;
- if(status == 12)
+ if (status == 12)
{
netStatus = CA_INTERFACE_UP;
}
- else if(status == 10)
+ else if (status == 10)
{
netStatus = CA_INTERFACE_DOWN;
}
}
CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
- CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
- u_thread_pool_t handle)
+ CANetworkPacketReceivedCallback reqRespCallback,
+ CANetworkChangeCallback netCallback, u_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "IntializeBLE");
handler.startAdapter = CAStartLE;
handler.startListenServer = CAStartLEListeningServer;
- handler.startDiscoverServer = CAStartLEDiscoveryServer;
+ handler.startDiscoveryServer = CAStartLEDiscoveryServer;
handler.sendData = CASendLEUnicastData;
handler.sendDataToAll = CASendLEMulticastData;
handler.GetnetInfo = CAGetLEInterfaceInformation;
{
OIC_LOG_V(DEBUG, TAG, "CAStartLEListeningServer");
- gIsBluetoothGattServer = JNI_TRUE;
+ g_isBluetoothGattServer = JNI_TRUE;
// start gatt service
CALEServerStartMulticastServer();
{
OIC_LOG_V(DEBUG, TAG, "CAStartLEDiscoveryServer");
- gIsBluetoothGattServer = JNI_FALSE;
+ g_isBluetoothGattServer = JNI_FALSE;
// start scan through gatt client
CALEStartMulticastServer();
return CA_STATUS_OK;
}
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t* endpoint, const void* data, uint32_t dataLen)
{
- if(gIsBluetoothGattServer == JNI_FALSE)
+ if (g_isBluetoothGattServer == JNI_FALSE)
{
OIC_LOG_V(DEBUG, TAG, "CALESendUnicastData");
CALESendUnicastMessage(endpoint->addressInfo.BT.btMacAddress, data, dataLen);
}
- else if(gIsBluetoothGattServer == JNI_TRUE)
+ else
{
OIC_LOG_V(DEBUG, TAG, "CALEServerSendUnicastData");
CALEServerSendUnicastMessage(endpoint->addressInfo.BT.btMacAddress, data, dataLen);
}
- return 0;
+ return dataLen;
}
-uint32_t CASendLEMulticastData(void* data, uint32_t dataLen)
+int32_t CASendLEMulticastData(const void* data, uint32_t dataLen)
{
- if(gIsBluetoothGattServer == JNI_FALSE)
+ if (g_isBluetoothGattServer == JNI_FALSE)
{
OIC_LOG_V(DEBUG, TAG, "CASendLEMulticastData");
CALESendMulticastMessage(data, dataLen);
}
- else if(gIsBluetoothGattServer == JNI_TRUE)
+ else
{
OIC_LOG_V(DEBUG, TAG, "CALEServerSendMulticastMessage");
CALEServerSendMulticastMessage(data, dataLen);
}
- return 0;
+ return dataLen;
}
CAResult_t CAStartLENotifyServer()
return CA_STATUS_OK;
}
-uint32_t CASendLENotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
+uint32_t CASendLENotification(const CARemoteEndpoint_t* endpoint, const void* data,
+ uint32_t dataLen)
{
- if(gIsBluetoothGattServer == JNI_FALSE)
+ if (g_isBluetoothGattServer == JNI_FALSE)
{
OIC_LOG_V(DEBUG, TAG, "not server mode");
return -1;
}
- else if(gIsBluetoothGattServer == JNI_TRUE)
+ else
{
OIC_LOG_V(DEBUG, TAG, "CALEServerSendLEUnicastData");
CALEServerSendUnicastMessage(endpoint->addressInfo.BT.btMacAddress, data, dataLen);
int32_t netInfoSize = 1;
netInfo = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t) * netInfoSize);
- if(NULL == netInfo)
+ if (NULL == netInfo)
{
OIC_LOG_V(ERROR, TAG, "Invalid input..");
return CA_MEMORY_ALLOC_FAILED;
if (NULL == endpoint)
{
OIC_LOG_V(ERROR, TAG, "Failed to create Local Endpoint!",
- CA_MEMORY_ALLOC_FAILED);
+ CA_MEMORY_ALLOC_FAILED);
OICFree(netInfo);
OICFree(macAddress);
return CA_MEMORY_ALLOC_FAILED;
}
// copy unciast server information
- endpoint->isSecured = CA_FALSE;
+ endpoint->isSecured = false;
memcpy(&netInfo[0], endpoint, sizeof(CALocalConnectivity_t));
*size = 1;
*info = netInfo;
CAResult_t CAStopLE()
{
- if(gIsBluetoothGattServer == JNI_FALSE)
+ if (g_isBluetoothGattServer == JNI_FALSE)
{
OIC_LOG_V(DEBUG, TAG, "CA Stop LE Scan");
CANativeLEStopScan();
}
- else if(gIsBluetoothGattServer == JNI_TRUE)
+ else
{
OIC_LOG_V(DEBUG, TAG, "CA Stop Gatt Server");
}
void CATerminateLE()
{
- if(gIsBluetoothGattServer == JNI_FALSE)
+ if (g_isBluetoothGattServer == JNI_FALSE)
{
OIC_LOG_V(DEBUG, TAG, "Terminat Gatt Client");
CALETerminate();
}
- else if(gIsBluetoothGattServer == JNI_TRUE)
+ else
{
OIC_LOG_V(DEBUG, TAG, "Terminat Gatt Server");
CALEServerTerminate();
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
#include <stdio.h>
#include <string.h>
#include <jni.h>
+#include <unistd.h>
#include "calecore.h"
#include "caleserver.h"
#include "uthreadpool.h" /* for thread pool */
#include "umutex.h"
#include "uarraylist.h"
-#include "com_iotivity_jar_CALeInterface.h"
+#include "com_iotivity_jar_caleinterface.h"
//#define DEBUG_MODE
#define TAG PCF("CA_LE_CLIENT")
-static const char *METHODID_OBJECTNONPARAM = "()Landroid/bluetooth/BluetoothAdapter;";
-static const char *METHODID_STRINGNONPARAM = "()Ljava/lang/String;";
-static const char *CLASSPATH_BT_ADPATER = "android/bluetooth/BluetoothAdapter";
-static const char *CLASSPATH_BT_UUID = "java/util/UUID";
-static const char *CLASSPATH_BT_GATT = "android/bluetooth/BluetoothGatt";
+static const char METHODID_OBJECTNONPARAM[] = "()Landroid/bluetooth/BluetoothAdapter;";
+static const char METHODID_STRINGNONPARAM[] = "()Ljava/lang/String;";
+static const char CLASSPATH_BT_ADPATER[] = "android/bluetooth/BluetoothAdapter";
+static const char CLASSPATH_BT_UUID[] = "java/util/UUID";
+static const char CLASSPATH_BT_GATT[] = "android/bluetooth/BluetoothGatt";
-static const char *IOTIVITY_GATT_SERVIE_UUID = "713d0000-503e-4c75-ba94-3148f18d941e";
-static const char *IOTIVITY_GATT_TX_UUID = "713d0003-503e-4c75-ba94-3148f18d941e";
-static const char *IOTIVITY_GATT_RX_UUID = "713d0002-503e-4c75-ba94-3148f18d941e";
+static const char IOTIVITY_GATT_SERVIE_UUID[] = "713d0000-503e-4c75-ba94-3148f18d941e";
+static const char IOTIVITY_GATT_TX_UUID[] = "713d0003-503e-4c75-ba94-3148f18d941e";
+static const char IOTIVITY_GATT_RX_UUID[] = "713d0002-503e-4c75-ba94-3148f18d941e";
static const uint32_t STATE_CONNECTED = 2;
static const uint32_t STATE_DISCONNECTED = 0;
static const uint32_t GATT_SUCCESS = 0;
-static const uint32_t MAX_PDU_BUFFER = 1400;
+static const size_t MAX_PDU_BUFFER = 1400;
JavaVM *g_jvm;
-static u_arraylist_t *gdeviceList = NULL;
-static u_arraylist_t *gGattObjectList = NULL;
-static CAPacketReceiveCallback gPacketReceiveCallback = NULL;
-static u_thread_pool_t gThreadPoolHandle = NULL;
-static jobject gLeScanCallback;
-static jobject gLeGattCallback;
-static jobject gContext;
-static jobjectArray gUUIDList;
-static jboolean gIsStartServer;
-static jboolean gIsFinishSendData;
-
-static jbyteArray gSendBuffer;
-static uint32_t gTargetCnt = 0;
-static uint32_t gCurrentSentCnt = 0;
+static u_arraylist_t *g_deviceList = NULL;
+static u_arraylist_t *g_gattObjectList = NULL;
+static CAPacketReceiveCallback g_packetReceiveCallback = NULL;
+static u_thread_pool_t g_threadPoolHandle = NULL;
+static jobject g_leScanCallback;
+static jobject g_leGattCallback;
+static jobject g_context;
+static jobjectArray g_UUIDList;
+static jboolean g_isStartServer;
+static jboolean g_isFinishSendData;
+
+static jbyteArray g_sendBuffer;
+static uint32_t g_targetCnt = 0;
+static uint32_t g_currentSentCnt = 0;
/** mutex for synchrnoization **/
-static u_mutex gThreadMutex;
+static u_mutex g_threadMutex;
/** conditional mutex for synchrnoization **/
-static u_cond gThreadCond;
+static u_cond g_threadCond;
-////////////////////////////////////////////////////////////////////////////////////////////////////
+///////////////////////////////////////////////////////////////////////////////////////////////////
//FIXME getting context
void CALEClientJNISetContext(JNIEnv *env, jobject context)
{
OIC_LOG_V(DEBUG, TAG, "CALEClientJNISetContext");
- if(context == NULL)
+ if (context == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "context is null");
+ OIC_LOG_V(ERROR, TAG, "context is null");
return;
}
- gContext = (*env)->NewGlobalRef(env, context);
+ g_context = (*env)->NewGlobalRef(env, context);
}
void CALeCreateJniInterfaceObject()
{
OIC_LOG_V(DEBUG, TAG, "CALeCreateJniInterfaceObject");
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
jclass LeJniInterface = (*env)->FindClass(env, "com/iotivity/jar/CALeInterface");
return;
}
- jmethodID LeInterfaceConstructorMethod =
- (*env)->GetMethodID(env, LeJniInterface, "<init>", "(Landroid/content/Context;)V");
+ jmethodID LeInterfaceConstructorMethod = (*env)->GetMethodID(env, LeJniInterface, "<init>",
+ "(Landroid/content/Context;)V");
if (!LeInterfaceConstructorMethod)
{
OIC_LOG_V(DEBUG, TAG, "Could not get CALeInterface constructor method");
return;
}
- (*env)->NewObject(env, LeJniInterface, LeInterfaceConstructorMethod, gContext);
+ (*env)->NewObject(env, LeJniInterface, LeInterfaceConstructorMethod, g_context);
OIC_LOG_V(DEBUG, TAG, "Create CALeInterface instance");
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
}
JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
OIC_LOG_V(DEBUG, TAG, "JNI_OnLoad in calecore");
JNIEnv* env;
- if((*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6) != JNI_OK)
+ if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
{
return -1;
}
- g_jvm = jvm; /* cache the JavaVM pointer */
+ g_jvm = jvm; /* cache the JavaVM pointer */
//JVM required for WifiCore to work with JNI interface
CAWiFiJniInit(jvm);
OIC_LOG_V(DEBUG, TAG, "JNI_OnUnload in calecore");
JNIEnv* env;
- if((*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_6) != JNI_OK)
+ if ((*jvm)->GetEnv(jvm, (void**) &env, JNI_VERSION_1_6) != JNI_OK)
{
return;
}
return;
}
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CARegisterLeScanCallback(JNIEnv *env,
- jobject obj, jobject callback)
-{
- OIC_LOG_V(DEBUG, TAG, "CARegisterLeScanCallback");
-
- gLeScanCallback = (*env)->NewGlobalRef(env, callback);
-}
-
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CARegisterLeGattCallback(JNIEnv *env,
- jobject obj, jobject callback)
-{
- OIC_LOG_V(DEBUG, TAG, "CARegisterLeGattCallback");
-
- gLeGattCallback = (*env)->NewGlobalRef(env, callback);
-}
-
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeScanCallback (JNIEnv *env,
- jobject obj, jobject device, jint rssi, jbyteArray scanRecord)
-{
- CANativeAddScanDeviceToList(env, device);
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattConnectionStateChangeCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattConnectionStateChangeCallback
- (JNIEnv *env, jobject obj, jobject gatt, jint status, jint newstate)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattConnectionStateChangeCallback - status %d, newstate %d", status, newstate);
-
- if(GATT_SUCCESS == status && STATE_CONNECTED == newstate) // le connected
- {
- if(gatt) {
- CANativeAddGattobjToList(env, gatt);
- CANativeLEDiscoverServices(env, gatt);
- }
- }
- else if (GATT_SUCCESS == status && STATE_DISCONNECTED == newstate) // le disconnected
- {
-// CANativeLEStartScan();
-
- if(gatt) {
- //CANativeGattClose(env, gatt); // 20150105
- //CANativeRemoveGattObj(env, gatt); // 20150105
- }
- }
- else // other error
- {
- CANativeSendFinsih(env, gatt);
- }
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattServicesDiscoveredCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattServicesDiscoveredCallback
- (JNIEnv *env, jobject obj, jobject gatt, jint status)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattServicesDiscoveredCallback - status %d: ", status);
-
- if(0 != status) // discovery error
- {
- CANativeSendFinsih(env, gatt);
- return;
- }
-
- // read Characteristic
-// CANativeReadCharacteristic(env, gatt);
-
- jboolean ret_rx = CANativeSetCharacteristicNoti(env, gatt, IOTIVITY_GATT_RX_UUID);
- if(!ret_rx) // SetCharacteristicNoti is failed
- {
- CANativeSendFinsih(env, gatt);
- return;
- }
-
-// jstring data = (*env)->NewStringUTF(env, "HelloWorld");
- jobject jni_obj_character = CANativeCreateGattCharacteristic(env, gatt, gSendBuffer);
- if(!jni_obj_character)
- {
- CANativeSendFinsih(env, gatt);
- return;
- }
-
- sleep(1);
- jboolean ret = CANativeLESendData(env, gatt, jni_obj_character);
- if(!ret)
- {
- CANativeSendFinsih(env, gatt);
- return;
- }
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattCharacteristicReadCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattCharacteristicReadCallback
- (JNIEnv *env, jobject obj, jobject gatt, jobject characteristic, jbyteArray data, jint status)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicReadCallback - status : %d", status);
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattCharacteristicWritjclasseCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattCharacteristicWriteCallback
- (JNIEnv *env, jobject obj, jobject gatt, jobject characteristic, jbyteArray data, jint status)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicWriteCallback - status : %d", status);
-
- jboolean isCopy;
- char* wroteData = (char*)(*env)->GetByteArrayElements(env, data, &isCopy);
-
- jstring jni_address = CANativeGetAddressFromGattObj(env, gatt);
- const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
-
- OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicWriteCallback - write data : %s", wroteData);
-
-#ifdef DEBUG_MODE
- CANativeSendFinsih(env, gatt);
-#endif
-
- if(0 != status) // error case
- {
- CANativeSendFinsih(env, gatt);
- }
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattCharacteristicChangedCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattCharacteristicChangedCallback
- (JNIEnv *env, jobject obj, jobject gatt, jobject characteristic, jbyteArray data)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicChangedCallback");
-
- // get Byte Array and covert to char*
- jint length = (*env)->GetArrayLength(env, data);
-
- jboolean isCopy;
- jbyte *jni_byte_responseData = (char*)(*env)->GetByteArrayElements(env, data, &isCopy);
-
- char responseData[MAX_PDU_BUFFER];
- memset(responseData, 0, MAX_PDU_BUFFER);
- strncpy(responseData, (char*)jni_byte_responseData, length);
- responseData[length] = '\0';
- (*env)->ReleaseByteArrayElements(env, data, (jbyte*)jni_byte_responseData, JNI_ABORT);
-
- jstring jni_address = CANativeGetAddressFromGattObj(env, gatt);
- const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
-
- OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicChangedCallback - data. : %s, %d", responseData, length);
-
- // callback
- gPacketReceiveCallback(address, responseData);
-
- // LE disconnect and finish BLE write routine
- CANativeSendFinsih(env, gatt);
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattDescriptorReadCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattDescriptorReadCallback
- (JNIEnv *env, jobject obj, jobject gatt, jobject descriptor, jint status)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattDescriptorReadCallback - status %d: ", status);
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattDescriptorWriteCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattDescriptorWriteCallback
- (JNIEnv *env, jobject obj, jobject gatt, jobject descriptor, jint status)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattDescriptorWriteCallback - status %d: ", status);
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattReliableWriteCompletedCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattReliableWriteCompletedCallback
- (JNIEnv *env, jobject obj, jobject gatt, jint status)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattReliableWriteCompletedCallback - status %d: ", status);
-}
-
-/*
- * Class: com_iotivity_jar_CALeInterface
- * Method: CALeGattReadRemoteRssiCallback
- * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
- */
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattReadRemoteRssiCallback
- (JNIEnv *env, jobject obj, jobject gatt, jint rssi, jint status)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeGattReadRemoteRssiCallback - rssi %d, status %d: ", rssi, status);
-}
-
-
void CALEInitialize(u_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "CALEInitialize");
- gThreadPoolHandle = handle;
+ g_threadPoolHandle = handle;
// init mutex for send logic
- gThreadMutex = u_mutex_new();
- gThreadCond = u_cond_new();
+ g_threadMutex = u_mutex_new();
+ g_threadCond = u_cond_new();
CANativeCreateUUIDList();
{
OIC_LOG(DEBUG, TAG, "CALETerminate");
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
CANativeLEDisconnectAll(env);
- if(gLeScanCallback)
+ if (g_leScanCallback)
{
- CANativeLEStopScanImpl(env, gLeScanCallback);
+ CANativeLEStopScanImpl(env, g_leScanCallback);
sleep(1);
}
- if(gLeScanCallback)
+ if (g_leScanCallback)
{
- (*env)->DeleteGlobalRef(env, gLeScanCallback);
+ (*env)->DeleteGlobalRef(env, g_leScanCallback);
}
- if(gLeGattCallback)
+ if (g_leGattCallback)
{
- (*env)->DeleteGlobalRef(env, gLeGattCallback);
+ (*env)->DeleteGlobalRef(env, g_leGattCallback);
}
- if(gContext)
+ if (g_context)
{
- (*env)->DeleteGlobalRef(env, gContext);
+ (*env)->DeleteGlobalRef(env, g_context);
}
- if(gSendBuffer)
+ if (g_sendBuffer)
{
- (*env)->DeleteGlobalRef(env, gSendBuffer);
+ (*env)->DeleteGlobalRef(env, g_sendBuffer);
}
- if(gUUIDList)
+ if (g_UUIDList)
{
- (*env)->DeleteGlobalRef(env, gUUIDList);
+ (*env)->DeleteGlobalRef(env, g_UUIDList);
}
CANativeRemoveAllDevices(env);
CANativeRemoveAllGattObjsList(env);
- gIsStartServer = FALSE;
- gIsFinishSendData = FALSE;
+ g_isStartServer = FALSE;
+ g_isFinishSendData = FALSE;
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
// delete mutex object
- u_mutex_free(gThreadMutex);
- gThreadMutex = NULL;
- u_cond_signal(gThreadCond);
- u_cond_free(gThreadCond);
+ u_mutex_free(g_threadMutex);
+ g_threadMutex = NULL;
+ u_cond_signal(g_threadCond);
+ u_cond_free(g_threadCond);
}
-void CANativeSendFinsih(JNIEnv *env, jobject gatt)
+void CANativeSendFinish(JNIEnv *env, jobject gatt)
{
- OIC_LOG_V(DEBUG, TAG, "CANativeSendFinsih");
+ OIC_LOG_V(DEBUG, TAG, "CANativeSendFinish");
- if(gatt)
+ if (gatt)
{
CANativeLEDisconnect(env, gatt);
}
CANativeupdateSendCnt(env);
}
-int32_t CALESendUnicastMessage(const char* address, const char* data, uint32_t dataLen)
+CAResult_t CALESendUnicastMessage(const char* address, const char* data, const uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CALESendUnicastMessage(%s, %s)", address, data);
- CALESendUnicastMessageImpl(address, data, dataLen);
- return 0;
+ return CALESendUnicastMessageImpl(address, data, dataLen);
}
-int32_t CALESendMulticastMessage(const char* data, uint32_t dataLen)
+CAResult_t CALESendMulticastMessage(const char* data, const uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CALESendMulticastMessage(%s)", data);
- jboolean isAttached = FALSE;
- JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
- {
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
- res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
-
- if(res != JNI_OK)
- {
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return 0;
- }
- isAttached = TRUE;
- }
-
- CALESendMulticastMessageImpl(env, data, dataLen);
-
- if(isAttached)
- (*g_jvm)->DetachCurrentThread(g_jvm);
-
- return 1;
+ return CALESendMulticastMessageImpl(data, dataLen);
}
-int32_t CALEStartUnicastServer(const char* address)
+CAResult_t CALEStartUnicastServer(const char* address)
{
OIC_LOG_V(DEBUG, TAG, "CALEStartUnicastServer(%s)", address);
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CALEStartMulticastServer()
+CAResult_t CALEStartMulticastServer()
{
OIC_LOG_V(DEBUG, TAG, "CALEStartMulticastServer");
- if(gIsStartServer)
+ if (g_isStartServer)
{
- OIC_LOG_V(DEBUG, TAG, "server is already started..it will be skipped");
- return 0;
+ OIC_LOG_V(ERROR, TAG, "server is already started..it will be skipped");
+ return CA_STATUS_FAILED;
}
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return 0;
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
+ return CA_STATUS_FAILED;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
- gIsStartServer = TRUE;
+ g_isStartServer = JNI_TRUE;
CANativeLEStartScan();
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CALEStopUnicastServer(int32_t serverID)
+void CALEStopUnicastServer()
{
OIC_LOG(DEBUG, TAG, "CALEStopUnicastServer");
-
- return 0;
}
-int32_t CALEStopMulticastServer(int32_t serverID)
+void CALEStopMulticastServer()
{
OIC_LOG(DEBUG, TAG, "CALEStopMulticastServer");
- gIsStartServer = FALSE;
+ g_isStartServer = JNI_FALSE;
CANativeLEStopScan();
- return 0;
}
void CALESetCallback(CAPacketReceiveCallback callback)
{
- gPacketReceiveCallback = callback;
+ g_packetReceiveCallback = callback;
}
CAResult_t CALEGetInterfaceInfo(char **address)
void CALEGetLocalAddress(char** address)
{
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
jstring jni_address = CALEGetLocalDeviceAddress(env);
- if(jni_address)
+ if (jni_address)
{
const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
- *address = (char*)OICMalloc(strlen(localAddress) + 1);
+ uint32_t length = strlen(localAddress);
+ *address = (char*) OICMalloc(length + 1);
if (*address == NULL)
{
return;
}
- memcpy(*address, localAddress, strlen(localAddress));
+ memcpy(*address, localAddress, length + 1);
}
OIC_LOG_V(DEBUG, TAG, "Local Address : %s", *address);
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
}
-int32_t CALESendUnicastMessageImpl(const char* address, const char* data, uint32_t dataLen)
+CAResult_t CALESendUnicastMessageImpl(const char* address, const char* data, const uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CALESendUnicastMessageImpl, address: %s, data: %s", address, data);
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return 0;
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
+ return CA_STATUS_FAILED;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] set byteArray for data");
- if(gSendBuffer)
+ if (g_sendBuffer)
{
- (*env)->DeleteGlobalRef(env, gSendBuffer);
+ (*env)->DeleteGlobalRef(env, g_sendBuffer);
}
jbyteArray jni_arr = (*env)->NewByteArray(env, dataLen);
- (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*)data);
- gSendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
+ (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*) data);
+ g_sendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
// connect to gatt server
- CANativeLEStopScanImpl(env, gLeScanCallback);
+ CANativeLEStopScanImpl(env, g_leScanCallback);
sleep(1);
jobject jni_obj_bluetoothDevice = NULL;
- if(gContext && gdeviceList)
+ if (g_context && g_deviceList)
{
jint index;
- for (index = 0; index < u_arraylist_length(gdeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_deviceList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
- return 0;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
+ return CA_STATUS_FAILED;
}
jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
- if(!jni_setAddress)
+ if (!jni_setAddress)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
- return 0;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_setAddress is null");
+ return CA_STATUS_FAILED;
}
const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
- if(!strcmp(setAddress, address))
+ if (!strcmp(setAddress, address))
{
jni_obj_bluetoothDevice = jarrayObj;
break;
}
}
- if(jni_obj_bluetoothDevice)
+ if (jni_obj_bluetoothDevice)
{
jboolean autoConnect = FALSE;
- CANativeLEConnect(env, jni_obj_bluetoothDevice, gContext, autoConnect, gLeGattCallback);
+ CANativeLEConnect(env, jni_obj_bluetoothDevice, g_context, autoConnect,
+ g_leGattCallback);
}
}
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
- return 1;
+ return CA_STATUS_OK;
}
-int32_t CALESendMulticastMessageImpl(JNIEnv *env, const char* data, uint32_t dataLen)
+CAResult_t CALESendMulticastMessageImpl(const char* data, const uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, send to, data: %s, %d", data, dataLen);
- if(!gdeviceList)
+ jboolean isAttached = JNI_FALSE;
+ JNIEnv* env;
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceList is null");
- return 0;
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
+ res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
+ if (res != JNI_OK)
+ {
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
+ return CA_STATUS_FAILED;
+ }
+ isAttached = JNI_TRUE;
}
- OIC_LOG(DEBUG, TAG, "set wait");
+ if (!g_deviceList)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] g_deviceList is null");
+ return CA_STATUS_FAILED;
+ }OIC_LOG(DEBUG, TAG, "set wait");
- gIsFinishSendData = FALSE;
+ g_isFinishSendData = JNI_FALSE;
OIC_LOG(DEBUG, TAG, "[BLE][Native] set byteArray for data");
- if(gSendBuffer)
+ if (g_sendBuffer)
{
- (*env)->DeleteGlobalRef(env, gSendBuffer);
+ (*env)->DeleteGlobalRef(env, g_sendBuffer);
}
jbyteArray jni_arr = (*env)->NewByteArray(env, dataLen);
- (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*)data);
- gSendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
+ (*env)->SetByteArrayRegion(env, jni_arr, 0, dataLen, (jbyte*) data);
+ g_sendBuffer = (jbyteArray)(*env)->NewGlobalRef(env, jni_arr);
// connect to gatt server
- CANativeLEStopScanImpl(env, gLeScanCallback);
+ CANativeLEStopScanImpl(env, g_leScanCallback);
sleep(1);
// reset gatt list
CANativeRemoveAllGattObjsList(env);
CANativeCreateGattObjList(env);
- gTargetCnt = u_arraylist_length(gdeviceList);
+ g_targetCnt = u_arraylist_length(g_deviceList);
jint index = 0;
- while (index < u_arraylist_length(gdeviceList)) {
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceList, index);
- if(!jarrayObj)
+ while (index < u_arraylist_length(g_deviceList))
+ {
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
continue;
}
- if(0 <= CANativeLEConnect(env, jarrayObj, gContext, FALSE, gLeGattCallback))
+ if (CA_STATUS_FAILED
+ == CANativeLEConnect(env, jarrayObj, g_context, JNI_FALSE, g_leGattCallback))
{
// connection failure
- index++;
}
+ index++;
sleep(1);
}
// wait for finish to send data through "CALeGattServicesDiscoveredCallback"
- if(!gIsFinishSendData)
+ if (!g_isFinishSendData)
{
- u_mutex_lock(gThreadMutex);
- u_cond_wait(gThreadCond, gThreadMutex);
+ u_mutex_lock(g_threadMutex);
+ u_cond_wait(g_threadCond, g_threadMutex);
OIC_LOG(DEBUG, TAG, "unset wait");
- u_mutex_unlock(gThreadMutex);
+ u_mutex_unlock(g_threadMutex);
}
// start LE Scan again
CANativeLEStartScan();
#endif
- return 1;
+ if (isAttached)
+ {
+ (*g_jvm)->DetachCurrentThread(g_jvm);
+ }
+
+ return CA_STATUS_OK;
}
jstring CANativeGetAddressFromGattObj(JNIEnv *env, jobject gatt)
{
- if(!gatt)
+ if (!gatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gatt is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] gatt is null");
return NULL;
}
jclass jni_cid_gattdevice_list = (*env)->FindClass(env, CLASSPATH_BT_GATT);
- if(!jni_cid_gattdevice_list)
+ if (!jni_cid_gattdevice_list)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_gattdevice_list is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_gattdevice_list is null");
return NULL;
}
jmethodID jni_mid_getDevice = (*env)->GetMethodID(env, jni_cid_gattdevice_list, "getDevice",
- "()Landroid/bluetooth/BluetoothDevice;");
- if(!jni_mid_getDevice)
+ "()Landroid/bluetooth/BluetoothDevice;");
+ if (!jni_mid_getDevice)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_getDevice is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_getDevice is null");
return NULL;
}
jobject jni_obj_device = (*env)->CallObjectMethod(env, gatt, jni_mid_getDevice);
- if(!jni_obj_device)
+ if (!jni_obj_device)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_device is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_device is null");
return NULL;
}
jstring jni_address = CALEGetAddressFromBTDevice(env, jni_obj_device);
- if(!jni_address)
+ if (!jni_address)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_address is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_address is null");
return NULL;
}
// get BluetoothGatt class
OIC_LOG(DEBUG, TAG, "[BLE][Native] get BluetoothGatt class");
jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
- if(!jni_cid_BluetoothGatt)
+ if (!jni_cid_BluetoothGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
return;
}
- jmethodID jni_mid_closeGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "close","()V");
- if(!jni_mid_closeGatt)
+ jmethodID jni_mid_closeGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "close", "()V");
+ if (!jni_mid_closeGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_closeGatt is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_closeGatt is null");
return;
}
void CANativeLEStartScan()
{
- if(!gIsStartServer)
+ if (!g_isStartServer)
{
OIC_LOG_V(DEBUG, TAG, "server is not started yet..scan will be passed");
return;
jboolean isAttached = FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
isAttached = TRUE;
OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeLEStartScan");
// scan gatt server with UUID
- if(gLeScanCallback && gUUIDList)
+ if (g_leScanCallback && g_UUIDList)
{
- CANativeLEStartScanWithUUIDImpl(env, gUUIDList, gLeScanCallback);
+ CANativeLEStartScanWithUUIDImpl(env, g_UUIDList, g_leScanCallback);
}
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
}
void CANativeLEStartScanImpl(JNIEnv *env, jobject callback)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return;
}
// get default bt adapter class
- jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
- if(!jni_cid_BTAdapter)
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+ if (!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] getState From BTAdapter: jni_cid_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] getState From BTAdapter: jni_cid_BTAdapter is null");
return;
}
// get remote bt adapter method
- jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
- if(!jni_mid_getDefaultAdapter)
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+ "getDefaultAdapter",
+ METHODID_OBJECTNONPARAM);
+ if (!jni_mid_getDefaultAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] getState From BTAdapter: jni_mid_getDefaultAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] getState From BTAdapter: getDefaultAdapter is null");
return;
}
// get start le scan method
- jmethodID jni_mid_startLeScan = (*env)->GetMethodID(env, jni_cid_BTAdapter, "startLeScan",
+ jmethodID jni_mid_startLeScan = (*env)->GetMethodID(
+ env, jni_cid_BTAdapter, "startLeScan",
"(Landroid/bluetooth/BluetoothAdapter$LeScanCallback;)Z");
- if(!jni_mid_startLeScan)
+ if (!jni_mid_startLeScan)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] startLeScan: jni_mid_startLeScan is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] startLeScan: jni_mid_startLeScan is null");
return;
}
// gat bt adapter object
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
- if(!jni_obj_BTAdapter)
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+ jni_mid_getDefaultAdapter);
+ if (!jni_obj_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] getState From BTAdapter: jni_obj_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] getState From BTAdapter: jni_obj_BTAdapter is null");
return;
}
// call start le scan method
- jboolean jni_obj_startLeScan = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_startLeScan, callback);
- if(!jni_obj_startLeScan)
+ jboolean jni_obj_startLeScan = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter,
+ jni_mid_startLeScan, callback);
+ if (!jni_obj_startLeScan)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] startLeScan is failed");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] startLeScan is failed");
return;
}
else
{
// setting UUID
jclass jni_cid_uuid = (*env)->FindClass(env, CLASSPATH_BT_UUID);
- if(!jni_cid_uuid)
+ if (!jni_cid_uuid)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_uuid is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_uuid is null");
return NULL;
}
- jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(env, jni_cid_uuid, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
- if(!jni_mid_fromString)
+ jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(
+ env, jni_cid_uuid, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
+ if (!jni_mid_fromString)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_fromString is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_fromString is null");
return NULL;
}
jstring jni_uuid = (*env)->NewStringUTF(env, uuid);
- jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid, jni_mid_fromString, jni_uuid);
- if(!jni_obj_uuid)
+ jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_uuid, jni_mid_fromString,
+ jni_uuid);
+ if (!jni_obj_uuid)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_uuid is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_uuid is null");
return NULL;
}
// get default bt adapter class
OIC_LOG(DEBUG, TAG, "[BLE][Native] get default bt adapter class");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return;
}
- jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
- if(!jni_cid_BTAdapter)
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+ if (!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] getState From BTAdapter: jni_cid_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] getState From BTAdapter: jni_cid_BTAdapter is null");
return;
}
// get remote bt adapter method
OIC_LOG(DEBUG, TAG, "[BLE][Native] get remote bt adapter method");
- jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
- if(!jni_mid_getDefaultAdapter)
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+ "getDefaultAdapter",
+ METHODID_OBJECTNONPARAM);
+ if (!jni_mid_getDefaultAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] getState From BTAdapter: jni_mid_getDefaultAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] getState From BTAdapter: getDefaultAdapter is null");
return;
}
// get start le scan method
OIC_LOG(DEBUG, TAG, "[BLE][Native] get start le scan method");
- jmethodID jni_mid_startLeScan = (*env)->GetMethodID(env, jni_cid_BTAdapter, "startLeScan",
+ jmethodID jni_mid_startLeScan = (*env)->GetMethodID(
+ env, jni_cid_BTAdapter, "startLeScan",
"([Ljava/util/UUID;Landroid/bluetooth/BluetoothAdapter$LeScanCallback;)Z");
- if(!jni_mid_startLeScan)
+ if (!jni_mid_startLeScan)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] startLeScan: jni_mid_startLeScan is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] startLeScan: jni_mid_startLeScan is null");
return;
}
// get bt adapter object
OIC_LOG(DEBUG, TAG, "[BLE][Native] get bt adapter object");
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
- if(!jni_obj_BTAdapter)
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+ jni_mid_getDefaultAdapter);
+ if (!jni_obj_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] getState From BTAdapter: jni_obj_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] getState From BTAdapter: jni_obj_BTAdapter is null");
return;
}
// call start le scan method
OIC_LOG(DEBUG, TAG, "[BLE][Native] call start le scan service method");
- jboolean jni_obj_startLeScan = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter, jni_mid_startLeScan, uuids, callback);
- if(!jni_obj_startLeScan)
+ jboolean jni_obj_startLeScan = (*env)->CallBooleanMethod(env, jni_obj_BTAdapter,
+ jni_mid_startLeScan, uuids, callback);
+ if (!jni_obj_startLeScan)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] startLeScan With UUID is failed");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] startLeScan With UUID is failed");
return;
}
else
{
jboolean isAttached = FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
isAttached = TRUE;
}
- CANativeLEStopScanImpl(env, gLeScanCallback);
+ CANativeLEStopScanImpl(env, g_leScanCallback);
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
}
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeLEStopScan");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return;
}
// get default bt adapter class
- jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
- if(!jni_cid_BTAdapter)
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+ if (!jni_cid_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] getState From BTAdapter: jni_cid_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] getState From BTAdapter: jni_cid_BTAdapter is null");
return;
}
// get remote bt adapter method
- jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
- if(!jni_mid_getDefaultAdapter)
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+ "getDefaultAdapter",
+ METHODID_OBJECTNONPARAM);
+ if (!jni_mid_getDefaultAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] getState From BTAdapter: jni_mid_getDefaultAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] getState From BTAdapter: getDefaultAdapter is null");
return;
}
// get start le scan method
- jmethodID jni_mid_stopLeScan = (*env)->GetMethodID(env, jni_cid_BTAdapter, "stopLeScan",
+ jmethodID jni_mid_stopLeScan = (*env)->GetMethodID(
+ env, jni_cid_BTAdapter, "stopLeScan",
"(Landroid/bluetooth/BluetoothAdapter$LeScanCallback;)V");
- if(!jni_mid_stopLeScan)
+ if (!jni_mid_stopLeScan)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] stopLeScan: jni_mid_stopLeScan is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] stopLeScan: jni_mid_stopLeScan is null");
return;
}
// gat bt adapter object
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
- if(!jni_obj_BTAdapter)
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+ jni_mid_getDefaultAdapter);
+ if (!jni_obj_BTAdapter)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_BTAdapter is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_BTAdapter is null");
return;
}
(*env)->CallVoidMethod(env, jni_obj_BTAdapter, jni_mid_stopLeScan, callback);
}
-int32_t CANativeLEConnect(JNIEnv *env, jobject bluetoothDevice, jobject context,
- jboolean autoconnect, jobject callback)
+CAResult_t CANativeLEConnect(JNIEnv *env, jobject bluetoothDevice, jobject context,
+ jboolean autoconnect, jobject callback)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return 0;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_STATUS_FAILED;
}
jstring jni_address = CALEGetAddressFromBTDevice(env, bluetoothDevice);
// get BluetoothDevice class
OIC_LOG(DEBUG, TAG, "[BLE][Native] get BluetoothDevice class");
jclass jni_cid_BluetoothDevice = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
- if(!jni_cid_BluetoothDevice)
+ if (!jni_cid_BluetoothDevice)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] bleConnect: jni_cid_BluetoothDevice is null");
- return 0;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] bleConnect: jni_cid_BluetoothDevice is null");
+ return CA_STATUS_FAILED;
}
// get connectGatt method
OIC_LOG(DEBUG, TAG, "[BLE][Native] get connectGatt method");
- jmethodID jni_mid_connectGatt = (*env)->GetMethodID(env, jni_cid_BluetoothDevice,
- "connectGatt",
- "(Landroid/content/Context;ZLandroid/bluetooth/BluetoothGattCallback;)Landroid/bluetooth/BluetoothGatt;");
- if(!jni_mid_connectGatt)
+ jmethodID jni_mid_connectGatt = (*env)->GetMethodID(
+ env, jni_cid_BluetoothDevice, "connectGatt",
+ "(Landroid/content/Context;ZLandroid/bluetooth/BluetoothGattCallback;)"
+ "Landroid/bluetooth/BluetoothGatt;");
+ if (!jni_mid_connectGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] bleConnect: jni_mid_connectGatt is null");
- return 0;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] bleConnect: jni_mid_connectGatt is null");
+ return CA_STATUS_FAILED;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] Call object method - connectGatt");
jobject jni_obj_connectGatt = (*env)->CallObjectMethod(env, bluetoothDevice,
- jni_mid_connectGatt, NULL, autoconnect, callback);
- if(!jni_obj_connectGatt)
+ jni_mid_connectGatt,
+ NULL,
+ autoconnect, callback);
+ if (!jni_obj_connectGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] CALL API - connectGatt was failed.obj will be removed");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] CALL API - connectGatt was failed.obj will be removed");
CANativeRemoveDevice(env, jni_address);
CANativeupdateSendCnt(env);
- return -1;
+ return CA_STATUS_FAILED;
}
else
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] CALL API - connecting..");
}
- return 1;
+ return CA_STATUS_OK;
}
void CANativeLEDisconnect(JNIEnv *env, jobject bluetoothGatt)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return;
}
// get BluetoothGatt class
OIC_LOG(DEBUG, TAG, "[BLE][Native] get BluetoothGatt classjobject bluetoothGatt");
jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
- if(!jni_cid_BluetoothGatt)
+ if (!jni_cid_BluetoothGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
return;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] get gatt disconnect method");
- jmethodID jni_mid_disconnectGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
- "disconnect","()V");
- if(!jni_mid_disconnectGatt)
+ jmethodID jni_mid_disconnectGatt = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "disconnect",
+ "()V");
+ if (!jni_mid_disconnectGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_disconnectGatt is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_disconnectGatt is null");
return;
}
{
OIC_LOG_V(DEBUG, TAG, "CANativeLEDisconnectAll");
- if(!gGattObjectList)
+ if (!g_gattObjectList)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gGattObjectList is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] g_gattObjectList is null");
return;
}
jint index;
- for (index = 0; index < u_arraylist_length(gGattObjectList); index++)
+ for (index = 0; index < u_arraylist_length(g_gattObjectList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gGattObjectList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
- return;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
+ continue;
}
CANativeLEDisconnect(env, jarrayObj);
}
- OICFree(gGattObjectList);
- gGattObjectList = NULL;
+ OICFree(g_gattObjectList);
+ g_gattObjectList = NULL;
return;
}
void CANativeLEDiscoverServices(JNIEnv *env, jobject bluetoothGatt)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return;
}
// get BluetoothGatt class
OIC_LOG(DEBUG, TAG, "[BLE][Native] get BluetoothGatt class");
jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
- if(!jni_cid_BluetoothGatt)
+ if (!jni_cid_BluetoothGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
return;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] discovery gatt services method");
jmethodID jni_mid_discoverServices = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
- "discoverServices","()Z");
- if(!jni_mid_discoverServices)
+ "discoverServices", "()Z");
+ if (!jni_mid_discoverServices)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_discoverServices is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_discoverServices is null");
return;
}
// call disconnect gatt method
(*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_discoverServices);
}
-jboolean CANativeLESendData(JNIEnv *env, jobject bluetoothGatt, jobject gattCharacteristic)
+CAResult_t CANativeWriteCharacteristic(JNIEnv *env, jobject bluetoothGatt,
+ jobject gattCharacteristic)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_STATUS_FAILED;
}
// WRITE GATT CHARACTERISTIC
// get BluetoothGatt class
OIC_LOG(DEBUG, TAG, "[BLE][Native] get BluetoothGatt class");
jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
- if(!jni_cid_BluetoothGatt)
+ if (!jni_cid_BluetoothGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
+ return CA_STATUS_FAILED;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] write characteristic method");
- jmethodID jni_mid_writeCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGatt,
- "writeCharacteristic", "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z");
- if(!jni_mid_writeCharacteristic)
+ jmethodID jni_mid_writeCharacteristic = (*env)->GetMethodID(
+ env, jni_cid_BluetoothGatt, "writeCharacteristic",
+ "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z");
+ if (!jni_mid_writeCharacteristic)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_writeCharacteristic is null");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_writeCharacteristic is null");
+ return CA_STATUS_FAILED;
}
// call disconnect gatt method
OIC_LOG(DEBUG, TAG, "[BLE][Native] CALL API - request to write gatt characteristic");
- jboolean ret = (jboolean)(*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_writeCharacteristic, gattCharacteristic);
- if(ret)
+ jboolean ret = (jboolean)(*env)->CallBooleanMethod(env, bluetoothGatt,
+ jni_mid_writeCharacteristic,
+ gattCharacteristic);
+ if (ret)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] writeCharacteristic is success");
}
else
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] writeCharacteristic is failed");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] writeCharacteristic is failed");
+ return CA_STATUS_FAILED;
}
- return TRUE;
+ return CA_STATUS_OK;
}
void CANativeReadCharacteristic(JNIEnv *env, jobject bluetoothGatt)
{
- if(!CALEIsEnableBTAdapter(env))
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return;
- }
-
- jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
- if(!jni_cid_BluetoothGatt)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
- return;
- }
-
- jstring jni_uuid = (*env)->NewStringUTF(env, IOTIVITY_GATT_RX_UUID);
- jobject jni_obj_GattCharacteristic = CANativeGetGattService(env, bluetoothGatt, jni_uuid);
- if(!jni_obj_GattCharacteristic)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_GattCharacteristic is null");
- return;
- }
-
- OIC_LOG(DEBUG, TAG, "[BLE][Native] read characteristic method");
- jmethodID jni_mid_readCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "readCharacteristic", "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z");
- if(!jni_mid_readCharacteristic)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_readCharacteristic is null");
- return;
- }
-
- // call disconnect gatt method
- OIC_LOG(DEBUG, TAG, "[BLE][Native] CALL API - request to read gatt characteristic");
- jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_readCharacteristic, jni_obj_GattCharacteristic);
- if(ret)
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] readCharacteristic is success");
- }
- else
- {
- OIC_LOG(DEBUG, TAG, "[BLE][Native] readCharacteristic is failed");
- }
+ if (!CALEIsEnableBTAdapter(env))
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return;
+ }
+
+ jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
+ if (!jni_cid_BluetoothGatt)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
+ return;
+ }
+
+ jstring jni_uuid = (*env)->NewStringUTF(env, IOTIVITY_GATT_RX_UUID);
+ jobject jni_obj_GattCharacteristic = CANativeGetGattService(env, bluetoothGatt, jni_uuid);
+ if (!jni_obj_GattCharacteristic)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_GattCharacteristic is null");
+ return;
+ }
+
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] read characteristic method");
+ jmethodID jni_mid_readCharacteristic = (*env)->GetMethodID(
+ env, jni_cid_BluetoothGatt, "readCharacteristic",
+ "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z");
+ if (!jni_mid_readCharacteristic)
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_readCharacteristic is null");
+ return;
+ }
+
+ // call disconnect gatt method
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] CALL API - request to read gatt characteristic");
+ jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_readCharacteristic,
+ jni_obj_GattCharacteristic);
+ if (ret)
+ {
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] readCharacteristic is success");
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "[BLE][Native] readCharacteristic is failed");
+ }
}
-jboolean CANativeSetCharacteristicNoti(JNIEnv *env, jobject bluetoothGatt, const char* uuid)
+CAResult_t CANativeSetCharacteristicNotification(JNIEnv *env, jobject bluetoothGatt,
+ const char* uuid)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_ADAPTER_NOT_ENABLED;
}
// get BluetoothGatt class
- OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeSetCharacteristicNoti");
+ OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeSetCharacteristicNotification");
jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
- if(!jni_cid_BluetoothGatt)
+ if (!jni_cid_BluetoothGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
+ return CA_STATUS_FAILED;
}
jstring jni_uuid = (*env)->NewStringUTF(env, uuid);
jobject jni_obj_GattCharacteristic = CANativeGetGattService(env, bluetoothGatt, jni_uuid);
- if(!jni_obj_GattCharacteristic)
+ if (!jni_obj_GattCharacteristic)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_GattCharacteristic is null");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_GattCharacteristic is null");
+ return CA_STATUS_FAILED;
}
// set Characteristic Notification
- jmethodID jni_mid_setNotification = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "setCharacteristicNotification",
+ jmethodID jni_mid_setNotification = (*env)->GetMethodID(
+ env, jni_cid_BluetoothGatt, "setCharacteristicNotification",
"(Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z");
- if(!jni_mid_setNotification)
+ if (!jni_mid_setNotification)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_getService is null");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_getService is null");
+ return CA_STATUS_FAILED;
}
jboolean enable = TRUE;
- jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_setNotification, jni_obj_GattCharacteristic, enable);
- if(1 == ret)
+ jboolean ret = (*env)->CallBooleanMethod(env, bluetoothGatt, jni_mid_setNotification,
+ jni_obj_GattCharacteristic, enable);
+ if (1 == ret)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] CALL API - setCharacteristicNotification is success");
- return TRUE;
+ return CA_STATUS_OK;
}
else
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] CALL API - setCharacteristicNotification is failed");
- return FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] CALL API - setCharacteristicNotification is failed");
+ return CA_STATUS_FAILED;
}
}
jobject CANativeGetGattService(JNIEnv *env, jobject bluetoothGatt, jstring characterUUID)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return NULL;
}
// get BluetoothGatt class
OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeGetGattService");
jclass jni_cid_BluetoothGatt = (*env)->FindClass(env, CLASSPATH_BT_GATT);
- if(!jni_cid_BluetoothGatt)
+ if (!jni_cid_BluetoothGatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BluetoothGatt is null");
return NULL;
}
- jmethodID jni_mid_getService = (*env)->GetMethodID(env, jni_cid_BluetoothGatt, "getService",
+ jmethodID jni_mid_getService = (*env)->GetMethodID(
+ env, jni_cid_BluetoothGatt, "getService",
"(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattService;");
- if(!jni_mid_getService)
+ if (!jni_mid_getService)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_getService is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_getService is null");
return NULL;
}
jobject jni_obj_service_uuid = CANativeGetUUIDObject(env, IOTIVITY_GATT_SERVIE_UUID);
- if(!jni_obj_service_uuid)
+ if (!jni_obj_service_uuid)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_service_uuid is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_service_uuid is null");
return NULL;
}
// get bluetooth gatt service
OIC_LOG(DEBUG, TAG, "[BLE][Native] request to get service");
- jobject jni_obj_gattService = (*env)->CallObjectMethod(env, bluetoothGatt, jni_mid_getService, jni_obj_service_uuid);
+ jobject jni_obj_gattService = (*env)->CallObjectMethod(env, bluetoothGatt, jni_mid_getService,
+ jni_obj_service_uuid);
// get bluetooth gatt service class
- jclass jni_cid_BluetoothGattService = (*env)->FindClass(env, "android/bluetooth/BluetoothGattService");
- if(!jni_cid_BluetoothGattService)
+ jclass jni_cid_BluetoothGattService = (*env)->FindClass(
+ env, "android/bluetooth/BluetoothGattService");
+ if (!jni_cid_BluetoothGattService)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BluetoothGattService is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BluetoothGattService is null");
return NULL;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] get gatt getCharacteristic method");
- jmethodID jni_mid_getCharacteristic = (*env)->GetMethodID(env, jni_cid_BluetoothGattService, "getCharacteristic",
+ jmethodID jni_mid_getCharacteristic = (*env)->GetMethodID(
+ env, jni_cid_BluetoothGattService, "getCharacteristic",
"(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattCharacteristic;");
- if(!jni_mid_getCharacteristic)
+ if (!jni_mid_getCharacteristic)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_getCharacteristic is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_getCharacteristic is null");
return NULL;
}
const char* uuid = (*env)->GetStringUTFChars(env, characterUUID, NULL);
jobject jni_obj_tx_uuid = CANativeGetUUIDObject(env, uuid);
- if(!jni_obj_tx_uuid)
+ if (!jni_obj_tx_uuid)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_tx_uuid is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_tx_uuid is null");
return NULL;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] request to get Characteristic");
- jobject jni_obj_GattCharacteristic = (*env)->CallObjectMethod(env, jni_obj_gattService, jni_mid_getCharacteristic, jni_obj_tx_uuid);
+ jobject jni_obj_GattCharacteristic = (*env)->CallObjectMethod(env, jni_obj_gattService,
+ jni_mid_getCharacteristic,
+ jni_obj_tx_uuid);
return jni_obj_GattCharacteristic;
}
jobject CANativeCreateGattCharacteristic(JNIEnv *env, jobject bluetoothGatt, jbyteArray data)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return NULL;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeCreateGattCharacteristic");
jstring jni_uuid = (*env)->NewStringUTF(env, IOTIVITY_GATT_TX_UUID);
jobject jni_obj_GattCharacteristic = CANativeGetGattService(env, bluetoothGatt, jni_uuid);
- if(!jni_obj_GattCharacteristic)
+ if (!jni_obj_GattCharacteristic)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_GattCharacteristic is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_GattCharacteristic is null");
return NULL;
}
- jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/BluetoothGattCharacteristic");
- if(!jni_cid_BTGattCharacteristic)
+ jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(
+ env, "android/bluetooth/BluetoothGattCharacteristic");
+ if (!jni_cid_BTGattCharacteristic)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BTGattCharacteristic is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BTGattCharacteristic is null");
return NULL;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] set value in Characteristic");
jmethodID jni_mid_setValue = (*env)->GetMethodID(env, jni_cid_BTGattCharacteristic, "setValue",
- "([B)Z");
- if(!jni_mid_setValue)
+ "([B)Z");
+ if (!jni_mid_setValue)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_setValue is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_setValue is null");
return NULL;
}
- jboolean ret = (*env)->CallBooleanMethod(env, jni_obj_GattCharacteristic, jni_mid_setValue, data);
- if(1 == ret)
+ jboolean ret = (*env)->CallBooleanMethod(env, jni_obj_GattCharacteristic, jni_mid_setValue,
+ data);
+ if (1 == ret)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] the locally stored value has been set");
return jni_obj_GattCharacteristic;
jbyteArray CANativeGetValueFromCharacteristic(JNIEnv *env, jobject characteristic)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return NULL;
}
- jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(env, "android/bluetooth/BluetoothGattCharacteristic");
- if(!jni_cid_BTGattCharacteristic)
+ jclass jni_cid_BTGattCharacteristic = (*env)->FindClass(
+ env, "android/bluetooth/BluetoothGattCharacteristic");
+ if (!jni_cid_BTGattCharacteristic)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BTGattCharacteristic is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_BTGattCharacteristic is null");
return NULL;
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] get value in Characteristic");
jmethodID jni_mid_getValue = (*env)->GetMethodID(env, jni_cid_BTGattCharacteristic, "getValue",
- "()[B");
- if(!jni_mid_getValue)
+ "()[B");
+ if (!jni_mid_getValue)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_getValue is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_mid_getValue is null");
return NULL;
}
- jbyteArray jni_obj_data_array = (*env)->CallObjectMethod(env, characteristic, jni_mid_getValue);
+ jbyteArray jni_obj_data_array = (*env)->CallObjectMethod(env, characteristic, jni_mid_getValue);
return jni_obj_data_array;
}
-
void CANativeCreateUUIDList()
{
jboolean isAttached = FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
isAttached = TRUE;
// create new object array
jclass jni_cid_uuid_list = (*env)->FindClass(env, CLASSPATH_BT_UUID);
- if(!jni_cid_uuid_list)
+ if (!jni_cid_uuid_list)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_uuid_list is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_cid_uuid_list is null");
return;
}
- jobjectArray jni_obj_uuid_list = (jobjectArray)(*env)->NewObjectArray(env, 1, jni_cid_uuid_list, NULL);
- if(!jni_obj_uuid_list)
+ jobjectArray jni_obj_uuid_list = (jobjectArray)(*env)->NewObjectArray(env, 1, jni_cid_uuid_list,
+ NULL);
+ if (!jni_obj_uuid_list)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_uuid_list is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_obj_uuid_list is null");
return;
}
jobject jni_obj_uuid = CANativeGetUUIDObject(env, IOTIVITY_GATT_SERVIE_UUID);
(*env)->SetObjectArrayElement(env, jni_obj_uuid_list, 0, jni_obj_uuid);
- gUUIDList = (jobjectArray)(*env)->NewGlobalRef(env, jni_obj_uuid_list);
+ g_UUIDList = (jobjectArray)(*env)->NewGlobalRef(env, jni_obj_uuid_list);
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
}
void CANativeCreateScanDeviceList(JNIEnv *env)
OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeCreateScanDeviceList");
// create new object array
- if (gdeviceList == NULL)
+ if (g_deviceList == NULL)
{
OIC_LOG_V(DEBUG, TAG, "Create device list");
- gdeviceList = u_arraylist_create();
+ g_deviceList = u_arraylist_create();
}
}
void CANativeAddScanDeviceToList(JNIEnv *env, jobject device)
{
- if(!device)
+ if (!device)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] device is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] device is null");
return;
}
- if(!gdeviceList)
+ if (!g_deviceList)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdevice_list is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] gdevice_list is null");
return;
}
jstring jni_remoteAddress = CALEGetAddressFromBTDevice(env, device);
- if(!jni_remoteAddress)
+ if (!jni_remoteAddress)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_remoteAddress is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_remoteAddress is null");
return;
}
const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
- if(!CANativeIsDeviceInList(env, remoteAddress)) {
+ if (!CANativeIsDeviceInList(env, remoteAddress))
+ {
jobject gdevice = (*env)->NewGlobalRef(env, device);
- u_arraylist_add(gdeviceList, gdevice);
+ u_arraylist_add(g_deviceList, gdevice);
OIC_LOG_V(DEBUG, TAG, "Set Object to Array as Element");
}
}
-jboolean CANativeIsDeviceInList(JNIEnv *env, const char* remoteAddress){
+jboolean CANativeIsDeviceInList(JNIEnv *env, const char* remoteAddress)
+{
// get address value from device list
jint index;
- for (index = 0; index < u_arraylist_length(gdeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_deviceList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
return TRUE;
}
jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
- if(!jni_setAddress)
+ if (!jni_setAddress)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_setAddress is null");
return TRUE;
}
const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
- if(!strcmp(remoteAddress, setAddress))
+ if (!strcmp(remoteAddress, setAddress))
{
OIC_LOG_V(DEBUG, TAG, "the device is already set");
return TRUE;
}
- else
- {
- continue;
- }
}
OIC_LOG_V(DEBUG, TAG, "there are no the device in list. we can add");
{
OIC_LOG_V(DEBUG, TAG, "CANativeRemoveAllDevices");
- if(!gdeviceList)
+ if (!g_deviceList)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceList is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] g_deviceList is null");
return;
}
jint index;
- for (index = 0; index < u_arraylist_length(gdeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_deviceList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
- return;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
+ continue;
}
(*env)->DeleteGlobalRef(env, jarrayObj);
}
- OICFree(gdeviceList);
- gdeviceList = NULL;
+ OICFree(g_deviceList);
+ g_deviceList = NULL;
return;
}
{
OIC_LOG_V(DEBUG, TAG, "CANativeRemoveDevice");
- if(!gdeviceList)
+ if (!g_deviceList)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gdeviceList is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] g_deviceList is null");
return;
}
jint index;
- for (index = 0; index < u_arraylist_length(gdeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_deviceList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gdeviceList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_deviceList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
return;
}
jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
- if(!jni_setAddress)
+ if (!jni_setAddress)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_setAddress is null");
return;
}
const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
const char* remoteAddress = (*env)->GetStringUTFChars(env, address, NULL);
- if(!strcmp(setAddress, remoteAddress))
+ if (!strcmp(setAddress, remoteAddress))
{
OIC_LOG_V(DEBUG, TAG, "[BLE][Native] remove object : %s", remoteAddress);
(*env)->DeleteGlobalRef(env, jarrayObj);
CAReorderingDeviceList(index);
return;
}
- }
- OIC_LOG(DEBUG, TAG, "[BLE][Native] there are no target object");
+ }OIC_LOG(DEBUG, TAG, "[BLE][Native] there are no target object");
return;
}
void CAReorderingDeviceList(uint32_t index)
{
- if (index >= gdeviceList->length)
+ if (index >= g_deviceList->length)
{
return;
}
- if (index < gdeviceList->length - 1)
+ if (index < g_deviceList->length - 1)
{
- memmove(&gdeviceList->data[index], &gdeviceList->data[index + 1],
- (gdeviceList->length - index - 1) * sizeof(void *));
+ memmove(&g_deviceList->data[index], &g_deviceList->data[index + 1],
+ (g_deviceList->length - index - 1) * sizeof(void *));
}
- gdeviceList->size--;
- gdeviceList->length--;
+ g_deviceList->size--;
+ g_deviceList->length--;
}
/**
OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeCreateGattObjList");
// create new object array
- if (gGattObjectList == NULL)
+ if (g_gattObjectList == NULL)
{
OIC_LOG_V(DEBUG, TAG, "Create Gatt object list");
- gGattObjectList = u_arraylist_create();
+ g_gattObjectList = u_arraylist_create();
}
}
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeAddGattobjToList");
- if(!gatt)
+ if (!gatt)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gatt is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] gatt is null");
return;
}
- if(!gGattObjectList)
+ if (!g_gattObjectList)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gGattObjectList is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] g_gattObjectList is null");
return;
}
jstring jni_remoteAddress = CANativeGetAddressFromGattObj(env, gatt);
- if(!jni_remoteAddress)
+ if (!jni_remoteAddress)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_remoteAddress is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_remoteAddress is null");
return;
}
const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
- if(!CANativeIsGattObjInList(env, remoteAddress))
+ if (!CANativeIsGattObjInList(env, remoteAddress))
{
jobject gGatt = (*env)->NewGlobalRef(env, gatt);
- u_arraylist_add(gGattObjectList, gGatt);
+ u_arraylist_add(g_gattObjectList, gGatt);
OIC_LOG_V(DEBUG, TAG, "Set Object to Array as Element");
}
}
OIC_LOG(DEBUG, TAG, "[BLE][Native] CANativeIsGattObjInList");
jint index;
- for (index = 0; index < u_arraylist_length(gGattObjectList); index++)
+ for (index = 0; index < u_arraylist_length(g_gattObjectList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gGattObjectList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
return TRUE;
}
jstring jni_setAddress = CANativeGetAddressFromGattObj(env, jarrayObj);
- if(!jni_setAddress)
+ if (!jni_setAddress)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_setAddress is null");
return TRUE;
}
const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
- if(!strcmp(remoteAddress, setAddress))
+ if (!strcmp(remoteAddress, setAddress))
{
OIC_LOG_V(DEBUG, TAG, "the device is already set");
return TRUE;
{
OIC_LOG_V(DEBUG, TAG, "CANativeRemoveAllGattObjsList");
- if(!gGattObjectList)
+ if (!g_gattObjectList)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gGattObjectList is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] g_gattObjectList is null");
return;
}
jint index;
- for (index = 0; index < u_arraylist_length(gGattObjectList); index++)
+ for (index = 0; index < u_arraylist_length(g_gattObjectList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gGattObjectList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
- return;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
+ continue;
}
(*env)->DeleteGlobalRef(env, jarrayObj);
}
- OICFree(gGattObjectList);
- gGattObjectList = NULL;
+ OICFree(g_gattObjectList);
+ g_gattObjectList = NULL;
return;
}
{
OIC_LOG_V(DEBUG, TAG, "CANativeRemoveGattObj");
- if(!gGattObjectList)
+ if (!g_gattObjectList)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] gGattObjectList is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] g_gattObjectList is null");
return;
}
jint index;
- for (index = 0; index < u_arraylist_length(gGattObjectList); index++)
+ for (index = 0; index < u_arraylist_length(g_gattObjectList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gGattObjectList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_gattObjectList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jarrayObj is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jarrayObj is null");
return;
}
jstring jni_setAddress = CANativeGetAddressFromGattObj(env, jarrayObj);
- if(!jni_setAddress)
+ if (!jni_setAddress)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_setAddress is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_setAddress is null");
return;
}
const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
jstring jni_remoteAddress = CANativeGetAddressFromGattObj(env, gatt);
- if(!jni_remoteAddress)
+ if (!jni_remoteAddress)
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_remoteAddress is null");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] jni_remoteAddress is null");
return;
}
const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
- if(!strcmp(setAddress, remoteAddress))
+ if (!strcmp(setAddress, remoteAddress))
{
OIC_LOG_V(DEBUG, TAG, "[BLE][Native] remove object : %s", remoteAddress);
(*env)->DeleteGlobalRef(env, jarrayObj);
CAReorderingGattList(index);
return;
}
- }
- OIC_LOG(DEBUG, TAG, "[BLE][Native] there are no target object");
+ }OIC_LOG(DEBUG, TAG, "[BLE][Native] there are no target object");
return;
}
void CAReorderingGattList(uint32_t index)
{
- if (index >= gGattObjectList->length)
+ if (index >= g_gattObjectList->length)
{
return;
}
- if (index < gGattObjectList->length - 1)
+ if (index < g_gattObjectList->length - 1)
{
- memmove(&gGattObjectList->data[index], &gGattObjectList->data[index + 1],
- (gGattObjectList->length - index - 1) * sizeof(void *));
+ memmove(&g_gattObjectList->data[index], &g_gattObjectList->data[index + 1],
+ (g_gattObjectList->length - index - 1) * sizeof(void *));
}
- gGattObjectList->size--;
- gGattObjectList->length--;
+ g_gattObjectList->size--;
+ g_gattObjectList->length--;
}
/**
- * Check Sent Count for remove gSendBuffer
+ * Check Sent Count for remove g_sendBuffer
*/
void CANativeupdateSendCnt(JNIEnv *env)
{
// mutex lock
- u_mutex_lock(gThreadMutex);
+ u_mutex_lock(g_threadMutex);
- gCurrentSentCnt++;
+ g_currentSentCnt++;
- if(gTargetCnt <= gCurrentSentCnt)
+ if (g_targetCnt <= g_currentSentCnt)
{
- gTargetCnt = 0;
- gCurrentSentCnt = 0;
+ g_targetCnt = 0;
+ g_currentSentCnt = 0;
- if(gSendBuffer)
+ if (g_sendBuffer)
{
- (*env)->DeleteGlobalRef(env, gSendBuffer);
- gSendBuffer = NULL;
+ (*env)->DeleteGlobalRef(env, g_sendBuffer);
+ g_sendBuffer = NULL;
}
// notity the thread
- u_cond_signal(gThreadCond);
- gIsFinishSendData = TRUE;
+ u_cond_signal(g_threadCond);
+ g_isFinishSendData = TRUE;
OIC_LOG(DEBUG, TAG, "set signal for send data");
}
// mutex unlock
- u_mutex_unlock(gThreadMutex);
+ u_mutex_unlock(g_threadMutex);
+}
+
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CARegisterLeScanCallback(JNIEnv *env, jobject obj,
+ jobject callback)
+{
+ OIC_LOG_V(DEBUG, TAG, "CARegisterLeScanCallback");
+
+ g_leScanCallback = (*env)->NewGlobalRef(env, callback);
+}
+
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CARegisterLeGattCallback(JNIEnv *env, jobject obj,
+ jobject callback)
+{
+ OIC_LOG_V(DEBUG, TAG, "CARegisterLeGattCallback");
+
+ g_leGattCallback = (*env)->NewGlobalRef(env, callback);
+}
+
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeScanCallback(JNIEnv *env, jobject obj, jobject device,
+ jint rssi, jbyteArray scanRecord)
+{
+ CANativeAddScanDeviceToList(env, device);
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattConnectionStateChangeCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattConnectionStateChangeCallback(JNIEnv *env, jobject obj,
+ jobject gatt, jint status,
+ jint newstate)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattConnectionStateChangeCallback - status %d, newstate %d", status,
+ newstate);
+
+ if (GATT_SUCCESS == status && STATE_CONNECTED == newstate) // le connected
+ {
+ if (gatt)
+ {
+ CANativeAddGattobjToList(env, gatt);
+ CANativeLEDiscoverServices(env, gatt);
+ }
+ }
+ else if (GATT_SUCCESS == status && STATE_DISCONNECTED == newstate) // le disconnected
+ {
+
+ }
+ else // other error
+ {
+ CANativeSendFinish(env, gatt);
+ }
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattServicesDiscoveredCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattServicesDiscoveredCallback(JNIEnv *env, jobject obj,
+ jobject gatt, jint status)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattServicesDiscoveredCallback - status %d: ", status);
+
+ if (0 != status) // discovery error
+ {
+ CANativeSendFinish(env, gatt);
+ return;
+ }
+
+ // read Characteristic
+// CANativeReadCharacteristic(env, gatt);
+
+ CAResult_t ret = CANativeSetCharacteristicNotification(env, gatt, IOTIVITY_GATT_RX_UUID);
+ if (CA_STATUS_OK != ret) // SetCharacteristicNoti is failed
+ {
+ CANativeSendFinish(env, gatt);
+ return;
+ }
+
+// jstring data = (*env)->NewStringUTF(env, "HelloWorld");
+ jobject jni_obj_character = CANativeCreateGattCharacteristic(env, gatt, g_sendBuffer);
+ if (!jni_obj_character)
+ {
+ CANativeSendFinish(env, gatt);
+ return;
+ }
+
+ sleep(1);
+ ret = CANativeWriteCharacteristic(env, gatt, jni_obj_character);
+ if (CA_STATUS_FAILED == ret)
+ {
+ CANativeSendFinish(env, gatt);
+ return;
+ }
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattCharacteristicReadCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattCharacteristicReadCallback(JNIEnv *env, jobject obj,
+ jobject gatt,
+ jobject characteristic,
+ jbyteArray data, jint status)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicReadCallback - status : %d", status);
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattCharacteristicWritjclasseCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattCharacteristicWriteCallback(JNIEnv *env, jobject obj,
+ jobject gatt,
+ jobject characteristic,
+ jbyteArray data,
+ jint status)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicWriteCallback - status : %d", status);
+
+ jstring jni_address = CANativeGetAddressFromGattObj(env, gatt);
+ const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+
+ jboolean isCopy;
+ OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicWriteCallback - write data : %s",
+ (char*)(*env)->GetByteArrayElements(env, data, &isCopy));
+
+#ifdef DEBUG_MODE
+ CANativeSendFinish(env, gatt);
+#endif
+
+ if (0 != status) // error case
+ {
+ CANativeSendFinish(env, gatt);
+ }
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattCharacteristicChangedCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattCharacteristicChangedCallback(JNIEnv *env, jobject obj,
+ jobject gatt,
+ jobject characteristic,
+ jbyteArray data)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicChangedCallback");
+
+ // get Byte Array and covert to char*
+ jint length = (*env)->GetArrayLength(env, data);
+
+ jboolean isCopy;
+ jbyte *jni_byte_responseData = (jbyte*) (*env)->GetByteArrayElements(env, data, &isCopy);
+
+ char* recevicedData = (char*) OICMalloc(sizeof(char) * length);
+ if (NULL == recevicedData)
+ {
+ OIC_LOG_V(ERROR, TAG, "recevicedData is null");
+ CANativeSendFinish(env, gatt);
+
+ return;
+ }
+
+ memcpy(recevicedData, (const char*) jni_byte_responseData, length);
+ recevicedData[length] = '\0';
+ (*env)->ReleaseByteArrayElements(env, data, jni_byte_responseData, JNI_ABORT);
+
+ jstring jni_address = CANativeGetAddressFromGattObj(env, gatt);
+ const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
+
+ OIC_LOG_V(DEBUG, TAG, "CALeGattCharacteristicChangedCallback - data. : %s, %d",
+ recevicedData, length);
+
+ // callback
+ g_packetReceiveCallback(address, recevicedData);
+ (*env)->ReleaseStringUTFChars(env, jni_address, address);
+
+ // LE disconnect and finish BLE write routine
+ CANativeSendFinish(env, gatt);
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattDescriptorReadCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattDescriptorReadCallback(JNIEnv *env, jobject obj,
+ jobject gatt, jobject descriptor,
+ jint status)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattDescriptorReadCallback - status %d: ", status);
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattDescriptorWriteCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattDescriptorWriteCallback(JNIEnv *env, jobject obj,
+ jobject gatt,
+ jobject descriptor, jint status)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattDescriptorWriteCallback - status %d: ", status);
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattReliableWriteCompletedCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;I)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattReliableWriteCompletedCallback(JNIEnv *env, jobject obj,
+ jobject gatt,
+ jint status)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattReliableWriteCompletedCallback - status %d: ", status);
+}
+
+/*
+ * Class: com_iotivity_jar_caleinterface
+ * Method: CALeGattReadRemoteRssiCallback
+ * Signature: (Landroid/bluetooth/BluetoothGatt;II)V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattReadRemoteRssiCallback(JNIEnv *env, jobject obj,
+ jobject gatt, jint rssi,
+ jint status)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeGattReadRemoteRssiCallback - rssi %d, status %d: ", rssi, status);
}
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
#include <jni.h>
#include <stdio.h>
#include <android/log.h>
#include "logger.h"
#include "calenwmonitor.h"
#include "caleutils.h"
-#include "com_iotivity_jar_CALeInterface.h"
+#include "com_iotivity_jar_caleinterface.h"
#define TAG PCF("CA_LE_MONITOR")
-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
static JavaVM *g_jvm;
-static jobject gContext;
-static CALENetStateChantedCallback gNetworkChangeCb = NULL;
+static jobject g_context;
+static CALENetStateChantedCallback g_networkChangeCb = NULL;
//getting context
void CALENetworkMonitorJNISetContext(JNIEnv *env, jobject context)
{
OIC_LOG_V(DEBUG, TAG, "CALENetworkMonitorJNISetContext");
- if(context == NULL)
+ if (context == NULL)
+ {
OIC_LOG_V(DEBUG, TAG, "context is null");
+ }
- gContext = (*env)->NewGlobalRef(env, context);
+ g_context = (*env)->NewGlobalRef(env, context);
}
-
//getting jvm
void CALeNetworkMonitorJniInit(JNIEnv *env, JavaVM *jvm)
{
void CALESetNetStateCallback(CALENetStateChantedCallback callback)
{
OIC_LOG_V(DEBUG, TAG, "CALESetNetStateCallback");
- gNetworkChangeCb = callback;
+ g_networkChangeCb = callback;
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeStateChangedCallback
-(JNIEnv *env, jobject obj, jint status)
+Java_com_iotivity_jar_caleinterface_CALeStateChangedCallback(JNIEnv *env, jobject obj, jint status)
{
// STATE_ON:12, STATE_OFF:10
OIC_LOG_V(DEBUG, TAG, "CALeInterface - Network State Changed");
- if(gNetworkChangeCb == NULL)
- OIC_LOG_V(DEBUG, TAG, "gNetworkChangeCb is null", status);
+ if (g_networkChangeCb == NULL)
+ {
+ OIC_LOG_V(DEBUG, TAG, "g_networkChangeCb is null", status);
+ }
jstring jni_address = CALEGetLocalDeviceAddress(env);
const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
- gNetworkChangeCb(localAddress, status);
+ g_networkChangeCb(localAddress, status);
}
+
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
#include <jni.h>
#include <stdio.h>
#include <string.h>
#include <android/log.h>
+#include <unistd.h>
#include "caleserver.h"
#include "caleutils.h"
#include "logger.h"
#include "oic_malloc.h"
#include "uthreadpool.h"
#include "uarraylist.h"
-#include "com_iotivity_jar_CALeInterface.h"
+#include "com_iotivity_jar_caleinterface.h"
#define TAG PCF("CA_LE_SERVER")
-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
/* Service UUID */
-static const char *OIC_GATT_SERVICE_UUID = "713d0000-503e-4c75-ba94-3148f18d941e";
-static const char *OIC_GATT_CHARACTERISTIC_RESPONSE_UUID = "713d0002-503e-4c75-ba94-3148f18d941e"; //read
-static const char *OIC_GATT_CHARACTERISTIC_REQUEST_UUID = "713d0003-503e-4c75-ba94-3148f18d941e"; //write
+static const char OIC_GATT_SERVICE_UUID[] = "713d0000-503e-4c75-ba94-3148f18d941e";
+/* Read */
+static const char OIC_GATT_CHARACTERISTIC_RESPONSE_UUID[] = "713d0002-503e-4c75-ba94-3148f18d941e";
+/* Write */
+static const char OIC_GATT_CHARACTERISTIC_REQUEST_UUID[] = "713d0003-503e-4c75-ba94-3148f18d941e";
static JavaVM *g_jvm;
-static jobject gContext;
-static jobject gBluetoothGattServer;
-static jobject gBluetoothGattServerCallback;
-static jobject gLeAdvertiseCallback;
+static jobject g_context;
+static jobject g_bluetoothGattServer;
+static jobject g_bluetoothGattServerCallback;
+static jobject g_leAdvertiseCallback;
-static CAPacketReceiveCallback gPacketReceiveCallback = NULL;
-static u_arraylist_t *gConnectedDeviceList = NULL;
-static u_thread_pool_t gThreadPoolHandle = NULL;
+static CAPacketReceiveCallback g_packetReceiveCallback = NULL;
+static u_arraylist_t *g_connectedDeviceList = NULL;
+static u_thread_pool_t g_threadPoolHandle = NULL;
-static jboolean gIsStartServer;
-static jboolean gIsSendingMulticastData;
+static jboolean g_isStartServer;
+static jboolean g_isSendingMulticastData;
//getting context
void CALEServerJNISetContext(JNIEnv *env, jobject context)
{
OIC_LOG_V(DEBUG, TAG, "CALEServerJNISetContext");
- if(context == NULL)
- OIC_LOG_V(DEBUG, TAG, "context is null");
+ if (context == NULL)
+ {
+ OIC_LOG_V(ERROR, TAG, "context is null");
+ }
- gContext = (*env)->NewGlobalRef(env, context);
+ g_context = (*env)->NewGlobalRef(env, context);
}
//getting jvm
jobject CANativeLEServerSetResponseData(JNIEnv *env, jbyteArray responseData)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return NULL;
}
OIC_LOG_V(DEBUG, TAG, "CALEServerSetResponseData");
jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattServer");
+ "android/bluetooth/BluetoothGattServer");
- jclass jni_cid_bluetoothGattService = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattService");
+ jclass jni_cid_bluetoothGattService = (*env)->FindClass(
+ env, "android/bluetooth/BluetoothGattService");
- jclass jni_cid_bluetoothGattCharacteristic = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattCharacteristic");
+ jclass jni_cid_bluetoothGattCharacteristic = (*env)->FindClass(
+ env, "android/bluetooth/BluetoothGattCharacteristic");
- jmethodID jni_mid_getService = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattServer, "getService",
+ jmethodID jni_mid_getService = (*env)->GetMethodID(
+ env, jni_cid_bluetoothGattServer, "getService",
"(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattService;");
jobject jni_obj_serviceUUID = CALEGetUuidFromString(env, OIC_GATT_SERVICE_UUID);
- if (!gBluetoothGattServer)
+ if (!g_bluetoothGattServer)
{
- OIC_LOG_V(DEBUG, TAG, "Check BluetoothGattServer status");
+ OIC_LOG_V(ERROR, TAG, "Check BluetoothGattServer status");
return NULL;
}
- jobject jni_obj_bluetoothGattService = (*env)->CallObjectMethod(env,
- gBluetoothGattServer, jni_mid_getService, jni_obj_serviceUUID);
+ jobject jni_obj_bluetoothGattService = (*env)->CallObjectMethod(env, g_bluetoothGattServer,
+ jni_mid_getService,
+ jni_obj_serviceUUID);
- jmethodID jni_mid_getCharacteristic =
- (*env)->GetMethodID(env, jni_cid_bluetoothGattService,
- "getCharacteristic",
- "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattCharacteristic;");
+ jmethodID jni_mid_getCharacteristic = (*env)->GetMethodID(
+ env, jni_cid_bluetoothGattService, "getCharacteristic",
+ "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattCharacteristic;");
jobject jni_obj_responseUUID = CALEGetUuidFromString(env,
- OIC_GATT_CHARACTERISTIC_RESPONSE_UUID);
+ OIC_GATT_CHARACTERISTIC_RESPONSE_UUID);
- jobject jni_obj_bluetoothGattCharacteristic = (*env)->CallObjectMethod(env,
- jni_obj_bluetoothGattService, jni_mid_getCharacteristic,
- jni_obj_responseUUID);
+ jobject jni_obj_bluetoothGattCharacteristic = (*env)->CallObjectMethod(
+ env, jni_obj_bluetoothGattService, jni_mid_getCharacteristic, jni_obj_responseUUID);
- jmethodID jni_mid_setValue = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattCharacteristic, "setValue",
- "([B)Z");
+ jmethodID jni_mid_setValue = (*env)->GetMethodID(env, jni_cid_bluetoothGattCharacteristic,
+ "setValue", "([B)Z");
jboolean jni_boolean_setValue = (*env)->CallBooleanMethod(env,
- jni_obj_bluetoothGattCharacteristic, jni_mid_setValue,
- responseData);
+ jni_obj_bluetoothGattCharacteristic,
+ jni_mid_setValue, responseData);
- if (jni_boolean_setValue == JNI_FALSE) {
- OIC_LOG_V(DEBUG, TAG, "Fail to set response data");
+ if (jni_boolean_setValue == JNI_FALSE)
+ {
+ OIC_LOG_V(ERROR, TAG, "Fail to set response data");
}
return jni_obj_bluetoothGattCharacteristic;
}
-jboolean CANativeLEServerSendResponseData(JNIEnv *env, jobject device, jobject responseData)
+CAResult_t CANativeLEServerSendResponseData(JNIEnv *env, jobject device, jobject responseData)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return JNI_FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_ADAPTER_NOT_ENABLED;
}
OIC_LOG_V(DEBUG, TAG, "CALEServerSendResponseData");
jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattServer");
+ "android/bluetooth/BluetoothGattServer");
- jmethodID jni_mid_notifyCharacteristicChanged =
- (*env)->GetMethodID(env, jni_cid_bluetoothGattServer,
- "notifyCharacteristicChanged",
- "(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z");
+ jmethodID jni_mid_notifyCharacteristicChanged = (*env)->GetMethodID(
+ env, jni_cid_bluetoothGattServer, "notifyCharacteristicChanged",
+ "(Landroid/bluetooth/BluetoothDevice;"
+ "Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z");
- jboolean jni_boolean_notifyCharacteristicChanged =
- (*env)->CallBooleanMethod(env, gBluetoothGattServer,
- jni_mid_notifyCharacteristicChanged, device, responseData,
- JNI_TRUE);
+ jboolean jni_boolean_notifyCharacteristicChanged = (*env)->CallBooleanMethod(
+ env, g_bluetoothGattServer, jni_mid_notifyCharacteristicChanged, device, responseData,
+ JNI_FALSE);
- if (jni_boolean_notifyCharacteristicChanged == JNI_FALSE) {
- OIC_LOG_V(DEBUG, TAG, "Fail to notify characteristic");
+ if (jni_boolean_notifyCharacteristicChanged == JNI_FALSE)
+ {
+ OIC_LOG_V(ERROR, TAG, "Fail to notify characteristic");
+ return CA_SEND_FAILED;
}
- return jni_boolean_notifyCharacteristicChanged;
+ return CA_STATUS_OK;
}
-jboolean CANativeLEServerSendResponse(JNIEnv *env, jobject device, jint requestId, jint status,
- jint offset, jbyteArray value)
+CAResult_t CANativeLEServerSendResponse(JNIEnv *env, jobject device, jint requestId, jint status,
+ jint offset, jbyteArray value)
{
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return JNI_FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_ADAPTER_NOT_ENABLED;
}
OIC_LOG_V(DEBUG, TAG, "CALEServerSendResponse");
jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattServer");
+ "android/bluetooth/BluetoothGattServer");
- jmethodID jni_mid_sendResponse = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattServer, "sendResponse",
+ jmethodID jni_mid_sendResponse = (*env)->GetMethodID(
+ env, jni_cid_bluetoothGattServer, "sendResponse",
"(Landroid/bluetooth/BluetoothDevice;III[B)Z");
- jboolean jni_boolean_sendResponse = (*env)->CallBooleanMethod(env, gBluetoothGattServer,
- jni_mid_sendResponse, device, requestId, status, offset, value);
+ jboolean jni_boolean_sendResponse = (*env)->CallBooleanMethod(env, g_bluetoothGattServer,
+ jni_mid_sendResponse, device,
+ requestId, status, offset, value);
- if (jni_boolean_sendResponse == JNI_FALSE) {
- OIC_LOG_V(DEBUG, TAG, "Fail to send response for gatt characteristic write request");
+ if (jni_boolean_sendResponse == JNI_FALSE)
+ {
+ OIC_LOG_V(ERROR, TAG, "Fail to send response for gatt characteristic write request");
+ return CA_SEND_FAILED;
}
- return jni_boolean_sendResponse;
+ return CA_STATUS_OK;
}
void CANativeLEServerStartAdvertise(JNIEnv *env, jobject advertiseCallback)
OIC_LOG_V(DEBUG, TAG, "LEServerStartAdvertise");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return;
}
- jclass jni_cid_AdvertiseSettings = (*env)->FindClass(env,
- "android/bluetooth/le/AdvertiseSettings$Builder");
+ jclass jni_cid_AdvertiseSettings = (*env)->FindClass(
+ env, "android/bluetooth/le/AdvertiseSettings$Builder");
- jclass jni_cid_AdvertiseDataBuilder = (*env)->FindClass(env,
- "android/bluetooth/le/AdvertiseData$Builder");
+ jclass jni_cid_AdvertiseDataBuilder = (*env)->FindClass(
+ env, "android/bluetooth/le/AdvertiseData$Builder");
- jclass jni_cid_BTAdapter = (*env)->FindClass(env,
- "android/bluetooth/BluetoothAdapter");
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, "android/bluetooth/BluetoothAdapter");
jclass jni_cid_leAdvertiser = (*env)->FindClass(env,
- "android/bluetooth/le/BluetoothLeAdvertiser");
+ "android/bluetooth/le/BluetoothLeAdvertiser");
- jmethodID jni_mid_AdvertiseSettings = (*env)->GetMethodID(env,
- jni_cid_AdvertiseSettings, "<init>", "()V");
+ jmethodID jni_mid_AdvertiseSettings = (*env)->GetMethodID(env, jni_cid_AdvertiseSettings,
+ "<init>", "()V");
- jmethodID jni_mid_setAdvertiseMode = (*env)->GetMethodID(env,
- jni_cid_AdvertiseSettings, "setAdvertiseMode",
- "(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;");
+ jmethodID jni_mid_setAdvertiseMode = (*env)->GetMethodID(
+ env, jni_cid_AdvertiseSettings, "setAdvertiseMode",
+ "(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;");
- jmethodID jni_mid_setConnectable = (*env)->GetMethodID(env,
- jni_cid_AdvertiseSettings, "setConnectable",
+ jmethodID jni_mid_setConnectable = (*env)->GetMethodID(
+ env, jni_cid_AdvertiseSettings, "setConnectable",
"(Z)Landroid/bluetooth/le/AdvertiseSettings$Builder;");
- jmethodID jni_mid_setTimeout = (*env)->GetMethodID(env,
- jni_cid_AdvertiseSettings, "setTimeout",
+ jmethodID jni_mid_setTimeout = (*env)->GetMethodID(
+ env, jni_cid_AdvertiseSettings, "setTimeout",
"(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;");
- jmethodID jni_mid_AdvertiseDataBuilder = (*env)->GetMethodID(env,
- jni_cid_AdvertiseDataBuilder, "<init>", "()V");
+ jmethodID jni_mid_AdvertiseDataBuilder = (*env)->GetMethodID(env, jni_cid_AdvertiseDataBuilder,
+ "<init>", "()V");
- jmethodID jni_mid_addServiceUuid =
- (*env)->GetMethodID(env, jni_cid_AdvertiseDataBuilder,
- "addServiceUuid",
- "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;");
+ jmethodID jni_mid_addServiceUuid = (*env)->GetMethodID(
+ env, jni_cid_AdvertiseDataBuilder, "addServiceUuid",
+ "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;");
- jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env,
- jni_cid_BTAdapter, "getDefaultAdapter",
- "()Landroid/bluetooth/BluetoothAdapter;");
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(
+ env, jni_cid_BTAdapter, "getDefaultAdapter", "()Landroid/bluetooth/BluetoothAdapter;");
- jmethodID jni_mid_getBluetoothLeAdvertiser = (*env)->GetMethodID(env,
- jni_cid_BTAdapter, "getBluetoothLeAdvertiser",
+ jmethodID jni_mid_getBluetoothLeAdvertiser = (*env)->GetMethodID(
+ env, jni_cid_BTAdapter, "getBluetoothLeAdvertiser",
"()Landroid/bluetooth/le/BluetoothLeAdvertiser;");
- jmethodID jni_mid_build_LeAdvertiseSettings = (*env)->GetMethodID(env,
- jni_cid_AdvertiseSettings, "build",
- "()Landroid/bluetooth/le/AdvertiseSettings;");
+ jmethodID jni_mid_build_LeAdvertiseSettings = (*env)->GetMethodID(
+ env, jni_cid_AdvertiseSettings, "build", "()Landroid/bluetooth/le/AdvertiseSettings;");
- jmethodID jni_mid_build_LeAdvertiseData = (*env)->GetMethodID(env,
- jni_cid_AdvertiseDataBuilder, "build",
- "()Landroid/bluetooth/le/AdvertiseData;");
+ jmethodID jni_mid_build_LeAdvertiseData = (*env)->GetMethodID(
+ env, jni_cid_AdvertiseDataBuilder, "build", "()Landroid/bluetooth/le/AdvertiseData;");
- jmethodID jni_mid_startAdvertising =
- (*env)->GetMethodID(env, jni_cid_leAdvertiser, "startAdvertising",
- "(Landroid/bluetooth/le/AdvertiseSettings;Landroid/bluetooth/le/AdvertiseData;Landroid/bluetooth/le/AdvertiseCallback;)V");
+ jmethodID jni_mid_startAdvertising = (*env)->GetMethodID(
+ env, jni_cid_leAdvertiser, "startAdvertising",
+ "(Landroid/bluetooth/le/AdvertiseSettings;Landroid/bluetooth/le/AdvertiseData;"
+ "Landroid/bluetooth/le/AdvertiseCallback;)V");
- jobject jni_AdvertiseSettings = (*env)->NewObject(env,
- jni_cid_AdvertiseSettings, jni_mid_AdvertiseSettings);
+ jobject jni_AdvertiseSettings = (*env)->NewObject(env, jni_cid_AdvertiseSettings,
+ jni_mid_AdvertiseSettings);
- jobject jni_obj_setAdvertiseMode = (*env)->CallObjectMethod(env,
- jni_AdvertiseSettings, jni_mid_setAdvertiseMode, 0); // 0: Low power, 1: Balanced
+ // 0: Low power, 1: Balanced
+ jobject jni_obj_setAdvertiseMode = (*env)->CallObjectMethod(env, jni_AdvertiseSettings,
+ jni_mid_setAdvertiseMode, 0);
- jobject jni_obj_setConnectable = (*env)->CallObjectMethod(env,
- jni_AdvertiseSettings, jni_mid_setConnectable, JNI_TRUE);
+ jobject jni_obj_setConnectable = (*env)->CallObjectMethod(env, jni_AdvertiseSettings,
+ jni_mid_setConnectable, JNI_TRUE);
- jobject jni_obj_setTimeout = (*env)->CallObjectMethod(env,
- jni_AdvertiseSettings, jni_mid_setTimeout, 0); //A value of 0 will disable the time limit
+ //A value of 0 will disable the time limit
+ jobject jni_obj_setTimeout = (*env)->CallObjectMethod(env, jni_AdvertiseSettings,
+ jni_mid_setTimeout, 0);
- jobject jni_AdvertiseDataBuilder = (*env)->NewObject(env,
- jni_cid_AdvertiseDataBuilder, jni_mid_AdvertiseDataBuilder);
+ jobject jni_AdvertiseDataBuilder = (*env)->NewObject(env, jni_cid_AdvertiseDataBuilder,
+ jni_mid_AdvertiseDataBuilder);
jobject jni_obj_serviceUUID = CALEGetUuidFromString(env, OIC_GATT_SERVICE_UUID);
jobject jni_ParcelUuid = CALEGetParcelUuid(env, jni_obj_serviceUUID);
- jobject jni_obj_addServiceUuid = (*env)->CallObjectMethod(env,
- jni_AdvertiseDataBuilder, jni_mid_addServiceUuid, jni_ParcelUuid);
+ jobject jni_obj_addServiceUuid = (*env)->CallObjectMethod(env, jni_AdvertiseDataBuilder,
+ jni_mid_addServiceUuid,
+ jni_ParcelUuid);
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env,
- jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+ jni_mid_getDefaultAdapter);
- jobject jni_obj_getBluetoothLeAdvertiser = (*env)->CallObjectMethod(env,
- jni_obj_BTAdapter, jni_mid_getBluetoothLeAdvertiser);
+ jobject jni_obj_getBluetoothLeAdvertiser = (*env)->CallObjectMethod(
+ env, jni_obj_BTAdapter, jni_mid_getBluetoothLeAdvertiser);
- jobject jni_obj_build_LeAdvertiseSettings = (*env)->CallObjectMethod(env,
- jni_AdvertiseSettings, jni_mid_build_LeAdvertiseSettings);
+ jobject jni_obj_build_LeAdvertiseSettings = (*env)->CallObjectMethod(
+ env, jni_AdvertiseSettings, jni_mid_build_LeAdvertiseSettings);
- jobject jni_obj_build_LeAdvertiseData = (*env)->CallObjectMethod(env,
- jni_AdvertiseDataBuilder, jni_mid_build_LeAdvertiseData);
+ jobject jni_obj_build_LeAdvertiseData = (*env)->CallObjectMethod(env, jni_AdvertiseDataBuilder,
+ jni_mid_build_LeAdvertiseData);
- (*env)->CallVoidMethod(env, jni_obj_getBluetoothLeAdvertiser,
- jni_mid_startAdvertising, jni_obj_build_LeAdvertiseSettings,
- jni_obj_build_LeAdvertiseData, advertiseCallback);
+ (*env)->CallVoidMethod(env, jni_obj_getBluetoothLeAdvertiser, jni_mid_startAdvertising,
+ jni_obj_build_LeAdvertiseSettings, jni_obj_build_LeAdvertiseData,
+ advertiseCallback);
OIC_LOG_V(DEBUG, TAG, "Advertising started!!");
}
OIC_LOG_V(DEBUG, TAG, "LEServerStopAdvertise");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return;
}
- jclass jni_cid_BTAdapter = (*env)->FindClass(env,
- "android/bluetooth/BluetoothAdapter");
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, "android/bluetooth/BluetoothAdapter");
jclass jni_cid_leAdvertiser = (*env)->FindClass(env,
- "android/bluetooth/le/BluetoothLeAdvertiser");
+ "android/bluetooth/le/BluetoothLeAdvertiser");
- jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env,
- jni_cid_BTAdapter, "getDefaultAdapter",
- "()Landroid/bluetooth/BluetoothAdapter;");
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(
+ env, jni_cid_BTAdapter, "getDefaultAdapter", "()Landroid/bluetooth/BluetoothAdapter;");
- jmethodID jni_mid_getBluetoothLeAdvertiser = (*env)->GetMethodID(env,
- jni_cid_BTAdapter, "getBluetoothLeAdvertiser",
+ jmethodID jni_mid_getBluetoothLeAdvertiser = (*env)->GetMethodID(
+ env, jni_cid_BTAdapter, "getBluetoothLeAdvertiser",
"()Landroid/bluetooth/le/BluetoothLeAdvertiser;");
- jmethodID jni_mid_stopAdvertising =
- (*env)->GetMethodID(env, jni_cid_leAdvertiser, "stopAdvertising",
- "(Landroid/bluetooth/le/AdvertiseCallback;)V");
+ jmethodID jni_mid_stopAdvertising = (*env)->GetMethodID(
+ env, jni_cid_leAdvertiser, "stopAdvertising",
+ "(Landroid/bluetooth/le/AdvertiseCallback;)V");
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env,
- jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+ jni_mid_getDefaultAdapter);
- jobject jni_obj_getBluetoothLeAdvertiser = (*env)->CallObjectMethod(env,
- jni_obj_BTAdapter, jni_mid_getBluetoothLeAdvertiser);
+ jobject jni_obj_getBluetoothLeAdvertiser = (*env)->CallObjectMethod(
+ env, jni_obj_BTAdapter, jni_mid_getBluetoothLeAdvertiser);
- (*env)->CallVoidMethod(env, jni_obj_getBluetoothLeAdvertiser,
- jni_mid_stopAdvertising, advertiseCallback);
+ (*env)->CallVoidMethod(env, jni_obj_getBluetoothLeAdvertiser, jni_mid_stopAdvertising,
+ advertiseCallback);
OIC_LOG_V(DEBUG, TAG, "Advertising stopped!!");
}
-jboolean CALEStartGattServer(JNIEnv *env, jobject gattServerCallback)
+CAResult_t CALEStartGattServer(JNIEnv *env, jobject gattServerCallback)
{
OIC_LOG_V(DEBUG, TAG, "CALEStartGattServer");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return JNI_FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_ADAPTER_NOT_ENABLED;
}
- if(gIsStartServer)
+ if (g_isStartServer)
+ {
OIC_LOG_V(DEBUG, TAG, "Gatt server already started");
+ }
- gBluetoothGattServerCallback = (*env)->NewGlobalRef(env, gattServerCallback);
+ g_bluetoothGattServerCallback = (*env)->NewGlobalRef(env, gattServerCallback);
// open gatt server
jobject bluetoothGattServer = CANativeLEServerOpenGattServer(env);
- if(!bluetoothGattServer)
+ if (!bluetoothGattServer)
{
- OIC_LOG_V(DEBUG, TAG, "bluetoothGattServer is null");
- return JNI_FALSE;
+ OIC_LOG_V(ERROR, TAG, "bluetoothGattServer is null");
+ return CA_STATUS_FAILED;
}
- gBluetoothGattServer = (*env)->NewGlobalRef(env, bluetoothGattServer);
+ g_bluetoothGattServer = (*env)->NewGlobalRef(env, bluetoothGattServer);
// create gatt service
jobject bluetoothGattService = CANativeLEServerCreateGattService(env);
// add gatt service
- return CANativeLEServerAddGattService(env, gBluetoothGattServer, bluetoothGattService);
+ return CANativeLEServerAddGattService(env, g_bluetoothGattServer, bluetoothGattService);
}
jobject CANativeLEServerOpenGattServer(JNIEnv *env)
OIC_LOG_V(DEBUG, TAG, "CALEServerOpenGattServer");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return NULL;
}
jclass jni_cid_context = (*env)->FindClass(env, "android/content/Context");
- jclass jni_cid_bluetoothManager = (*env)->FindClass(env,
- "android/bluetooth/BluetoothManager");
+ jclass jni_cid_bluetoothManager = (*env)->FindClass(env, "android/bluetooth/BluetoothManager");
- jfieldID jni_fid_bluetoothService = (*env)->GetStaticFieldID(env,
- jni_cid_context, "BLUETOOTH_SERVICE", "Ljava/lang/String;");
+ jfieldID jni_fid_bluetoothService = (*env)->GetStaticFieldID(env, jni_cid_context,
+ "BLUETOOTH_SERVICE",
+ "Ljava/lang/String;");
- jmethodID jni_mid_getSystemService = (*env)->GetMethodID(env,
- jni_cid_context, "getSystemService",
- "(Ljava/lang/String;)Ljava/lang/Object;");
+ jmethodID jni_mid_getSystemService = (*env)->GetMethodID(
+ env, jni_cid_context, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
- jmethodID jni_mid_openGattServer =
- (*env)->GetMethodID(env, jni_cid_bluetoothManager, "openGattServer",
- "(Landroid/content/Context;Landroid/bluetooth/BluetoothGattServerCallback;)Landroid/bluetooth/BluetoothGattServer;");
+ jmethodID jni_mid_openGattServer = (*env)->GetMethodID(
+ env, jni_cid_bluetoothManager, "openGattServer",
+ "(Landroid/content/Context;Landroid/bluetooth/BluetoothGattServerCallback;)"
+ "Landroid/bluetooth/BluetoothGattServer;");
- jobject jni_obj_bluetoothService = (*env)->GetStaticObjectField(env,
- jni_cid_context, jni_fid_bluetoothService);
- if(!jni_obj_bluetoothService)
+ jobject jni_obj_bluetoothService = (*env)->GetStaticObjectField(env, jni_cid_context,
+ jni_fid_bluetoothService);
+ if (!jni_obj_bluetoothService)
{
- OIC_LOG_V(DEBUG, TAG, "jni_obj_bluetoothService is null");
+ OIC_LOG_V(ERROR, TAG, "jni_obj_bluetoothService is null");
return JNI_FALSE;
}
-
- jobject jni_obj_bluetoothManager = (*env)->CallObjectMethod(env, gContext,
- jni_mid_getSystemService, jni_obj_bluetoothService);
- if(!jni_obj_bluetoothManager)
+ jobject jni_obj_bluetoothManager = (*env)->CallObjectMethod(env, g_context,
+ jni_mid_getSystemService,
+ jni_obj_bluetoothService);
+ if (!jni_obj_bluetoothManager)
{
- OIC_LOG_V(DEBUG, TAG, "jni_obj_bluetoothManager is null");
+ OIC_LOG_V(ERROR, TAG, "jni_obj_bluetoothManager is null");
return JNI_FALSE;
}
- jobject jni_obj_bluetoothGattServer = (*env)->CallObjectMethod(env,
- jni_obj_bluetoothManager, jni_mid_openGattServer, gContext,
- gBluetoothGattServerCallback);
- if(!jni_obj_bluetoothGattServer)
+ jobject jni_obj_bluetoothGattServer = (*env)->CallObjectMethod(env, jni_obj_bluetoothManager,
+ jni_mid_openGattServer,
+ g_context,
+ g_bluetoothGattServerCallback);
+ if (!jni_obj_bluetoothGattServer)
{
- OIC_LOG_V(DEBUG, TAG, "jni_obj_bluetoothGattServer is null");
+ OIC_LOG_V(ERROR, TAG, "jni_obj_bluetoothGattServer is null");
return JNI_FALSE;
}
OIC_LOG_V(DEBUG, TAG, "CALEServerCreateGattService");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return NULL;
}
- jclass jni_cid_bluetoothGattService = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattService");
+ jclass jni_cid_bluetoothGattService = (*env)->FindClass(
+ env, "android/bluetooth/BluetoothGattService");
- jclass jni_cid_bluetoothGattCharacteristic = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattCharacteristic");
+ jclass jni_cid_bluetoothGattCharacteristic = (*env)->FindClass(
+ env, "android/bluetooth/BluetoothGattCharacteristic");
- jfieldID jni_fid_serviceType = (*env)->GetStaticFieldID(env,
- jni_cid_bluetoothGattService, "SERVICE_TYPE_PRIMARY", "I");
+ jfieldID jni_fid_serviceType = (*env)->GetStaticFieldID(env, jni_cid_bluetoothGattService,
+ "SERVICE_TYPE_PRIMARY", "I");
jfieldID jni_fid_readProperties = (*env)->GetStaticFieldID(env,
- jni_cid_bluetoothGattCharacteristic, "PROPERTY_READ", "I");
+ jni_cid_bluetoothGattCharacteristic,
+ "PROPERTY_READ", "I");
jfieldID jni_fid_writeProperties = (*env)->GetStaticFieldID(env,
- jni_cid_bluetoothGattCharacteristic, "PROPERTY_WRITE", "I");
+ jni_cid_bluetoothGattCharacteristic,
+ "PROPERTY_WRITE", "I");
jfieldID jni_fid_readPermissions = (*env)->GetStaticFieldID(env,
- jni_cid_bluetoothGattCharacteristic, "PERMISSION_READ", "I");
+ jni_cid_bluetoothGattCharacteristic,
+ "PERMISSION_READ", "I");
- jfieldID jni_fid_writePermissions = (*env)->GetStaticFieldID(env,
- jni_cid_bluetoothGattCharacteristic, "PERMISSION_WRITE", "I");
+ jfieldID jni_fid_writePermissions = (*env)->GetStaticFieldID(
+ env, jni_cid_bluetoothGattCharacteristic, "PERMISSION_WRITE", "I");
- jmethodID jni_mid_bluetoothGattService = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattService, "<init>", "(Ljava/util/UUID;I)V");
+ jmethodID jni_mid_bluetoothGattService = (*env)->GetMethodID(env, jni_cid_bluetoothGattService,
+ "<init>", "(Ljava/util/UUID;I)V");
- jmethodID jni_mid_addCharacteristic = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattService, "addCharacteristic",
+ jmethodID jni_mid_addCharacteristic = (*env)->GetMethodID(
+ env, jni_cid_bluetoothGattService, "addCharacteristic",
"(Landroid/bluetooth/BluetoothGattCharacteristic;)Z");
- jmethodID jni_mid_bluetoothGattCharacteristic = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattCharacteristic, "<init>",
- "(Ljava/util/UUID;II)V");
+ jmethodID jni_mid_bluetoothGattCharacteristic = (*env)->GetMethodID(
+ env, jni_cid_bluetoothGattCharacteristic, "<init>", "(Ljava/util/UUID;II)V");
jobject jni_obj_serviceUUID = CALEGetUuidFromString(env, OIC_GATT_SERVICE_UUID);
- jobject jni_obj_serviceType = (*env)->GetStaticObjectField(env,
- jni_cid_bluetoothGattService, jni_fid_serviceType);
+ jobject jni_obj_serviceType = (*env)->GetStaticObjectField(env, jni_cid_bluetoothGattService,
+ jni_fid_serviceType);
- jobject jni_bluetoothGattService = (*env)->NewObject(env,
- jni_cid_bluetoothGattService, jni_mid_bluetoothGattService,
- jni_obj_serviceUUID, jni_obj_serviceType);
+ jobject jni_bluetoothGattService = (*env)->NewObject(env, jni_cid_bluetoothGattService,
+ jni_mid_bluetoothGattService,
+ jni_obj_serviceUUID, jni_obj_serviceType);
- jobject jni_obj_readUuid = CALEGetUuidFromString(env,
- OIC_GATT_CHARACTERISTIC_RESPONSE_UUID);
+ jobject jni_obj_readUuid = CALEGetUuidFromString(env, OIC_GATT_CHARACTERISTIC_RESPONSE_UUID);
jint jni_int_readProperties = (*env)->GetStaticIntField(env,
- jni_cid_bluetoothGattCharacteristic, jni_fid_readProperties);
+ jni_cid_bluetoothGattCharacteristic,
+ jni_fid_readProperties);
jint jni_int_readPermissions = (*env)->GetStaticIntField(env,
- jni_cid_bluetoothGattCharacteristic, jni_fid_readPermissions);
+ jni_cid_bluetoothGattCharacteristic,
+ jni_fid_readPermissions);
- jobject jni_readCharacteristic = (*env)->NewObject(env,
- jni_cid_bluetoothGattCharacteristic,
- jni_mid_bluetoothGattCharacteristic, jni_obj_readUuid,
- jni_int_readProperties, jni_int_readPermissions);
+ jobject jni_readCharacteristic = (*env)->NewObject(env, jni_cid_bluetoothGattCharacteristic,
+ jni_mid_bluetoothGattCharacteristic,
+ jni_obj_readUuid, jni_int_readProperties,
+ jni_int_readPermissions);
- jboolean jni_boolean_addReadCharacteristic = (*env)->CallBooleanMethod(env,
- jni_bluetoothGattService, jni_mid_addCharacteristic,
- jni_readCharacteristic);
+ jboolean jni_boolean_addReadCharacteristic = (*env)->CallBooleanMethod(
+ env, jni_bluetoothGattService, jni_mid_addCharacteristic, jni_readCharacteristic);
- jobject jni_obj_writeUuid = CALEGetUuidFromString(env,
- OIC_GATT_CHARACTERISTIC_REQUEST_UUID);
+ jobject jni_obj_writeUuid = CALEGetUuidFromString(env, OIC_GATT_CHARACTERISTIC_REQUEST_UUID);
jint jni_int_writeProperties = (*env)->GetStaticIntField(env,
- jni_cid_bluetoothGattCharacteristic, jni_fid_writeProperties);
+ jni_cid_bluetoothGattCharacteristic,
+ jni_fid_writeProperties);
jint jni_int_writePermissions = (*env)->GetStaticIntField(env,
- jni_cid_bluetoothGattCharacteristic, jni_fid_writePermissions);
+ jni_cid_bluetoothGattCharacteristic,
+ jni_fid_writePermissions);
- jobject jni_writeCharacteristic = (*env)->NewObject(env,
- jni_cid_bluetoothGattCharacteristic,
- jni_mid_bluetoothGattCharacteristic, jni_obj_writeUuid,
- jni_int_writeProperties, jni_int_writePermissions);
+ jobject jni_writeCharacteristic = (*env)->NewObject(env, jni_cid_bluetoothGattCharacteristic,
+ jni_mid_bluetoothGattCharacteristic,
+ jni_obj_writeUuid, jni_int_writeProperties,
+ jni_int_writePermissions);
- jboolean jni_boolean_addWriteCharacteristic = (*env)->CallBooleanMethod(env,
- jni_bluetoothGattService, jni_mid_addCharacteristic,
- jni_writeCharacteristic);
+ jboolean jni_boolean_addWriteCharacteristic = (*env)->CallBooleanMethod(
+ env, jni_bluetoothGattService, jni_mid_addCharacteristic, jni_writeCharacteristic);
if (jni_boolean_addWriteCharacteristic == JNI_FALSE)
{
- OIC_LOG_V(DEBUG, TAG, "Fail to add jni_boolean_addReadCharacteristic");
+ OIC_LOG_V(ERROR, TAG, "Fail to add jni_boolean_addReadCharacteristic");
return NULL;
}
return jni_bluetoothGattService;
}
-jboolean CANativeLEServerAddGattService(JNIEnv *env, jobject bluetoothGattServer,
- jobject bluetoothGattService)
+CAResult_t CANativeLEServerAddGattService(JNIEnv *env, jobject bluetoothGattServer,
+ jobject bluetoothGattService)
{
OIC_LOG_V(DEBUG, TAG, "CALEServerAddGattService");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return JNI_FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_ADAPTER_NOT_ENABLED;
}
jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattServer");
+ "android/bluetooth/BluetoothGattServer");
- jmethodID jni_mid_addService = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattServer, "addService",
+ jmethodID jni_mid_addService = (*env)->GetMethodID(
+ env, jni_cid_bluetoothGattServer, "addService",
"(Landroid/bluetooth/BluetoothGattService;)Z");
jboolean jni_boolean_addService = (*env)->CallBooleanMethod(env, bluetoothGattServer,
- jni_mid_addService, bluetoothGattService);
+ jni_mid_addService,
+ bluetoothGattService);
if (jni_boolean_addService == JNI_FALSE)
{
- OIC_LOG_V(DEBUG, TAG, "Fail to add gatt service");
+ OIC_LOG_V(ERROR, TAG, "Fail to add gatt service");
+ return CA_STATUS_FAILED;
}
- return jni_boolean_addService;
+ return CA_STATUS_OK;
}
-jboolean CANativeLEServerConnect(JNIEnv *env, jobject bluetoothDevice)
+CAResult_t CANativeLEServerConnect(JNIEnv *env, jobject bluetoothDevice)
{
OIC_LOG_V(DEBUG, TAG, "CALEConnect");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return JNI_FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_ADAPTER_NOT_ENABLED;
}
jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattServer");
+ "android/bluetooth/BluetoothGattServer");
- jmethodID jni_mid_connect = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattServer, "connect",
- "(Landroid/bluetooth/BluetoothDevice;Z)Z");
+ jmethodID jni_mid_connect = (*env)->GetMethodID(env, jni_cid_bluetoothGattServer, "connect",
+ "(Landroid/bluetooth/BluetoothDevice;Z)Z");
- jboolean jni_boolean_connect = (*env)->CallBooleanMethod(env,
- gBluetoothGattServer, jni_mid_connect, bluetoothDevice, JNI_FALSE);
+ jboolean jni_boolean_connect = (*env)->CallBooleanMethod(env, g_bluetoothGattServer,
+ jni_mid_connect, bluetoothDevice,
+ JNI_FALSE);
- if(jni_boolean_connect == JNI_FALSE) {
- OIC_LOG_V(DEBUG, TAG, "Fail to connect");
+ if (jni_boolean_connect == JNI_FALSE)
+ {
+ OIC_LOG_V(ERROR, TAG, "Fail to connect");
+ return CA_STATUS_FAILED;
}
- return jni_boolean_connect;
+ return CA_STATUS_OK;
}
void CANativeLEServerDisconnect(JNIEnv *env, jobject bluetoothDevice)
OIC_LOG_V(DEBUG, TAG, "CALEDisconnect");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
return;
}
jclass jni_cid_bluetoothGattServer = (*env)->FindClass(env,
- "android/bluetooth/BluetoothGattServer");
+ "android/bluetooth/BluetoothGattServer");
- jmethodID jni_mid_cancelConnection = (*env)->GetMethodID(env,
- jni_cid_bluetoothGattServer, "cancelConnection",
+ jmethodID jni_mid_cancelConnection = (*env)->GetMethodID(
+ env, jni_cid_bluetoothGattServer, "cancelConnection",
"(Landroid/bluetooth/BluetoothDevice;)V");
- (*env)->CallVoidMethod(env, gBluetoothGattServer, jni_mid_cancelConnection,
- bluetoothDevice);
+ (*env)->CallVoidMethod(env, g_bluetoothGattServer, jni_mid_cancelConnection, bluetoothDevice);
}
-jboolean CALEServerSend(JNIEnv *env, jobject bluetoothDevice, jbyteArray responseData)
+CAResult_t CALEServerSend(JNIEnv *env, jobject bluetoothDevice, jbyteArray responseData)
{
OIC_LOG_V(DEBUG, TAG, "CALESend");
- if(!CALEIsEnableBTAdapter(env))
+ if (!CALEIsEnableBTAdapter(env))
{
- OIC_LOG(DEBUG, TAG, "[BLE][Native] BT adpater is not enable");
- return JNI_FALSE;
+ OIC_LOG(ERROR, TAG, "[BLE][Native] BT adpater is not enable");
+ return CA_ADAPTER_NOT_ENABLED;
}
jobject responseChar = CANativeLEServerSetResponseData(env, responseData);
- jboolean result = CANativeLEServerSendResponseData(env, bluetoothDevice, responseChar);
+ CAResult_t result = CANativeLEServerSendResponseData(env, bluetoothDevice, responseChar);
- if(result == JNI_FALSE)
+ if (result != CA_STATUS_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Fail to send response data");
+ OIC_LOG_V(ERROR, TAG, "Fail to send response data");
+ return result;
}
return result;
{
OIC_LOG_V(DEBUG, TAG, "CALeServerCreateJniInterfaceObject");
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
// initialize le server
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
}
void CALEServerInitialize(u_thread_pool_t handle)
{
OIC_LOG(DEBUG, TAG, "CALEServerInitialize");
- gThreadPoolHandle = handle;
+ g_threadPoolHandle = handle;
- gIsSendingMulticastData = FALSE;
+ g_isSendingMulticastData = JNI_FALSE;
CALEServerCreateCachedDeviceList();
}
{
OIC_LOG(DEBUG, TAG, "CALEServerTerminate");
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
CALEServerStopMulticastServer(0);
CALEServerRemoveAllDevices(env);
- if(gLeAdvertiseCallback)
+ if (g_leAdvertiseCallback)
{
- (*env)->DeleteGlobalRef(env, gLeAdvertiseCallback);
+ (*env)->DeleteGlobalRef(env, g_leAdvertiseCallback);
}
- if(gBluetoothGattServer)
+ if (g_bluetoothGattServer)
{
- (*env)->DeleteGlobalRef(env, gBluetoothGattServer);
+ (*env)->DeleteGlobalRef(env, g_bluetoothGattServer);
}
- if(gBluetoothGattServerCallback)
+ if (g_bluetoothGattServerCallback)
{
- (*env)->DeleteGlobalRef(env, gBluetoothGattServerCallback);
+ (*env)->DeleteGlobalRef(env, g_bluetoothGattServerCallback);
}
- if(gContext)
+ if (g_context)
{
- (*env)->DeleteGlobalRef(env, gContext);
+ (*env)->DeleteGlobalRef(env, g_context);
}
- gIsStartServer = FALSE;
+ g_isStartServer = JNI_FALSE;
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
}
-int32_t CALEServerSendUnicastMessage(const char* address, const char* data, uint32_t dataLen)
+CAResult_t CALEServerSendUnicastMessage(const char* address, const char* data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CALEServerSendUnicastMessage(%s, %s)", address, data);
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return -1;
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
+ return CA_STATUS_FAILED;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
CALEServerSendUnicastMessageImpl(env, address, data, dataLen);
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CALEServerSendMulticastMessage(const char* data, uint32_t dataLen)
+CAResult_t CALEServerSendMulticastMessage(const char* data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CALEServerSendMulticastMessage(%s)", data);
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return -1;
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
+ return CA_STATUS_FAILED;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
CALEServerSendMulticastMessageImpl(env, data, dataLen);
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CALEServerStartUnicastServer(const char* address)
+CAResult_t CALEServerStartUnicastServer(const char* address)
{
OIC_LOG_V(DEBUG, TAG, "CALEServerStartUnicastServer(%s)", address);
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CALEServerStartMulticastServer()
+CAResult_t CALEServerStartMulticastServer()
{
OIC_LOG_V(DEBUG, TAG, "CALEServerStartMulticastServer");
- if(gIsStartServer)
+ if (g_isStartServer)
{
- OIC_LOG_V(DEBUG, TAG, "server is already started..it will be skipped");
- return 0;
+ OIC_LOG_V(ERROR, TAG, "server is already started..it will be skipped");
+ return CA_STATUS_FAILED;
}
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return -1;
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
+ return CA_STATUS_FAILED;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
- gIsStartServer = TRUE;
+ g_isStartServer = JNI_TRUE;
// start gatt server
- if( CALEStartGattServer(env, gBluetoothGattServerCallback) == JNI_FALSE) {
- OIC_LOG_V(DEBUG, TAG, "Fail to start gatt server");
- return -1;
+ CAResult_t ret = CALEStartGattServer(env, g_bluetoothGattServerCallback);
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "Fail to start gatt server");
+ return ret;
}
// start advertise
- CANativeLEServerStartAdvertise(env, gLeAdvertiseCallback);
+ CANativeLEServerStartAdvertise(env, g_leAdvertiseCallback);
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CALEServerStopUnicastServer(int32_t serverID)
+CAResult_t CALEServerStopUnicastServer()
{
OIC_LOG(DEBUG, TAG, "CALEServerStopUnicastServer");
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CALEServerStopMulticastServer(int32_t serverID)
+CAResult_t CALEServerStopMulticastServer()
{
OIC_LOG(DEBUG, TAG, "CALEServerStopMulticastServer");
- if(gIsStartServer == FALSE)
+ if (g_isStartServer == JNI_FALSE)
{
- OIC_LOG_V(DEBUG, TAG, "server is already stopped..it will be skipped");
- return 0;
+ OIC_LOG_V(ERROR, TAG, "server is already stopped..it will be skipped");
+ return CA_STATUS_FAILED;
}
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
- return -1;
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
+ return CA_STATUS_FAILED;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
- CANativeLEServerStopAdvertise(env, gLeAdvertiseCallback);
+ CANativeLEServerStopAdvertise(env, g_leAdvertiseCallback);
- gIsStartServer = FALSE;
+ g_isStartServer = JNI_FALSE;
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
- return 0;
+ return CA_STATUS_OK;
}
void CALEServerSetCallback(CAPacketReceiveCallback callback)
{
OIC_LOG(DEBUG, TAG, "CALEServerSetCallback");
- gPacketReceiveCallback = callback;
+ g_packetReceiveCallback = callback;
}
void CALEServerGetInterfaceInfo(CALocalConnectivity_t **info, uint32_t* size)
{
OIC_LOG(DEBUG, TAG, "CALEServerGetLocalAddress");
- jboolean isAttached = FALSE;
+ jboolean isAttached = JNI_FALSE;
JNIEnv* env;
- jint res = (*g_jvm)->GetEnv(g_jvm, (void**)&env, JNI_VERSION_1_6);
- if(res != JNI_OK)
+ jint res = (*g_jvm)->GetEnv(g_jvm, (void**) &env, JNI_VERSION_1_6);
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "Could not get JNIEnv pointer");
+ OIC_LOG_V(ERROR, TAG, "Could not get JNIEnv pointer");
res = (*g_jvm)->AttachCurrentThread(g_jvm, &env, NULL);
- if(res != JNI_OK)
+ if (res != JNI_OK)
{
- OIC_LOG_V(DEBUG, TAG, "AttachCurrentThread failed");
+ OIC_LOG_V(ERROR, TAG, "AttachCurrentThread failed");
return;
}
- isAttached = TRUE;
+ isAttached = JNI_TRUE;
}
jstring jni_address = CALEGetLocalDeviceAddress(env);
const char* localAddress = (*env)->GetStringUTFChars(env, jni_address, NULL);
+ if (NULL == localAddress)
+ {
+ OIC_LOG_V(ERROR, TAG, "there are no local address");
+ return;
+ }
+
memcpy(address, localAddress, strlen(localAddress));
OIC_LOG_V(DEBUG, TAG, "Local Address : %s", address);
- if(isAttached)
+ if (isAttached)
+ {
(*g_jvm)->DetachCurrentThread(g_jvm);
+ }
}
-int32_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, const char* data,
- uint32_t dataLen)
+CAResult_t CALEServerSendUnicastMessageImpl(JNIEnv *env, const char* address, const char* data,
+ uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CALEServerSendUnicastMessageImpl, address: %s, data: %s", address, data);
jobject jni_obj_bluetoothDevice = NULL;
- if(gConnectedDeviceList == NULL)
+ if (g_connectedDeviceList == NULL)
{
- OIC_LOG(DEBUG, TAG, "gConnectedDeviceList is null");
+ OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
}
- if(gConnectedDeviceList)
+ if (g_connectedDeviceList)
{
jint index;
- for (index = 0; index < u_arraylist_length(gConnectedDeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_connectedDeviceList); index++)
{
OIC_LOG(DEBUG, TAG, "check device address");
- jobject jarrayObj = (jobject) u_arraylist_get(gConnectedDeviceList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "jarrayObj is null");
- return -1;
+ OIC_LOG(ERROR, TAG, "jarrayObj is null");
+ return CA_STATUS_FAILED;
}
jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
- if(!jni_setAddress)
+ if (!jni_setAddress)
{
- OIC_LOG(DEBUG, TAG, "jni_setAddress is null");
- return -1;
+ OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+ return CA_STATUS_FAILED;
}
const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress, NULL);
- if(!strcmp(setAddress, address))
+ if (!strcmp(setAddress, address))
{
OIC_LOG(DEBUG, TAG, "device address matched");
jni_obj_bluetoothDevice = jarrayObj;
jni_obj_bluetoothDevice = jarrayObj;
}
- if(jni_obj_bluetoothDevice)
+ if (jni_obj_bluetoothDevice)
{
jbyteArray jni_bytearr_data = (*env)->NewByteArray(env, dataLen);
- (*env)->SetByteArrayRegion(env, jni_bytearr_data, 0, dataLen, (jbyte*)data);
+ (*env)->SetByteArrayRegion(env, jni_bytearr_data, 0, dataLen, (jbyte*) data);
CALEServerSend(env, jni_obj_bluetoothDevice, jni_bytearr_data);
- } else {
- OIC_LOG(DEBUG, TAG, "jni_obj_bluetoothDevice is null");
+ }
+ else
+ {
+ OIC_LOG(ERROR, TAG, "jni_obj_bluetoothDevice is null");
}
}
- return 0;
+ return CA_STATUS_OK;
}
-int32_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const char* data, uint32_t dataLen)
+CAResult_t CALEServerSendMulticastMessageImpl(JNIEnv *env, const char* data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CALEServerSendMulticastMessageImpl, send to, data: %s", data);
- if(!gConnectedDeviceList)
+ if (!g_connectedDeviceList)
{
- OIC_LOG(DEBUG, TAG, "gConnectedDeviceList is null");
- return 0;
+ OIC_LOG(ERROR, TAG, "g_connectedDeviceList is null");
+ return CA_STATUS_FAILED;
}
// 1. get all the device objects from cache
// 5. disconnect
jint index;
- for (index = 0; index < u_arraylist_length(gConnectedDeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_connectedDeviceList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gConnectedDeviceList, index);
- if(!jarrayObj)
+ jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
+ if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "jarrayObj is null");
- return -1;
+ OIC_LOG(ERROR, TAG, "jarrayObj is null");
+ return CA_STATUS_FAILED;
}
- gIsSendingMulticastData = TRUE;
+ g_isSendingMulticastData = JNI_TRUE;
CANativeLEServerConnect(env, jarrayObj);
sleep(1);
}
- return 0;
-}
-
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CARegisterLeGattServerCallback
- (JNIEnv *env, jobject obj, jobject callback)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeInterface - Register Le Gatt Server Callback");
-
- gBluetoothGattServerCallback = (*env)->NewGlobalRef(env, callback);
-}
-
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CARegisterBluetoothLeAdvertiseCallback
- (JNIEnv *env, jobject obj, jobject callback)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeInterface - Register Le Advertise Callback");
-
- gLeAdvertiseCallback = (*env)->NewGlobalRef(env, callback);
-}
-
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CALeInterface_CALeGattServerConnectionStateChangeCallback
- (JNIEnv *env, jobject obj, jobject device, jint status, jint newState)
-{
- OIC_LOG_V(DEBUG, TAG, "CALeInterface - Gatt Server ConnectionStateChange Callback");
-
- OIC_LOG_V(DEBUG, TAG, "New connection State: %d", newState);
-
- if (!device)
- {
- OIC_LOG(DEBUG, TAG, "device is null");
- return;
- }
-
- jclass jni_cid_bluetoothProfile = (*env)->FindClass(env,
- "android/bluetooth/BluetoothProfile");
-
- jfieldID jni_fid_state_connected = (*env)->GetStaticFieldID(env,
- jni_cid_bluetoothProfile, "STATE_CONNECTED", "I");
-
- jfieldID jni_fid_state_disconnected = (*env)->GetStaticFieldID(env,
- jni_cid_bluetoothProfile, "STATE_DISCONNECTED", "I");
-
- // STATE_CONNECTED
- jint jni_int_state_connected = (*env)->GetStaticIntField(env,
- jni_cid_bluetoothProfile, jni_fid_state_connected);
-
- // STATE_DISCONNECTED
- jint jni_int_state_disconnected = (*env)->GetStaticIntField(env,
- jni_cid_bluetoothProfile, jni_fid_state_disconnected);
-
- if(newState == jni_int_state_connected)
- {
-
- OIC_LOG_V(DEBUG, TAG, "LE CONNECTED");
-
- jstring jni_remoteAddress = CALEGetAddressFromBTDevice(env, device);
- if (!jni_remoteAddress)
- {
- OIC_LOG(DEBUG, TAG, "jni_remoteAddress is null");
- return;
- }
-
- const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
-
- if (gConnectedDeviceList == NULL)
- {
- OIC_LOG_V(DEBUG, TAG, "gConnectedDeviceList is null");
- }
-
- if(CALEServerIsDeviceInList(env, remoteAddress) == JNI_FALSE)
- {
- OIC_LOG_V(DEBUG, TAG, "add connected device to cache");
- CALEServerAddDeviceToList(env, device);
- }
-
-// // temp data
-// if(gIsSendingMulticastData)
-// {
-// OIC_LOG_V(DEBUG, TAG, "send data");
-//
-// const char* data = "HelloWorld~";
-// uint32_t dataLen = strlen(data);
-// jbyteArray jni_bytearr_data = (*env)->NewByteArray(env, dataLen);
-// (*env)->SetByteArrayRegion(env, jni_bytearr_data, 0, dataLen, (jbyte*)data);
-// CALEServerSend(env, device, jni_bytearr_data);
-// gIsSendingMulticastData = FALSE;
-// }
-
-
- }
- else if(newState == jni_int_state_disconnected)
- {
- OIC_LOG_V(DEBUG, TAG, "LE DISCONNECTED");
- }
+ return CA_STATUS_OK;
}
void CALEServerCreateCachedDeviceList()
OIC_LOG(DEBUG, TAG, "CALEServerCreateCachedDeviceList");
// create new object array
- if (gConnectedDeviceList == NULL)
+ if (g_connectedDeviceList == NULL)
{
OIC_LOG_V(DEBUG, TAG, "Create device list");
- gConnectedDeviceList = u_arraylist_create();
+ g_connectedDeviceList = u_arraylist_create();
}
}
{
OIC_LOG(DEBUG, TAG, "CALEServerIsDeviceInList");
- if(gConnectedDeviceList == NULL)
- OIC_LOG(DEBUG, TAG, "list is null");
+ if (g_connectedDeviceList == NULL)
+ OIC_LOG(ERROR, TAG, "list is null");
- uint32_t len = u_arraylist_length(gConnectedDeviceList);
+ uint32_t len = u_arraylist_length(g_connectedDeviceList);
uint32_t index;
- for (index = 0; index < u_arraylist_length(gConnectedDeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_connectedDeviceList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gConnectedDeviceList, index);
+ jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
if (!jarrayObj)
{
- OIC_LOG(DEBUG, TAG, "jarrayObj is null");
- return JNI_TRUE;
+ OIC_LOG(ERROR, TAG, "jarrayObj is null");
+ return JNI_FALSE;
}
jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
if (!jni_setAddress)
{
- OIC_LOG(DEBUG, TAG, "jni_setAddress is null");
- return JNI_TRUE;
+ OIC_LOG(ERROR, TAG, "jni_setAddress is null");
+ return JNI_FALSE;
}
const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress,
- NULL);
+ NULL);
if (!strcmp(remoteAddress, setAddress))
{
{
if (device == NULL)
{
- OIC_LOG(DEBUG, TAG, "device is null");
+ OIC_LOG(ERROR, TAG, "device is null");
return;
}
- if (gConnectedDeviceList == NULL)
+ if (g_connectedDeviceList == NULL)
{
- OIC_LOG(DEBUG, TAG, "list is null");
+ OIC_LOG(ERROR, TAG, "list is null");
return;
}
jstring jni_remoteAddress = CALEGetAddressFromBTDevice(env, device);
if (!jni_remoteAddress)
{
- OIC_LOG(DEBUG, TAG, "jni_remoteAddress is null");
+ OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
return;
}
- const char* remoteAddress = (*env)->GetStringUTFChars(env,
- jni_remoteAddress, NULL);
+ const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
if (CALEServerIsDeviceInList(env, remoteAddress) == JNI_FALSE)
{
jobject gdevice = (*env)->NewGlobalRef(env, device);
- u_arraylist_add(gConnectedDeviceList, gdevice);
+ u_arraylist_add(g_connectedDeviceList, gdevice);
OIC_LOG_V(DEBUG, TAG, "Set Object to Array as Element");
}
}
{
OIC_LOG_V(DEBUG, TAG, "CALEServerRemoveAllDevices");
- if (!gConnectedDeviceList)
+ if (!g_connectedDeviceList)
{
- OIC_LOG(DEBUG, TAG, "no deviceList");
+ OIC_LOG(ERROR, TAG, "no deviceList");
return;
}
uint32_t index;
- for (index = 0; index < u_arraylist_length(gConnectedDeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_connectedDeviceList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gConnectedDeviceList, index);
+ jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
if (jarrayObj)
{
}
}
- OICFree(gConnectedDeviceList);
- gConnectedDeviceList = NULL;
+ OICFree(g_connectedDeviceList);
+ g_connectedDeviceList = NULL;
return;
}
{
OIC_LOG_V(DEBUG, TAG, "CALEServerRemoveDevice");
- if (!gConnectedDeviceList)
+ if (!g_connectedDeviceList)
{
- OIC_LOG(DEBUG, TAG, "no deviceList");
+ OIC_LOG(ERROR, TAG, "no deviceList");
return;
}
uint32_t index;
- for (index = 0; index < u_arraylist_length(gConnectedDeviceList); index++)
+ for (index = 0; index < u_arraylist_length(g_connectedDeviceList); index++)
{
- jobject jarrayObj = (jobject) u_arraylist_get(gConnectedDeviceList, index);
+ jobject jarrayObj = (jobject) u_arraylist_get(g_connectedDeviceList, index);
if (jarrayObj)
{
jstring jni_setAddress = CALEGetAddressFromBTDevice(env, jarrayObj);
if (!jni_setAddress)
{
- OIC_LOG(DEBUG, TAG, "wrong device address");
+ OIC_LOG(ERROR, TAG, "wrong device address");
continue;
}
const char* setAddress = (*env)->GetStringUTFChars(env, jni_setAddress,
- NULL);
+ NULL);
const char* remoteAddress = (*env)->GetStringUTFChars(env, address,
- NULL);
+ NULL);
if (!strcmp(setAddress, remoteAddress))
{
return;
}
}
- }
- OIC_LOG(DEBUG, TAG, "no target object");
+ }OIC_LOG(DEBUG, TAG, "no target object");
return;
}
void CALEServerReorderinglist(uint32_t index)
{
- if (index >= gConnectedDeviceList->length)
+ if (index >= g_connectedDeviceList->length)
return;
- if (index < gConnectedDeviceList->length - 1)
+ if (index < g_connectedDeviceList->length - 1)
{
- memmove(&gConnectedDeviceList->data[index], &gConnectedDeviceList->data[index + 1],
- (gConnectedDeviceList->length - index - 1) * sizeof(void *));
+ memmove(&g_connectedDeviceList->data[index], &g_connectedDeviceList->data[index + 1],
+ (g_connectedDeviceList->length - index - 1) * sizeof(void *));
}
- gConnectedDeviceList->size--;
- gConnectedDeviceList->length--;
+ g_connectedDeviceList->size--;
+ g_connectedDeviceList->length--;
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerServiceAddedCallback
-(JNIEnv *env, jobject obj, jint status, jobject gattService)
+Java_com_iotivity_jar_caleinterface_CALeGattServerServiceAddedCallback(JNIEnv *env, jobject obj,
+ jint status,
+ jobject gattService)
{
OIC_LOG_V(DEBUG, TAG, "CALeInterface - Gatt Service Added Callback(%d)", status);
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerCharacteristicReadRequestCallback
-(JNIEnv *env, jobject obj, jobject device, jint requestId, jint offset, jobject characteristic, jbyteArray data)
+Java_com_iotivity_jar_caleinterface_CALeGattServerCharacteristicReadRequestCallback(
+ JNIEnv *env, jobject obj, jobject device, jint requestId, jint offset,
+ jobject characteristic, jbyteArray data)
{
OIC_LOG_V(DEBUG, TAG, "CALeInterface - Gatt Server Characteristic Read Request Callback");
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerCharacteristicWriteRequestCallback
-(JNIEnv *env, jobject obj, jobject device, jint requestId, jobject characteristic, jbyteArray data,
- jboolean preparedWrite, jboolean responseNeeded, jint offset, jbyteArray value)
+Java_com_iotivity_jar_caleinterface_CALeGattServerCharacteristicWriteRequestCallback(
+ JNIEnv *env, jobject obj, jobject device, jint requestId, jobject characteristic,
+ jbyteArray data, jboolean preparedWrite, jboolean responseNeeded, jint offset,
+ jbyteArray value)
{
OIC_LOG_V(DEBUG, TAG, "CALeInterface - Gatt Server Characteristic Write Request Callback");
CANativeLEServerSendResponse(env, device, requestId, 0, offset, value);
- if(data == NULL)
+ if (data == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "Reqeust data is null");
+ OIC_LOG_V(ERROR, TAG, "Reqeust data is null");
return;
}
jint length = (*env)->GetArrayLength(env, data);
jboolean isCopy;
- jbyte *jni_byte_requestData = (char*)(*env)->GetByteArrayElements(env, data, &isCopy);
+ jbyte *jni_byte_requestData = (jbyte *) (*env)->GetByteArrayElements(env, data, &isCopy);
char* requestData = NULL;
- requestData = (char*) OICMalloc (length + 1);
- memset(requestData, 0, length + 1);
- strncpy(requestData, (char*)jni_byte_requestData, length);
+ requestData = (char*) OICCalloc(1, length + 1);
+ if (NULL == requestData)
+ {
+ OIC_LOG_V(ERROR, TAG, "requestData is null");
+ return;
+ }
+
+ strncpy(requestData, (char*) jni_byte_requestData, length);
requestData[length] = '\0';
(*env)->ReleaseByteArrayElements(env, data, jni_byte_requestData, JNI_ABORT);
const char* address = (*env)->GetStringUTFChars(env, jni_address, NULL);
OIC_LOG_V(DEBUG, TAG, "remote device address : %s", address);
- gPacketReceiveCallback(address, requestData);
+ g_packetReceiveCallback(address, requestData);
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerDescriptorReadRequestCallback
-(JNIEnv *env, jobject obj, jobject device, jint requestId, jint offset, jobject descriptor)
+Java_com_iotivity_jar_caleinterface_CALeGattServerDescriptorReadRequestCallback(JNIEnv *env,
+ jobject obj,
+ jobject device,
+ jint requestId,
+ jint offset,
+ jobject descriptor)
{
OIC_LOG_V(DEBUG, TAG, "CALeInterface_CALeGattServerDescriptorReadRequestCallback");
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerDescriptorWriteRequestCallback
-(JNIEnv *env, jobject obj, jobject device, jint requestId, jobject descriptor,
+Java_com_iotivity_jar_caleinterface_CALeGattServerDescriptorWriteRequestCallback(
+ JNIEnv *env, jobject obj, jobject device, jint requestId, jobject descriptor,
jboolean preparedWrite, jboolean responseNeeded, jint offset, jbyteArray value)
{
OIC_LOG_V(DEBUG, TAG, "CALeInterface_CALeGattServerDescriptorWriteRequestCallback");
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerExecuteWriteCallback
-(JNIEnv *env, jobject obj, jobject device, jint requestId, jboolean execute)
+Java_com_iotivity_jar_caleinterface_CALeGattServerExecuteWriteCallback(JNIEnv *env, jobject obj,
+ jobject device,
+ jint requestId,
+ jboolean execute)
{
OIC_LOG_V(DEBUG, TAG, "CALeInterface_CALeGattServerExecuteWriteCallback");
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerNotificationSentCallback
-(JNIEnv *env, jobject obj, jobject device, jint status)
+Java_com_iotivity_jar_caleinterface_CALeGattServerNotificationSentCallback(JNIEnv *env, jobject obj,
+ jobject device,
+ jint status)
{
OIC_LOG_V(DEBUG, TAG, "CALeInterface - Gatt Server Notification Sent Callback");
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeAdvertiseStartSuccessCallback
-(JNIEnv *env, jobject obj, jobject settingsInEffect)
+Java_com_iotivity_jar_caleinterface_CALeAdvertiseStartSuccessCallback(JNIEnv *env, jobject obj,
+ jobject settingsInEffect)
{
OIC_LOG_V(DEBUG, TAG, "CALeInterface - LE Advertise Start Success Callback");
}
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeAdvertiseStartFailureCallback
-(JNIEnv *env, jobject obj, jint errorCode)
+Java_com_iotivity_jar_caleinterface_CALeAdvertiseStartFailureCallback(JNIEnv *env, jobject obj,
+ jint errorCode)
+{
+ OIC_LOG_V(ERROR, TAG, "CALeInterface - LE Advertise Start Failure Callback(%)", errorCode);
+}
+
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CARegisterLeGattServerCallback(JNIEnv *env, jobject obj,
+ jobject callback)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeInterface - Register Le Gatt Server Callback");
+
+ g_bluetoothGattServerCallback = (*env)->NewGlobalRef(env, callback);
+}
+
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CARegisterBluetoothLeAdvertiseCallback(JNIEnv *env, jobject obj,
+ jobject callback)
{
- OIC_LOG_V(DEBUG, TAG, "CALeInterface - LE Advertise Start Failure Callback(%)", errorCode);
+ OIC_LOG_V(DEBUG, TAG, "CALeInterface - Register Le Advertise Callback");
+
+ g_leAdvertiseCallback = (*env)->NewGlobalRef(env, callback);
+}
+
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_caleinterface_CALeGattServerConnectionStateChangeCallback(JNIEnv *env,
+ jobject obj,
+ jobject device,
+ jint status,
+ jint newState)
+{
+ OIC_LOG_V(DEBUG, TAG, "CALeInterface - Gatt Server ConnectionStateChange Callback");
+
+ OIC_LOG_V(DEBUG, TAG, "New connection State: %d", newState);
+
+ if (!device)
+ {
+ OIC_LOG(ERROR, TAG, "device is null");
+ return;
+ }
+
+ jclass jni_cid_bluetoothProfile = (*env)->FindClass(env, "android/bluetooth/BluetoothProfile");
+
+ jfieldID jni_fid_state_connected = (*env)->GetStaticFieldID(env, jni_cid_bluetoothProfile,
+ "STATE_CONNECTED", "I");
+
+ jfieldID jni_fid_state_disconnected = (*env)->GetStaticFieldID(env, jni_cid_bluetoothProfile,
+ "STATE_DISCONNECTED", "I");
+
+// STATE_CONNECTED
+ jint jni_int_state_connected = (*env)->GetStaticIntField(env, jni_cid_bluetoothProfile,
+ jni_fid_state_connected);
+
+// STATE_DISCONNECTED
+ jint jni_int_state_disconnected = (*env)->GetStaticIntField(env, jni_cid_bluetoothProfile,
+ jni_fid_state_disconnected);
+
+ if (newState == jni_int_state_connected)
+ {
+
+ OIC_LOG_V(DEBUG, TAG, "LE CONNECTED");
+
+ jstring jni_remoteAddress = CALEGetAddressFromBTDevice(env, device);
+ if (!jni_remoteAddress)
+ {
+ OIC_LOG(ERROR, TAG, "jni_remoteAddress is null");
+ return;
+ }
+
+ const char* remoteAddress = (*env)->GetStringUTFChars(env, jni_remoteAddress, NULL);
+
+ if (g_connectedDeviceList == NULL)
+ {
+ OIC_LOG_V(ERROR, TAG, "g_connectedDeviceList is null");
+ }
+
+ if (CALEServerIsDeviceInList(env, remoteAddress) == JNI_FALSE)
+ {
+ OIC_LOG_V(DEBUG, TAG, "add connected device to cache");
+ CALEServerAddDeviceToList(env, device);
+ }
+ }
+ else if (newState == jni_int_state_disconnected)
+ {
+ OIC_LOG_V(DEBUG, TAG, "LE DISCONNECTED");
+ }
}
+/******************************************************************
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
#include <jni.h>
#include <stdio.h>
#include <android/log.h>
#define TAG PCF("CA_LE_UTILS")
-#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
-#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-
#define METHODID_OBJECTNONPARAM "()Landroid/bluetooth/BluetoothAdapter;"
#define METHODID_STRINGNONPARAM "()Ljava/lang/String;"
#define CLASSPATH_BT_ADPATER "android/bluetooth/BluetoothAdapter"
jclass jni_cid_UUID = (*env)->FindClass(env, "java/util/UUID");
- jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(env, jni_cid_UUID,
- "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
+ jmethodID jni_mid_fromString = (*env)->GetStaticMethodID(
+ env, jni_cid_UUID, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;");
jstring str_uuid = (*env)->NewStringUTF(env, uuid);
- jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_UUID,
- jni_mid_fromString, str_uuid);
+ jobject jni_obj_uuid = (*env)->CallStaticObjectMethod(env, jni_cid_UUID, jni_mid_fromString,
+ str_uuid);
if (!jni_obj_uuid)
{
OIC_LOG_V(DEBUG, TAG, "Fail to get jni uuid object");
jclass jni_cid_ParcelUuid = (*env)->FindClass(env, "android/os/ParcelUuid");
- jmethodID jni_mid_ParcelUuid = (*env)->GetMethodID(env, jni_cid_ParcelUuid,
- "<init>", "(Ljava/util/UUID;)V");
+ jmethodID jni_mid_ParcelUuid = (*env)->GetMethodID(env, jni_cid_ParcelUuid, "<init>",
+ "(Ljava/util/UUID;)V");
- jobject jni_ParcelUuid = (*env)->NewObject(env, jni_cid_ParcelUuid,
- jni_mid_ParcelUuid, uuid);
+ jobject jni_ParcelUuid = (*env)->NewObject(env, jni_cid_ParcelUuid, jni_mid_ParcelUuid, uuid);
if (!jni_ParcelUuid)
{
OIC_LOG_V(DEBUG, TAG, "Fail to get jni ParcelUuid");
jstring CALEGetLocalDeviceAddress(JNIEnv* env)
{
- jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
- if(!jni_cid_BTAdapter)
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+ if (!jni_cid_BTAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getAddress: jni_cid_BTAdapter is null");
return NULL;
}
- jmethodID jni_mid_getDefaultAdapter =
- (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
- if(!jni_mid_getDefaultAdapter)
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+ "getDefaultAdapter",
+ METHODID_OBJECTNONPARAM);
+ if (!jni_mid_getDefaultAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getAddress: jni_mid_getDefaultAdapter is null");
return NULL;
}
- jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTAdapter, "getAddress", METHODID_STRINGNONPARAM);
- if(!jni_mid_getAddress)
+ jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_BTAdapter, "getAddress",
+ METHODID_STRINGNONPARAM);
+ if (!jni_mid_getAddress)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getAddress: jni_mid_getAddress is null");
return NULL;
}
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
- if(!jni_obj_BTAdapter)
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+ jni_mid_getDefaultAdapter);
+ if (!jni_obj_BTAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getAddress: jni_obj_BTAdapter is null");
return NULL;
}
- jstring jni_str_address = (jstring)(*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_getAddress);
- if(!jni_str_address)
+ jstring jni_str_address = (jstring)(*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+ jni_mid_getAddress);
+ if (!jni_str_address)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getAddress: jni_str_address is null");
return NULL;
jobjectArray CALEBondedDevices(JNIEnv *env)
{
- jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
- if(!jni_cid_BTAdapter)
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+ if (!jni_cid_BTAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getBondedDevices: jni_cid_BTAdapter is null");
return NULL;
}
- jmethodID jni_mid_getDefaultAdapter =
- (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+ "getDefaultAdapter",
+ METHODID_OBJECTNONPARAM);
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
- if(!jni_obj_BTAdapter)
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+ jni_mid_getDefaultAdapter);
+ if (!jni_obj_BTAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getBondedDevices: bluetooth adapter is null");
return NULL;
// Get a list of currently paired devices
jmethodID jni_mid_getBondedDevices = (*env)->GetMethodID(env, jni_cid_BTAdapter,
- "getBondedDevices", "()Ljava/util/Set;");
- if(!jni_mid_getBondedDevices)
+ "getBondedDevices",
+ "()Ljava/util/Set;");
+ if (!jni_mid_getBondedDevices)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getBondedDevices: jni_mid_getBondedDevicesr is null");
return NULL;
}
- jobject jni_obj_setPairedDevices = (*env)->CallObjectMethod(env, jni_obj_BTAdapter, jni_mid_getBondedDevices);
- if(!jni_obj_setPairedDevices)
+ jobject jni_obj_setPairedDevices = (*env)->CallObjectMethod(env, jni_obj_BTAdapter,
+ jni_mid_getBondedDevices);
+ if (!jni_obj_setPairedDevices)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getBondedDevices: jni_obj_setPairedDevices is null");
return NULL;
// Convert the set to an object array
// object[] array = Set<BluetoothDevice>.toArray();
- jclass jni_cid_Set = (*env)->FindClass(env, "java/util/Set");
- jmethodID jni_mid_toArray = (*env)->GetMethodID(env, jni_cid_Set, "toArray", "()[Ljava/lang/Object;");
+ jclass jni_cid_Set = (*env)->FindClass(env, "java/util/Set");
+ jmethodID jni_mid_toArray = (*env)->GetMethodID(env, jni_cid_Set, "toArray",
+ "()[Ljava/lang/Object;");
- if(!jni_mid_toArray)
+ if (!jni_mid_toArray)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getBondedDevices: jni_mid_toArray is null");
return NULL;
}
- jobjectArray jni_arrayPairedDevices = (jobjectArray)((*env)->CallObjectMethod(env,
- jni_obj_setPairedDevices, jni_mid_toArray));
- if(!jni_arrayPairedDevices)
+ jobjectArray jni_arrayPairedDevices = (jobjectArray)(
+ (*env)->CallObjectMethod(env, jni_obj_setPairedDevices, jni_mid_toArray));
+ if (!jni_arrayPairedDevices)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getBondedDevices: jni_arrayPairedDevices is null");
return NULL;
jint CALEGetBTStateOnInfo(JNIEnv *env)
{
- jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
- if(!jni_cid_BTAdapter)
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+ if (!jni_cid_BTAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] getBTStateOnInfo: jni_cid_BTAdapter is null");
return -1;
jboolean CALEIsEnableBTAdapter(JNIEnv *env)
{
- jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
- if(!jni_cid_BTAdapter)
+ jclass jni_cid_BTAdapter = (*env)->FindClass(env, CLASSPATH_BT_ADPATER);
+ if (!jni_cid_BTAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_BTAdapter: jni_cid_BTAdapter is null");
return FALSE;
}
- jmethodID jni_mid_getDefaultAdapter =
- (*env)->GetStaticMethodID(env, jni_cid_BTAdapter, "getDefaultAdapter", METHODID_OBJECTNONPARAM);
- if(!jni_mid_getDefaultAdapter)
+ jmethodID jni_mid_getDefaultAdapter = (*env)->GetStaticMethodID(env, jni_cid_BTAdapter,
+ "getDefaultAdapter",
+ METHODID_OBJECTNONPARAM);
+ if (!jni_mid_getDefaultAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_getDefaultAdapter is null");
return FALSE;
}
- jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter, jni_mid_getDefaultAdapter);
- if(!jni_obj_BTAdapter)
+ jobject jni_obj_BTAdapter = (*env)->CallStaticObjectMethod(env, jni_cid_BTAdapter,
+ jni_mid_getDefaultAdapter);
+ if (!jni_obj_BTAdapter)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_obj_BTAdapter is null");
return FALSE;
}
// isEnable()
- jmethodID jni_mid_isEnable = (*env)->GetMethodID(env, jni_cid_BTAdapter, "isEnabled",
- "()Z");
- if(!jni_mid_isEnable)
+ jmethodID jni_mid_isEnable = (*env)->GetMethodID(env, jni_cid_BTAdapter, "isEnabled", "()Z");
+ if (!jni_mid_isEnable)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_isEnable is null");
return FALSE;
jstring CALEGetAddressFromBTDevice(JNIEnv *env, jobject bluetoothDevice)
{
jclass jni_cid_device_list = (*env)->FindClass(env, "android/bluetooth/BluetoothDevice");
- if(!jni_cid_device_list)
+ if (!jni_cid_device_list)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_cid_device_list is null");
return NULL;
}
jmethodID jni_mid_getAddress = (*env)->GetMethodID(env, jni_cid_device_list, "getAddress",
- "()Ljava/lang/String;");
- if(!jni_mid_getAddress)
+ "()Ljava/lang/String;");
+ if (!jni_mid_getAddress)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_mid_getAddress is null");
return NULL;
}
- jstring jni_address = (jstring)(*env)->CallObjectMethod(env, bluetoothDevice, jni_mid_getAddress);
- if(!jni_address)
+ jstring jni_address = (jstring)(*env)->CallObjectMethod(env, bluetoothDevice,
+ jni_mid_getAddress);
+ if (!jni_address)
{
OIC_LOG(DEBUG, TAG, "[BLE][Native] jni_address is null");
return NULL;
}
return jni_address;
}
+
-/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
-/* Header for class com_iotivity_jar_CALeInterface */
+/* Header for class com_iotivity_jar_caleinterface */
-#ifndef _Included_com_iotivity_jar_CALeInterface
-#define _Included_com_iotivity_jar_CALeInterface
+#ifndef _Included_com_iotivity_jar_caleinterface
+#define _Included_com_iotivity_jar_caleinterface
#ifdef __cplusplus
-extern "C" {
+extern "C"
+{
#endif
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CARegisterLeScanCallback
* Signature: (Landroid/bluetooth/BluetoothAdapter/LeScanCallback;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CARegisterLeScanCallback
+Java_com_iotivity_jar_caleinterface_CARegisterLeScanCallback
(JNIEnv *, jobject, jobject);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CARegisterLeGattCallback
* Signature: (Landroid/bluetooth/BluetoothGattCallback;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CARegisterLeGattCallback
+Java_com_iotivity_jar_caleinterface_CARegisterLeGattCallback
(JNIEnv *, jobject, jobject);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CARegisterLeGattServerCallback
* Signature: (Landroid/bluetooth/BluetoothGattServerCallback;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CARegisterLeGattServerCallback
+Java_com_iotivity_jar_caleinterface_CARegisterLeGattServerCallback
(JNIEnv *, jobject, jobject);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CARegisterBluetoothLeAdvertiseCallback
* Signature: (Landroid/bluetooth/le/AdvertiseCallback;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CARegisterBluetoothLeAdvertiseCallback
+Java_com_iotivity_jar_caleinterface_CARegisterBluetoothLeAdvertiseCallback
(JNIEnv *, jobject, jobject);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeScanCallback
* Signature: (Landroid/bluetooth/BluetoothDevice;I[B)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeScanCallback
+Java_com_iotivity_jar_caleinterface_CALeScanCallback
(JNIEnv *, jobject, jobject, jint, jbyteArray);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattConnectionStateChangeCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;II)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattConnectionStateChangeCallback
+Java_com_iotivity_jar_caleinterface_CALeGattConnectionStateChangeCallback
(JNIEnv *, jobject, jobject, jint, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServicesDiscoveredCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServicesDiscoveredCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServicesDiscoveredCallback
(JNIEnv *, jobject, jobject, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattCharacteristicReadCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattCharacteristicReadCallback
+Java_com_iotivity_jar_caleinterface_CALeGattCharacteristicReadCallback
(JNIEnv *, jobject, jobject, jobject, jbyteArray, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattCharacteristicWritjclasseCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattCharacteristicWriteCallback
+Java_com_iotivity_jar_caleinterface_CALeGattCharacteristicWriteCallback
(JNIEnv *, jobject, jobject, jobject, jbyteArray, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattCharacteristicChangedCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattCharacteristic;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattCharacteristicChangedCallback
+Java_com_iotivity_jar_caleinterface_CALeGattCharacteristicChangedCallback
(JNIEnv *, jobject, jobject, jobject, jbyteArray);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattDescriptorReadCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattDescriptorReadCallback
+Java_com_iotivity_jar_caleinterface_CALeGattDescriptorReadCallback
(JNIEnv *, jobject, jobject, jobject, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattDescriptorWriteCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;Landroid/bluetooth/BluetoothGattDescriptor;I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattDescriptorWriteCallback
+Java_com_iotivity_jar_caleinterface_CALeGattDescriptorWriteCallback
(JNIEnv *, jobject, jobject, jobject, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattReliableWriteCompletedCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattReliableWriteCompletedCallback
+Java_com_iotivity_jar_caleinterface_CALeGattReliableWriteCompletedCallback
(JNIEnv *, jobject, jobject, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattReadRemoteRssiCallback
* Signature: (Landroid/bluetooth/BluetoothGatt;II)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattReadRemoteRssiCallback
+Java_com_iotivity_jar_caleinterface_CALeGattReadRemoteRssiCallback
(JNIEnv *, jobject, jobject, jint, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServerConnectionStateChangeCallback
* Signature: (Landroid/bluetooth/BluetoothDevice;II)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerConnectionStateChangeCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServerConnectionStateChangeCallback
(JNIEnv *, jobject, jobject, jint, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServerServiceAddedCallback
* Signature: (ILandroid/bluetooth/BluetoothGattService;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerServiceAddedCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServerServiceAddedCallback
(JNIEnv *, jobject, jint, jobject);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServerCharacteristicReadRequestCallback
* Signature: (Landroid/bluetooth/BluetoothDevice;IILandroid/
* bluetooth/BluetoothGattCharacteristic;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerCharacteristicReadRequestCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServerCharacteristicReadRequestCallback
(JNIEnv *, jobject, jobject, jint, jint, jobject, jbyteArray);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServerCharacteristicWriteRequestCallback
* Signature: (Landroid/bluetooth/BluetoothDevice;ILandroid/bluetooth/
* BluetoothGattCharacteristic;ZZI[B)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerCharacteristicWriteRequestCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServerCharacteristicWriteRequestCallback
(JNIEnv *, jobject, jobject, jint, jobject, jbyteArray, jboolean, jboolean, jint, jbyteArray);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServerDescriptorReadRequestCallback
* Signature: (Landroid/bluetooth/BluetoothDevice;IILandroid/bluetooth/
* BluetoothGattDescriptor;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerDescriptorReadRequestCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServerDescriptorReadRequestCallback
(JNIEnv *, jobject, jobject, jint, jint, jobject);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServerDescriptorWriteRequestCallback
* Signature: (Landroid/bluetooth/BluetoothDevice;ILandroid/bluetooth/
* BluetoothGattDescriptor;ZZI[B)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerDescriptorWriteRequestCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServerDescriptorWriteRequestCallback
(JNIEnv *, jobject, jobject, jint, jobject, jboolean, jboolean, jint, jbyteArray);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServerExecuteWriteCallback
* Signature: (Landroid/bluetooth/BluetoothDevice;IZ)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerExecuteWriteCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServerExecuteWriteCallback
(JNIEnv *, jobject, jobject, jint, jboolean);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeGattServerNotificationSentCallback
* Signature: (Landroid/bluetooth/BluetoothDevice;I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeGattServerNotificationSentCallback
+Java_com_iotivity_jar_caleinterface_CALeGattServerNotificationSentCallback
(JNIEnv *, jobject, jobject, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeAdvertiseStartSuccessCallback
* Signature: (Landroid/bluetooth/le/AdvertiseSettings;)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeAdvertiseStartSuccessCallback
+Java_com_iotivity_jar_caleinterface_CALeAdvertiseStartSuccessCallback
(JNIEnv *, jobject, jobject);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeAdvertiseStartFailureCallback
* Signature: (I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeAdvertiseStartFailureCallback
+Java_com_iotivity_jar_caleinterface_CALeAdvertiseStartFailureCallback
(JNIEnv *, jobject, jint);
/*
- * Class: com_iotivity_jar_CALeInterface
+ * Class: com_iotivity_jar_caleinterface
* Method: CALeStateChangedCallback
* Signature: (I)V
*/
JNIEXPORT void JNICALL
-Java_com_iotivity_jar_CALeInterface_CALeStateChangedCallback
+Java_com_iotivity_jar_caleinterface_CALeStateChangedCallback
(JNIEnv *, jobject, jint);
#ifdef __cplusplus
}
#endif
#endif
+
#include "caleadapter_singlethread.h"
#include "caadapterutils.h"
+#include "oic_malloc.h"
/**
* @def TAG
#define TAG "LENW"
/**
- * @var gCALEDeviceStateChangedCallback
+ * @var g_caLEDeviceStateChangedCallback
* @brief Maintains the callback to be notified on device state changed.
*/
-static CALEDeviceStateChangedCallback gCALEDeviceStateChangedCallback = NULL;
+static CALEDeviceStateChangedCallback g_caLEDeviceStateChangedCallback = NULL;
/**
- * @var gLeAddress
+ * @var g_leAddress
* @brief Maintains the local BLE Shield Address
*/
-static unsigned char *gLeAddress = NULL;
+static unsigned char *g_leAddress = NULL;
CAResult_t CALEInitializeNetworkMonitor()
{
OIC_LOG(DEBUG, TAG, "IN");
- if(gLeAddress != NULL)
- {
- memcpy(gLeAddress, 0, CA_MACADDR_SIZE);
- }
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
void CAGetLEAddress(char **leAddress)
{
OIC_LOG(DEBUG, TAG, "IN");
- gLeAddress = ble_getAddress();
+ VERIFY_NON_NULL_VOID(leAddress, TAG, "leAddress");
+
+ g_leAddress = ble_getAddress();
/**
* Below Allocated Memory will be freed by caller API
*/
*leAddress = (char*)OICMalloc(CA_MACADDR_SIZE);
if (NULL == *leAddress)
{
- OIC_LOG(ERROR, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc fail");
return;
}
- memset(*leAddress, 0, CA_MACADDR_SIZE);
- memcpy(*leAddress, gLeAddress, CA_MACADDR_SIZE);
+ memcpy(*leAddress, g_leAddress, CA_MACADDR_SIZE);
OIC_LOG(DEBUG, TAG, "OUT");
return;
}
{
OIC_LOG(DEBUG, TAG, "IN");
- gCALEDeviceStateChangedCallback = callback;
+ g_caLEDeviceStateChangedCallback = callback;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, TAG, "IN");
- gCALEDeviceStateChangedCallback = NULL;
+ g_caLEDeviceStateChangedCallback = NULL;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
+
}
-CAResult_t CAAddNewBleServiceInGattServer(const char *service_uuid)
-{
- // Not Supported - Done at compile time
- return CA_STATUS_OK;
-}
-
-CAResult_t CARemoveBleServiceFromGattServer(const char *svc_path)
-{
- // Not Supported - Done at compile time
- return CA_STATUS_OK;
-}
-
-CAResult_t CARemoveAllBleServicesFromGattServer()
-{
- // Not Supported
- return CA_STATUS_OK;
-}
-
-CAResult_t CARegisterBleServicewithGattServer(const char *svc_path)
-{
- // Not Supported - Done at compile time
- return CA_STATUS_OK;
-}
-
-CAResult_t CAAddNewCharacteristicsToGattServer(const char *svc_path,
- const char *char_uuid,
- const char *char_value,
- int char_value_len,
- int read)
-{
- // Not Supported - Done at compile time
- return CA_STATUS_OK;
-}
-
-CAResult_t CARemoveCharacteristicsFromGattServer(const char *char_path)
-{
- // Not Supported
- return CA_STATUS_OK;
-}
-
unsigned char CAIsBleDataAvailable()
{
return ble_available();
}
CAResult_t CAUpdateCharacteristicsInGattServer(const char *char_value,
- const uint32_t value_length)
+ uint32_t valueLength)
{
+ // ble_write_bytes() api can send only max of 255 bytes at a time
+ // This function shall never be called to send more than 255 bytes by the fragmentation logic.
+ if(valueLength > 255)
+ {
+ OIC_LOG_V(ERROR, TAG, "Error:Max 255");
+ return CA_STATUS_INVALID_PARAM;
+ }
// Currently ble_write_bytes api returns void.
- ble_write_bytes((unsigned char *)char_value, (unsigned char)value_length);
+ ble_write_bytes((unsigned char *)char_value, (unsigned char)valueLength);
return CA_STATUS_OK;
}
+
* @param senderPort [IN] Sender port
* @return #CA_STATUS_OK or Appropriate error code
*/
-void CANotifyCallback(void *data, int32_t dataLen, char *senderAdrs, int32_t senderPort);
-
-/**
- * @brief Adds a new service in Gatt Server
- * @param service_uuid [IN] Unique identifier for each service.
- * @return #CA_STATUS_OK or Appropriate error code
- */
-CAResult_t CAAddNewBleServiceInGattServer(const char *service_uuid);
-
-/**
- * @brief Remove the added service from Ble Gatt server.
- * @param svc_path [IN] Unique identifier for each service.
- * @return #CA_STATUS_OK or Appropriate error code
- */
-CAResult_t CARemoveBleServiceFromGattServer(const char *svc_path);
-
-/**
- * @brief Remove all the services from Ble Gatt server.
- * @return #CA_STATUS_OK or Appropriate error code
- */
-CAResult_t CARemoveAllBleServicesFromGattServer();
-
-/**
- * @brief Register service with GattService after adding the service.
- * @param svc_path [IN] Unique identifier for each service.
- * @return #CA_STATUS_OK or Appropriate error code
- */
-CAResult_t CARegisterBleServicewithGattServer(const char *svc_path);
-
-/**
- * @brief Add new characteristics to the service
- * @param svc_path [IN] Service path to which this characteristic belongs to.
- * @param char_uuid [IN] Gatt characteristic uuid.
- * @param char_value [IN] Gatt characteristic value.
- * @param char_value_len [IN] Characteristic value length.
- * @param read [IN] Boolean variable for checking whether read characteristics or
- * write characteristics.
- * @return #CA_STATUS_OK or Appropriate error code
- */
-CAResult_t CAAddNewCharacteristicsToGattServer(const char *svc_path, const char *char_uuid,
- const char *char_value, int char_value_len,
- int read);
-
-/**
- * @brief Remove the characteristics from BLE GATT server
- * @param char_path [IN] characteristic path registered on the interface and unique
- * identifier for added characteristics.
- * @return #CA_STATUS_OK or Appropriate error code
- */
-CAResult_t CARemoveCharacteristicsFromGattServer(const char *char_path);
+void CANotifyCallback(const void *data, int32_t dataLen, const char *senderAdrs,
+ int32_t senderPort);
/**
* @brief API to check whether data is available in BLE shield
#endif
#endif //#ifndef _BLE_ADAPTER_ARDUINO_H_
+
#include "caadapterutils.h"
#include "caqueueingthread.h"
#include "camsgparser.h"
-
+#include "oic_malloc.h"
/**
* @var CALEADAPTER_TAG
#define CALEADAPTER_TAG "CA_BLE_ADAPTER"
/**
- * @var gNetworkCallback
+ * @var g_networkCallback
* @brief Callback to provide the status of the network change to CA layer.
*/
-static CANetworkChangeCallback gNetworkCallback = NULL;
+static CANetworkChangeCallback g_networkCallback = NULL;
/**
- * @var gLocalBLEAddress
+ * @var g_localBLEAddress
* @brief bleAddress of the local adapter. Value will be initialized to zero, and will be updated later.
*/
-static char gLocalBLEAddress[16] = { 0, };
+static char g_localBLEAddress[16] = { 0, };
/**
- * @var gIsServer
+ * @var g_isServer
* @brief Variable to differentiate btw GattServer and GattClient.
*/
-static CABool_t gIsServer = CA_FALSE;
+static bool g_isServer = false;
/**
- * @var gBleIsServerMutex
+ * @var g_bleIsServerMutex
* @brief Mutex to synchronize the task to be executed on the GattServer function calls.
*/
-static u_mutex gBleIsServerMutex = NULL;
+static u_mutex g_bleIsServerMutex = NULL;
/**
- * @var gBleNetworkCbMutex
+ * @var g_bleNetworkCbMutex
* @brief Mutex to synchronize the callback to be called for the network changes.
*/
-static u_mutex gBleNetworkCbMutex = NULL;
+static u_mutex g_bleNetworkCbMutex = NULL;
/**
- * @var gBleLocalAddressMutex
+ * @var g_bleLocalAddressMutex
* @brief Mutex to synchronize the updation of the local LE address of the adapter.
*/
-static u_mutex gBleLocalAddressMutex = NULL;
+static u_mutex g_bleLocalAddressMutex = NULL;
/**
* @var gBleClientThreadPool
* @brief reference to threadpool
*/
-static u_thread_pool_t gBleAdapterThreadPool = NULL;
+static u_thread_pool_t g_bleAdapterThreadPool = NULL;
/**
- * @var gBleAdapterThreadPoolMutex
+ * @var g_bleAdapterThreadPoolMutex
* @brief Mutex to synchronize the task to be pushed to thread pool.
*/
-static u_mutex gBleAdapterThreadPoolMutex = NULL;
+static u_mutex g_bleAdapterThreadPoolMutex = NULL;
/**
- * @var gBLEClientSendQueueHandle
+ * @var g_bLEClientSendQueueHandle
* @brief Queue to process the outgoing packets from GATTClient.
*/
-static CAQueueingThread_t *gBLEClientSendQueueHandle = NULL;
+static CAQueueingThread_t *g_bLEClientSendQueueHandle = NULL;
/**
- * @var gCABleClientReceiverQueue
+ * @var g_bleClientReceiverQueue
* @brief Queue to process the incoming packets to GATT Client.
*/
-static CAQueueingThread_t *gCABleClientReceiverQueue = NULL;
+static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
/**
- * @var gBleClientSendDataMutex
+ * @var g_bleClientSendDataMutex
* @brief Mutex to synchronize the queing of the data from SenderQueue.
*/
-static u_mutex gBleClientSendDataMutex = NULL;
+static u_mutex g_bleClientSendDataMutex = NULL;
/**
- * @var gBleClientReceiveDataMutex
+ * @var g_bleClientReceiveDataMutex
* @brief Mutex to synchronize the queing of the data from ReceiverQueue.
*/
-static u_mutex gBleClientReceiveDataMutex = NULL;
+static u_mutex g_bleClientReceiveDataMutex = NULL;
/**
- * @var gDataReceiverHandlerState
+ * @var g_dataReceiverHandlerState
* @brief Stop condition of redvhandler.
*/
-static bool gDataReceiverHandlerState = false;
+static bool g_dataReceiverHandlerState = false;
/**
- * @var gSendQueueHandle
+ * @var g_sendQueueHandle
* @brief Queue to process the outgoing packets from GATTServer.
*/
-static CAQueueingThread_t *gSendQueueHandle = NULL;
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
/**
- * @var gCABleServerReceiverQueue
+ * @var g_bleServerReceiverQueue
* @brief Queue to process the incoming packets to GATTServer
*/
-static CAQueueingThread_t *gCABleServerReceiverQueue = NULL;
+static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
/**
- * @var gBleServerSendDataMutex
+ * @var g_bleServerSendDataMutex
* @brief Mutex to synchronize the queing of the data from SenderQueue.
*/
-static u_mutex gBleServerSendDataMutex = NULL;
+static u_mutex g_bleServerSendDataMutex = NULL;
/**
- * @var gBleServerReceiveDataMutex
+ * @var g_bleServerReceiveDataMutex
* @brief Mutex to synchronize the queing of the data from ReceiverQueue.
*/
-static u_mutex gBleServerReceiveDataMutex = NULL;
+static u_mutex g_bleServerReceiveDataMutex = NULL;
/**
- * @var gBleAdapterReqRespCbMutex
+ * @var g_bleAdapterReqRespCbMutex
* @brief Mutex to synchronize the callback to be called for the adapterReqResponse.
*/
-static u_mutex gBleAdapterReqRespCbMutex = NULL;
+static u_mutex g_bleAdapterReqRespCbMutex = NULL;
/**
- * @var gNetworkPacketReceivedCallback
+ * @var g_networkPacketReceivedCallback
* @brief Callback to be called when the network packet recieved from either GattServer or GattClient.
*/
-static CANetworkPacketReceivedCallback gNetworkPacketReceivedCallback = NULL;
+static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
/**
* @ENUM CALeServerStatus
CAResult_t CAInitBleAdapterMutex();
/**
-* @fn CATermiateBleAdapterMutex
+* @fn CATerminateBleAdapterMutex
* @brief Used to terminate all required mutex variable for LE adapter implementation.
*
* @return void
*
*/
-void CATermiateBleAdapterMutex();
+void CATerminateBleAdapterMutex();
static void CALEDataDestroyer(void *data, uint32_t size);
CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
return CA_STATUS_FAILED;
}
- result = CAInitializeLENwkMonitor();
+ result = CAInitializeLENetworkMonitor();
if (CA_STATUS_OK != result)
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "CAInitializeLENwkMonitor() failed");
+ OIC_LOG_V(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
return CA_STATUS_FAILED;
}
connHandler.startAdapter = NULL;
connHandler.stopAdapter = CAStopLE;
connHandler.startListenServer = CAStartLEListeningServer;
- connHandler.startDiscoverServer = CAStartLEDiscoveryServer;
+ connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
connHandler.sendData = CASendLEUnicastData;
connHandler.sendDataToAll = CASendLEMulticastData;
connHandler.GetnetInfo = CAGetLEInterfaceInformation;
CAStopBleQueues();
- u_mutex_lock(gBleIsServerMutex);
- if (CA_TRUE == gIsServer)
+ u_mutex_lock(g_bleIsServerMutex);
+ if (true == g_isServer)
{
CAStopBleGattServer();
}
{
CAStopBLEGattClient();
}
- u_mutex_unlock(gBleIsServerMutex);
+ u_mutex_unlock(g_bleIsServerMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
CASetBLEReqRespClientCallback(NULL);
CALERegisterNetworkNotifications(NULL);
CASetBLEReqRespAdapterCallback(NULL);
- CATerminateLENwkMonitor();
+ CATerminateLENetworkMonitor();
- u_mutex_lock(gBleIsServerMutex);
- if (CA_TRUE == gIsServer)
+ u_mutex_lock(g_bleIsServerMutex);
+ if (true == g_isServer)
{
CATerminateBleGattServer();
}
{
CATerminateBLEGattClient();
}
- u_mutex_unlock(gBleIsServerMutex);
+ u_mutex_unlock(g_bleIsServerMutex);
CATerminateBleQueues();
- CATermiateBleAdapterMutex();
+ CATerminateBleAdapterMutex();
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return;
CAStartBleGattServer();
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- u_mutex_lock(gBleIsServerMutex);
- gIsServer = CA_TRUE;
- u_mutex_unlock(gBleIsServerMutex);
+ u_mutex_lock(g_bleIsServerMutex);
+ g_isServer = true;
+ u_mutex_unlock(g_bleIsServerMutex);
return CA_STATUS_OK;
}
CAStartBLEGattClient();
- u_mutex_lock(gBleIsServerMutex);
- gIsServer = CA_FALSE;
- u_mutex_unlock(gBleIsServerMutex);
+ u_mutex_lock(g_bleIsServerMutex);
+ g_isServer = false;
+ u_mutex_unlock(g_bleIsServerMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
return CA_STATUS_OK;
}
-uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
return CA_STATUS_OK;
}
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
//Input validation
- VERIFY_NON_NULL(endpoint, NULL, "Remote endpoint is null");
- VERIFY_NON_NULL(data, NULL, "Data is null");
+ VERIFY_NON_NULL_RET(endpoint, NULL, "Remote endpoint is null", -1);
+ VERIFY_NON_NULL_RET(data, NULL, "Data is null", -1);
CAResult_t result = CA_STATUS_FAILED;
- u_mutex_lock(gBleIsServerMutex);
- if (CA_TRUE == gIsServer)
+ u_mutex_lock(g_bleIsServerMutex);
+ if (true == g_isServer)
{
result = CABLEServerSendData(endpoint, data, dataLen);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, CALEADAPTER_TAG,
"[SendLEUnicastData] CABleServerSenderQueueEnqueueMessage failed \n");
- u_mutex_unlock(gBleIsServerMutex);
- return 0;
+ u_mutex_unlock(g_bleIsServerMutex);
+ return -1;
}
}
else
{
OIC_LOG(ERROR, CALEADAPTER_TAG,
"[SendLEUnicastData] CABleClientSenderQueueEnqueueMessage failed \n");
- u_mutex_unlock(gBleIsServerMutex);
- return 0;
+ u_mutex_unlock(g_bleIsServerMutex);
+ return -1;
}
}
- u_mutex_unlock(gBleIsServerMutex);
+ u_mutex_unlock(g_bleIsServerMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return dataLen;
}
-uint32_t CASendLEMulticastData(void *data, uint32_t dataLen)
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
//Input validation
- VERIFY_NON_NULL(data, NULL, "Data is null");
+ VERIFY_NON_NULL_RET(data, NULL, "Data is null", -1);
if (0 >= dataLen)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
- return 0;
+ return -1;
}
CAResult_t result = CA_STATUS_FAILED;
- u_mutex_lock(gBleIsServerMutex);
- if (CA_TRUE == gIsServer)
+ u_mutex_lock(g_bleIsServerMutex);
+ if (true == g_isServer)
{
result = CABLEServerSendData(NULL, data, dataLen);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, CALEADAPTER_TAG,
"[SendLEMulticastDataToAll] CABleServerSenderQueueEnqueueMessage failed" );
- u_mutex_unlock(gBleIsServerMutex);
- return 0;
+ u_mutex_unlock(g_bleIsServerMutex);
+ return -1;
}
}
else
{
OIC_LOG(ERROR, CALEADAPTER_TAG,
"[SendLEMulticastDataToAll] CABleClientSenderQueueEnqueueMessage failed" );
- u_mutex_unlock(gBleIsServerMutex);
- return 0;
+ u_mutex_unlock(g_bleIsServerMutex);
+ return -1;
}
}
- u_mutex_unlock(gBleIsServerMutex);
+ u_mutex_unlock(g_bleIsServerMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return dataLen;
}
*size = 0;
- (*info) = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t));
+ (*info) = (CALocalConnectivity_t *) OICCalloc(1, sizeof(CALocalConnectivity_t));
if (NULL == (*info))
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
return CA_STATUS_FAILED;
}
- memset((*info), 0x0, sizeof(CALocalConnectivity_t));
strncpy((*info)->addressInfo.BT.btMacAddress, local_address, strlen(local_address));
- u_mutex_lock(gBleLocalAddressMutex);
- strncpy(gLocalBLEAddress, local_address, sizeof(gLocalBLEAddress));
- u_mutex_unlock(gBleLocalAddressMutex);
+ u_mutex_lock(g_bleLocalAddressMutex);
+ strncpy(g_localBLEAddress, local_address, sizeof(g_localBLEAddress));
+ u_mutex_unlock(g_bleLocalAddressMutex);
(*info)->type = CA_LE;
*size = 1;
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- u_mutex_lock(gBleNetworkCbMutex);
- gNetworkCallback = netCallback;
- u_mutex_unlock(gBleNetworkCbMutex);
+ u_mutex_lock(g_bleNetworkCbMutex);
+ g_networkCallback = netCallback;
+ u_mutex_unlock(g_bleNetworkCbMutex);
if (netCallback)
{
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CALocalConnectivity_t localEndpoint = {{{{0}}}};
+ CALocalConnectivity_t localEndpoint = {};
- u_mutex_lock(gBleLocalAddressMutex);
- strncpy(localEndpoint.addressInfo.BT.btMacAddress, gLocalBLEAddress, strlen(gLocalBLEAddress));
- u_mutex_unlock(gBleLocalAddressMutex);
+ u_mutex_lock(g_bleLocalAddressMutex);
+ strncpy(localEndpoint.addressInfo.BT.btMacAddress, g_localBLEAddress, strlen(g_localBLEAddress));
+ u_mutex_unlock(g_bleLocalAddressMutex);
// Start a GattServer/Client if gLeServerStatus is SET
if (CA_LISTENING_SERVER == gLeServerStatus)
}
gLeServerStatus = CA_SERVER_NOTSTARTED;
- u_mutex_lock(gBleNetworkCbMutex);
- if (NULL != gNetworkCallback)
+ u_mutex_lock(g_bleNetworkCbMutex);
+ if (NULL != g_networkCallback)
{
- gNetworkCallback(&localEndpoint, adapter_state);
+ g_networkCallback(&localEndpoint, adapter_state);
}
else
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "gNetworkCallback is NULL");
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
}
- u_mutex_unlock(gBleNetworkCbMutex);
+ u_mutex_unlock(g_bleNetworkCbMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return;
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- u_mutex_init();
- if (NULL == gBleIsServerMutex)
+ if (NULL == g_bleIsServerMutex)
{
- gBleIsServerMutex = u_mutex_new();
- if (NULL == gBleIsServerMutex)
+ g_bleIsServerMutex = u_mutex_new();
+ if (NULL == g_bleIsServerMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleNetworkCbMutex)
+ if (NULL == g_bleNetworkCbMutex)
{
- gBleNetworkCbMutex = u_mutex_new();
- if (NULL == gBleNetworkCbMutex)
+ g_bleNetworkCbMutex = u_mutex_new();
+ if (NULL == g_bleNetworkCbMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleLocalAddressMutex)
+ if (NULL == g_bleLocalAddressMutex)
{
- gBleLocalAddressMutex = u_mutex_new();
- if (NULL == gBleLocalAddressMutex)
+ g_bleLocalAddressMutex = u_mutex_new();
+ if (NULL == g_bleLocalAddressMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleAdapterThreadPoolMutex)
+ if (NULL == g_bleAdapterThreadPoolMutex)
{
- gBleAdapterThreadPoolMutex = u_mutex_new();
- if (NULL == gBleAdapterThreadPoolMutex)
+ g_bleAdapterThreadPoolMutex = u_mutex_new();
+ if (NULL == g_bleAdapterThreadPoolMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleClientSendDataMutex)
+ if (NULL == g_bleClientSendDataMutex)
{
- gBleClientSendDataMutex = u_mutex_new();
- if (NULL == gBleClientSendDataMutex)
+ g_bleClientSendDataMutex = u_mutex_new();
+ if (NULL == g_bleClientSendDataMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleClientReceiveDataMutex)
+ if (NULL == g_bleClientReceiveDataMutex)
{
- gBleClientReceiveDataMutex = u_mutex_new();
- if (NULL == gBleClientReceiveDataMutex)
+ g_bleClientReceiveDataMutex = u_mutex_new();
+ if (NULL == g_bleClientReceiveDataMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleServerSendDataMutex)
+ if (NULL == g_bleServerSendDataMutex)
{
- gBleServerSendDataMutex = u_mutex_new();
- if (NULL == gBleServerSendDataMutex)
+ g_bleServerSendDataMutex = u_mutex_new();
+ if (NULL == g_bleServerSendDataMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleServerReceiveDataMutex)
+ if (NULL == g_bleServerReceiveDataMutex)
{
- gBleServerReceiveDataMutex = u_mutex_new();
- if (NULL == gBleServerReceiveDataMutex)
+ g_bleServerReceiveDataMutex = u_mutex_new();
+ if (NULL == g_bleServerReceiveDataMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleAdapterReqRespCbMutex)
+ if (NULL == g_bleAdapterReqRespCbMutex)
{
- gBleAdapterReqRespCbMutex = u_mutex_new();
- if (NULL == gBleAdapterReqRespCbMutex)
+ g_bleAdapterReqRespCbMutex = u_mutex_new();
+ if (NULL == g_bleAdapterReqRespCbMutex)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
return CA_STATUS_OK;
}
-void CATermiateBleAdapterMutex()
+void CATerminateBleAdapterMutex()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- u_mutex_free(gBleIsServerMutex);
- gBleIsServerMutex = NULL;
+ u_mutex_free(g_bleIsServerMutex);
+ g_bleIsServerMutex = NULL;
- u_mutex_free(gBleNetworkCbMutex);
- gBleNetworkCbMutex = NULL;
+ u_mutex_free(g_bleNetworkCbMutex);
+ g_bleNetworkCbMutex = NULL;
- u_mutex_free(gBleLocalAddressMutex);
- gBleLocalAddressMutex = NULL;
+ u_mutex_free(g_bleLocalAddressMutex);
+ g_bleLocalAddressMutex = NULL;
- u_mutex_free(gBleAdapterThreadPoolMutex);
- gBleAdapterThreadPoolMutex = NULL;
+ u_mutex_free(g_bleAdapterThreadPoolMutex);
+ g_bleAdapterThreadPoolMutex = NULL;
- u_mutex_free(gBleClientSendDataMutex);
- gBleClientSendDataMutex = NULL;
+ u_mutex_free(g_bleClientSendDataMutex);
+ g_bleClientSendDataMutex = NULL;
- u_mutex_free(gBleClientReceiveDataMutex);
- gBleClientReceiveDataMutex = NULL;
+ u_mutex_free(g_bleClientReceiveDataMutex);
+ g_bleClientReceiveDataMutex = NULL;
- u_mutex_free(gBleServerSendDataMutex);
- gBleServerSendDataMutex = NULL;
+ u_mutex_free(g_bleServerSendDataMutex);
+ g_bleServerSendDataMutex = NULL;
- u_mutex_free(gBleServerReceiveDataMutex);
- gBleServerReceiveDataMutex = NULL;
+ u_mutex_free(g_bleServerReceiveDataMutex);
+ g_bleServerReceiveDataMutex = NULL;
- u_mutex_free(gBleAdapterReqRespCbMutex);
- gBleAdapterReqRespCbMutex = NULL;
+ u_mutex_free(g_bleAdapterReqRespCbMutex);
+ g_bleAdapterReqRespCbMutex = NULL;
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return;
CAResult_t result = CAInitBleServerQueues();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerQueues failed");
return;
}
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- u_mutex_lock(gBleAdapterThreadPoolMutex);
+ u_mutex_lock(g_bleAdapterThreadPoolMutex);
CAResult_t result = CAInitBleServerSenderQueue();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
- u_mutex_unlock(gBleAdapterThreadPoolMutex);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
+ u_mutex_unlock(g_bleAdapterThreadPoolMutex);
return CA_STATUS_FAILED;
}
result = CAInitBleServerReceiverQueue();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
- u_mutex_unlock(gBleAdapterThreadPoolMutex);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
+ u_mutex_unlock(g_bleAdapterThreadPoolMutex);
return CA_STATUS_FAILED;
}
- gDataReceiverHandlerState = true;
+ g_dataReceiverHandlerState = true;
- u_mutex_unlock(gBleAdapterThreadPoolMutex);
+ u_mutex_unlock(g_bleAdapterThreadPoolMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- u_mutex_lock(gBleAdapterThreadPoolMutex);
+ u_mutex_lock(g_bleAdapterThreadPoolMutex);
CAResult_t result = CAInitBleClientSenderQueue();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
- u_mutex_unlock(gBleAdapterThreadPoolMutex);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
+ u_mutex_unlock(g_bleAdapterThreadPoolMutex);
return CA_STATUS_FAILED;
}
result = CAInitBleClientReceiverQueue();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
- u_mutex_unlock(gBleAdapterThreadPoolMutex);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
+ u_mutex_unlock(g_bleAdapterThreadPoolMutex);
return CA_STATUS_FAILED;
}
- gDataReceiverHandlerState = true;
+ g_dataReceiverHandlerState = true;
- u_mutex_unlock(gBleAdapterThreadPoolMutex);
+ u_mutex_unlock(g_bleAdapterThreadPoolMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
// Check if the message queue is already initialized
- if (gSendQueueHandle)
+ if (g_sendQueueHandle)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
return CA_STATUS_OK;
}
// Create send message queue
- gSendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
- if (!gSendQueueHandle)
+ g_sendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_sendQueueHandle)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(gSendQueueHandle, gBleAdapterThreadPool,
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_bleAdapterThreadPool,
CABLEServerSendDataThread, CALEDataDestroyer))
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(gSendQueueHandle);
- gSendQueueHandle = NULL;
+ OICFree(g_sendQueueHandle);
+ g_sendQueueHandle = NULL;
return CA_STATUS_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadStart(gSendQueueHandle))
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "u_thread_pool_add_task failed ");
- OICFree(gSendQueueHandle);
- gSendQueueHandle = NULL;
+ OICFree(g_sendQueueHandle);
+ g_sendQueueHandle = NULL;
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- if (gBLEClientSendQueueHandle)
+ if (g_bLEClientSendQueueHandle)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
return CA_STATUS_OK;
}
// Create send message queue
- gBLEClientSendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
- if (!gBLEClientSendQueueHandle)
+ g_bLEClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_bLEClientSendQueueHandle)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(gBLEClientSendQueueHandle, gBleAdapterThreadPool,
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bLEClientSendQueueHandle, g_bleAdapterThreadPool,
CABLEClientSendDataThread, CALEDataDestroyer))
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(gBLEClientSendQueueHandle);
- gBLEClientSendQueueHandle = NULL;
+ OICFree(g_bLEClientSendQueueHandle);
+ g_bLEClientSendQueueHandle = NULL;
return CA_STATUS_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadStart(gBLEClientSendQueueHandle))
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_bLEClientSendQueueHandle))
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "u_thread_pool_add_task failed ");
- OICFree(gBLEClientSendQueueHandle);
- gBLEClientSendQueueHandle = NULL;
+ OICFree(g_bLEClientSendQueueHandle);
+ g_bLEClientSendQueueHandle = NULL;
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
// Check if the message queue is already initialized
- if (gCABleServerReceiverQueue)
+ if (g_bleServerReceiverQueue)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
return CA_STATUS_OK;
}
// Create send message queue
- gCABleServerReceiverQueue = OICMalloc(sizeof(CAQueueingThread_t));
- if (!gCABleServerReceiverQueue)
+ g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_bleServerReceiverQueue)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
- OICFree(gSendQueueHandle);
+ OICFree(g_sendQueueHandle);
return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(gCABleServerReceiverQueue, gBleAdapterThreadPool,
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue, g_bleAdapterThreadPool,
CABLEServerDataReceiverHandler, CALEDataDestroyer))
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(gCABleServerReceiverQueue);
- gCABleServerReceiverQueue = NULL;
+ OICFree(g_bleServerReceiverQueue);
+ g_bleServerReceiverQueue = NULL;
return CA_STATUS_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadStart(gCABleServerReceiverQueue))
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "u_thread_pool_add_task failed ");
- OICFree(gCABleServerReceiverQueue);
- gCABleServerReceiverQueue = NULL;
+ OICFree(g_bleServerReceiverQueue);
+ g_bleServerReceiverQueue = NULL;
return CA_STATUS_FAILED;
}
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
// Check if the message queue is already initialized
- if (gCABleClientReceiverQueue)
+ if (g_bleClientReceiverQueue)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
}
else
{
// Create send message queue
- gCABleClientReceiverQueue = OICMalloc(sizeof(CAQueueingThread_t));
- if (!gCABleClientReceiverQueue)
+ g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_bleClientReceiverQueue)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
- OICFree(gBLEClientSendQueueHandle);
+ OICFree(g_bLEClientSendQueueHandle);
return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(gCABleClientReceiverQueue, gBleAdapterThreadPool,
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue, g_bleAdapterThreadPool,
CABLEClientDataReceiverHandler, NULL))
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(gBLEClientSendQueueHandle);
- OICFree(gCABleClientReceiverQueue);
- gCABleClientReceiverQueue = NULL;
+ OICFree(g_bLEClientSendQueueHandle);
+ OICFree(g_bleClientReceiverQueue);
+ g_bleClientReceiverQueue = NULL;
return CA_STATUS_FAILED;
}
}
- if (CA_STATUS_OK != CAQueueingThreadStart(gCABleClientReceiverQueue))
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "u_thread_pool_add_task failed ");
- OICFree(gCABleClientReceiverQueue);
- gCABleClientReceiverQueue = NULL;
+ OICFree(g_bleClientReceiverQueue);
+ g_bleClientReceiverQueue = NULL;
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- u_mutex_lock(gBleClientSendDataMutex);
- if (NULL != gBLEClientSendQueueHandle)
+ u_mutex_lock(g_bleClientSendDataMutex);
+ if (NULL != g_bLEClientSendQueueHandle)
{
- CAQueueingThreadStop(gBLEClientSendQueueHandle);
+ CAQueueingThreadStop(g_bLEClientSendQueueHandle);
}
- u_mutex_unlock(gBleClientSendDataMutex);
+ u_mutex_unlock(g_bleClientSendDataMutex);
- u_mutex_lock(gBleClientReceiveDataMutex);
- if (NULL != gCABleClientReceiverQueue)
+ u_mutex_lock(g_bleClientReceiveDataMutex);
+ if (NULL != g_bleClientReceiverQueue)
{
- CAQueueingThreadStop(gCABleClientReceiverQueue);
+ CAQueueingThreadStop(g_bleClientReceiverQueue);
}
- u_mutex_unlock(gBleClientReceiveDataMutex);
+ u_mutex_unlock(g_bleClientReceiveDataMutex);
- u_mutex_lock(gBleServerSendDataMutex);
- if (NULL != gSendQueueHandle)
+ u_mutex_lock(g_bleServerSendDataMutex);
+ if (NULL != g_sendQueueHandle)
{
- CAQueueingThreadStop(gSendQueueHandle);
+ CAQueueingThreadStop(g_sendQueueHandle);
}
- u_mutex_unlock(gBleServerSendDataMutex);
+ u_mutex_unlock(g_bleServerSendDataMutex);
- u_mutex_lock(gBleServerReceiveDataMutex);
- if (NULL != gCABleServerReceiverQueue)
+ u_mutex_lock(g_bleServerReceiveDataMutex);
+ if (NULL != g_bleServerReceiverQueue)
{
- CAQueueingThreadStop(gCABleServerReceiverQueue);
+ CAQueueingThreadStop(g_bleServerReceiverQueue);
}
- u_mutex_unlock(gBleServerReceiveDataMutex);
+ u_mutex_unlock(g_bleServerReceiveDataMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CAQueueingThreadDestroy(gBLEClientSendQueueHandle);
- OICFree(gBLEClientSendQueueHandle);
- gBLEClientSendQueueHandle = NULL;
+ CAQueueingThreadDestroy(g_bLEClientSendQueueHandle);
+ OICFree(g_bLEClientSendQueueHandle);
+ g_bLEClientSendQueueHandle = NULL;
- CAQueueingThreadDestroy(gCABleClientReceiverQueue);
- OICFree(gCABleClientReceiverQueue);
- gCABleClientReceiverQueue = NULL;
+ CAQueueingThreadDestroy(g_bleClientReceiverQueue);
+ OICFree(g_bleClientReceiverQueue);
+ g_bleClientReceiverQueue = NULL;
- CAQueueingThreadDestroy(gSendQueueHandle);
- OICFree(gSendQueueHandle);
- gSendQueueHandle = NULL;
+ CAQueueingThreadDestroy(g_sendQueueHandle);
+ OICFree(g_sendQueueHandle);
+ g_sendQueueHandle = NULL;
- CAQueueingThreadDestroy(gCABleServerReceiverQueue);
- OICFree(gCABleServerReceiverQueue);
- gCABleServerReceiverQueue = NULL;
+ CAQueueingThreadDestroy(g_bleServerReceiverQueue);
+ OICFree(g_bleServerReceiverQueue);
+ g_bleServerReceiverQueue = NULL;
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN");
- // CAAdapterMessage_t *message = NULL;
- static const char *remoteAddress = NULL;
- static const char *serviceUUID = NULL;
static uint32_t recvDataLen = 0;
static uint32_t totalDataLen = 0;
static char *defragData = NULL;
static bool isHeaderAvailable = false;
static CARemoteEndpoint_t *remoteEndpoint = NULL;
- u_mutex_lock(gBleClientReceiveDataMutex);
+ u_mutex_lock(g_bleClientReceiveDataMutex);
- if (gDataReceiverHandlerState)
+ if (g_dataReceiverHandlerState)
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
- CABLEData *bleData = (CABLEData *) threadData;
+ CALEData_t *bleData = (CALEData_t *) threadData;
if (!bleData)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
if (!isHeaderAvailable)
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Parsing the header");
- char *header = (char *) OICMalloc(sizeof(char) * CA_HEADER_LENGTH);
- VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "header is NULL");
-
- memset(header, 0x0, sizeof(char) * CA_HEADER_LENGTH);
- memcpy(header, bleData->data, CA_HEADER_LENGTH);
- totalDataLen = CAParseHeader(header);
+ totalDataLen = CAParseHeader((char*)bleData->data);
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes", totalDataLen);
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%d] bytes", bleData->dataLen);
- defragData = (char *) OICMalloc(sizeof(char) * totalDataLen + 1);
+ defragData = (char *) OICCalloc(totalDataLen + 1, sizeof(char));
if (NULL == defragData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
- OICFree(header);
return;
}
- memset(defragData, 0x0, sizeof(char) * totalDataLen + 1);
- OICFree(header);
- remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
- serviceUUID = bleData->remoteEndpoint->resourceUri;
+ const char *remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
+ const char *serviceUUID = bleData->remoteEndpoint->resourceUri;
remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
serviceUUID);
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength [%d] recveived Datalen [%d]",
totalDataLen, recvDataLen);
}
- if (totalDataLen <= recvDataLen)
+ if (totalDataLen == recvDataLen)
{
- u_mutex_lock(gBleAdapterReqRespCbMutex);
- if (NULL == gNetworkPacketReceivedCallback)
+ u_mutex_lock(g_bleAdapterReqRespCbMutex);
+ if (NULL == g_networkPacketReceivedCallback)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
- u_mutex_unlock(gBleAdapterReqRespCbMutex);
+ u_mutex_unlock(g_bleAdapterReqRespCbMutex);
return;
}
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending data up !");
- gNetworkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
+ g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
recvDataLen = 0;
totalDataLen = 0;
isHeaderAvailable = false;
remoteEndpoint = NULL;
defragData = NULL;
- u_mutex_unlock(gBleAdapterReqRespCbMutex);
+ u_mutex_unlock(g_bleAdapterReqRespCbMutex);
}
- if (false == gDataReceiverHandlerState)
+ if (false == g_dataReceiverHandlerState)
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
recvDataLen = 0;
isHeaderAvailable = false;
OICFree(defragData);
CAAdapterFreeRemoteEndpoint(remoteEndpoint);
- u_mutex_unlock(gBleClientReceiveDataMutex);
+ u_mutex_unlock(g_bleClientReceiveDataMutex);
return;
}
}
- u_mutex_unlock(gBleClientReceiveDataMutex);
+ u_mutex_unlock(g_bleClientReceiveDataMutex);
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT");
}
static bool isHeaderAvailable = false;
static CARemoteEndpoint_t *remoteEndpoint = NULL;
- u_mutex_lock(gBleClientReceiveDataMutex);
+ u_mutex_lock(g_bleClientReceiveDataMutex);
- if (gDataReceiverHandlerState)
+ if (g_dataReceiverHandlerState)
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
- CABLEData *bleData = (CABLEData *) threadData;
+ CALEData_t *bleData = (CALEData_t *) threadData;
if (!bleData)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
if (!isHeaderAvailable)
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Parsing the header");
- char *header = (char *) OICMalloc(sizeof(char) * CA_HEADER_LENGTH);
- VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "header is NULL");
- memcpy(header, bleData->data, CA_HEADER_LENGTH);
- totalDataLen = CAParseHeader(header);
- OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes", totalDataLen);
- OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received in the first packet [%d] bytes", bleData->dataLen);
+ totalDataLen = CAParseHeader(bleData->data);
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes",
+ totalDataLen);
+ OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received in the first packet [%d] bytes",
+ bleData->dataLen);
+
defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
if (NULL == defragData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
- OICFree(header);
return;
}
- OICFree(header);
-
remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
serviceUUID = bleData->remoteEndpoint->resourceUri;
remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
- serviceUUID);
+ serviceUUID);
- memcpy(defragData , bleData->data + CA_HEADER_LENGTH,
+ memcpy(defragData, bleData->data + CA_HEADER_LENGTH,
bleData->dataLen - CA_HEADER_LENGTH);
recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
isHeaderAvailable = true;
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength [%d] recveived Datalen [%d]",
totalDataLen, recvDataLen);
}
- if (totalDataLen <= recvDataLen)
+ if (totalDataLen == recvDataLen)
{
- u_mutex_lock(gBleAdapterReqRespCbMutex);
- if (NULL == gNetworkPacketReceivedCallback)
+ u_mutex_lock(g_bleAdapterReqRespCbMutex);
+ if (NULL == g_networkPacketReceivedCallback)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
- u_mutex_unlock(gBleAdapterReqRespCbMutex);
+ u_mutex_unlock(g_bleAdapterReqRespCbMutex);
return;
}
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending data up !");
- gNetworkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
+ g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
recvDataLen = 0;
totalDataLen = 0;
isHeaderAvailable = false;
remoteEndpoint = NULL;
defragData = NULL;
- u_mutex_unlock(gBleAdapterReqRespCbMutex);
+ u_mutex_unlock(g_bleAdapterReqRespCbMutex);
}
- if (false == gDataReceiverHandlerState)
+ if (false == g_dataReceiverHandlerState)
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
OICFree(defragData);
CAAdapterFreeRemoteEndpoint(remoteEndpoint);
- u_mutex_unlock(gBleClientReceiveDataMutex);
+ u_mutex_unlock(g_bleClientReceiveDataMutex);
return;
}
}
- u_mutex_unlock(gBleClientReceiveDataMutex);
+ u_mutex_unlock(g_bleClientReceiveDataMutex);
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "OUT");
}
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CABLEData *bleData = (CABLEData *) threadData;
+ CALEData_t *bleData = (CALEData_t *) threadData;
if (!bleData)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
return;
}
- char *header = (char *) OICMalloc(sizeof(char) * CA_HEADER_LENGTH);
+
+ char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
- char *dataSegment = (char *) OICMalloc(sizeof(char) * bleData->dataLen + CA_HEADER_LENGTH + 1);
+ char *dataSegment = (char *) OICCalloc(bleData->dataLen + CA_HEADER_LENGTH + 1, sizeof(char));
if (NULL == dataSegment)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
return;
}
- memset(header, 0x0, sizeof(char) * CA_HEADER_LENGTH );
- memset(dataSegment, 0x0, sizeof(char) * bleData->dataLen + CA_HEADER_LENGTH + 1 );
-
CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
if (CA_STATUS_OK != result )
{
int32_t iter = bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
int32_t index = 0;
- u_mutex_lock(gBleServerSendDataMutex);
+ u_mutex_lock(g_bleServerSendDataMutex);
// Send the first segment with the header.
result = CAUpdateCharacteristicsInGattServer(dataSegment, length);
- if (CA_STATUS_OK != result)
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleServerSendDataMutex);
- return;
+ u_mutex_unlock(g_bleServerSendDataMutex);
+ return ;
}
-
+
for (index = 1; index < iter; index++)
{
// Send the remaining header.
result = CAUpdateCharacteristicsInGattServer(
bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
CA_SUPPORTED_BLE_MTU_SIZE);
- if (CA_STATUS_OK != result)
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleServerSendDataMutex);
- return;
+ u_mutex_unlock(g_bleServerSendDataMutex);
+ return ;
}
}
+
if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
{
// send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
result = CAUpdateCharacteristicsInGattServer(
bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH);
- if (CA_STATUS_OK != result)
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleServerSendDataMutex);
- return;
+ u_mutex_unlock(g_bleServerSendDataMutex);
+ return ;
}
}
OICFree(dataSegment);
- u_mutex_unlock(gBleServerSendDataMutex); // TODO: this mutex required ?
+ u_mutex_unlock(g_bleServerSendDataMutex); // TODO: this mutex required ?
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return;
-
}
void CABLEClientSendDataThread(void *threadData)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- CABLEData *bleData = (CABLEData *) threadData;
+ CALEData_t *bleData = (CALEData_t *) threadData;
if (!bleData)
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
return;
}
- char *header = (char *) OICMalloc(sizeof(char) * CA_HEADER_LENGTH);
+
+ char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
- char *dataSegment = (char *) OICMalloc(sizeof(char) * bleData->dataLen + CA_HEADER_LENGTH + 1);
+ char *dataSegment = (char *) OICCalloc(bleData->dataLen + CA_HEADER_LENGTH + 1, sizeof(char));
if (NULL == dataSegment)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
return;
}
- memset(header, 0x0, sizeof(char) * CA_HEADER_LENGTH );
- memset(dataSegment, 0x0, sizeof(char) * bleData->dataLen + CA_HEADER_LENGTH + 1);
-
CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
if (CA_STATUS_OK != result )
{
int32_t iter = bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
int32_t index = 0;
- u_mutex_lock(gBleClientSendDataMutex);
+ u_mutex_lock(g_bleClientSendDataMutex);
if (NULL != bleData->remoteEndpoint)
{
// Send the first segment with the header.
result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
dataSegment,
length,
- UNICAST, 0);
- if (CA_STATUS_OK != result)
+ LE_UNICAST, 0);
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleClientSendDataMutex);
+ u_mutex_unlock(g_bleClientSendDataMutex);
return ;
}
+
for (index = 1; index < iter; index++)
{
// Send the remaining header.
result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
CA_SUPPORTED_BLE_MTU_SIZE,
- UNICAST, 0);
- if (CA_STATUS_OK != result)
+ LE_UNICAST, 0);
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
- result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleClientSendDataMutex);
- return;
+ u_mutex_unlock(g_bleClientSendDataMutex);
+ return ;
}
}
+
if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
{
// send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH,
- UNICAST, 0);
- if (CA_STATUS_OK != result)
+ LE_UNICAST, 0);
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
- result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleClientSendDataMutex);
- return;
+ u_mutex_unlock(g_bleClientSendDataMutex);
+ return ;
}
}
}
// Send the first segment with the header.
result = CAUpdateCharacteristicsToAllGattServers(dataSegment + (index * length),
length);
- if (CA_STATUS_OK != result)
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed (all), result [%d]",
- result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleClientSendDataMutex);
+ u_mutex_unlock(g_bleClientSendDataMutex);
return ;
}
// Send the remaining header.
result = CAUpdateCharacteristicsToAllGattServers(
bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
CA_SUPPORTED_BLE_MTU_SIZE);
- if (CA_STATUS_OK != result)
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]",
- result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleClientSendDataMutex);
- return;
+ u_mutex_unlock(g_bleClientSendDataMutex);
+ return ;
}
}
if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
result = CAUpdateCharacteristicsToAllGattServers(
bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH);
- if (CA_STATUS_OK != result)
+ if (CA_STATUS_OK != result )
{
- OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]",
- result);
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
OICFree(dataSegment);
- u_mutex_unlock(gBleClientSendDataMutex);
- return;
+ u_mutex_unlock(g_bleClientSendDataMutex);
+ return ;
}
}
}
OICFree(dataSegment);
- u_mutex_unlock(gBleClientSendDataMutex);
+ u_mutex_unlock(g_bleClientSendDataMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
- return;
}
-CABLEData *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength)
{
- CABLEData *bleData = (CABLEData *) OICMalloc(sizeof(CABLEData));
+ CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
if (!bleData)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
}
bleData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
- bleData->data = (void *)OICMalloc(dataLength + 1);
+ bleData->data = (void *)OICCalloc(dataLength + 1, 1);
if (NULL == bleData->data)
{
OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
CAFreeBLEData(bleData);
return NULL;
}
- memset(bleData->data, 0x0, dataLength+1);
memcpy(bleData->data, data, dataLength);
bleData->dataLen = dataLength;
return bleData;
}
-void CAFreeBLEData(CABLEData *bleData)
+void CAFreeBLEData(CALEData_t *bleData)
{
if (!bleData)
return;
void CALEDataDestroyer(void *data, uint32_t size)
{
- CABLEData *ledata = (CABLEData *) data;
+ CALEData_t *ledata = (CALEData_t *) data;
CAFreeBLEData(ledata);
}
CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
- void *data,
+ const void *data,
uint32_t dataLen)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN ");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
VERIFY_NON_NULL(data, NULL, "Param data is NULL");
- VERIFY_NON_NULL_RET(gBLEClientSendQueueHandle, CALEADAPTER_TAG,
- "gBLEClientSendQueueHandle is NULL",
+ VERIFY_NON_NULL_RET(g_bLEClientSendQueueHandle, CALEADAPTER_TAG,
+ "g_bLEClientSendQueueHandle is NULL",
CA_STATUS_FAILED);
- VERIFY_NON_NULL_RET(gBleClientSendDataMutex, CALEADAPTER_TAG,
- "gBleClientSendDataMutex is NULL",
+ VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
+ "g_bleClientSendDataMutex is NULL",
CA_STATUS_FAILED);
- VERIFY_NON_NULL_RET(gBLEClientSendQueueHandle, CALEADAPTER_TAG, "gBLEClientSendQueueHandle",
+ VERIFY_NON_NULL_RET(g_bLEClientSendQueueHandle, CALEADAPTER_TAG, "g_bLEClientSendQueueHandle",
CA_STATUS_FAILED);
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
- CABLEData *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
+ CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
if (!bleData)
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
return CA_MEMORY_ALLOC_FAILED;
}
// Add message to send queue
- u_mutex_lock(gBleClientSendDataMutex);
- CAQueueingThreadAddData(gBLEClientSendQueueHandle, bleData, sizeof(CABLEData));
- u_mutex_unlock(gBleClientSendDataMutex);
+ u_mutex_lock(g_bleClientSendDataMutex);
+ CAQueueingThreadAddData(g_bLEClientSendQueueHandle, bleData, sizeof(CALEData_t));
+ u_mutex_unlock(g_bleClientSendDataMutex);
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT ");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
- void *data,
+ const void *data,
uint32_t dataLen)
{
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN ");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
VERIFY_NON_NULL(data, NULL, "Param data is NULL");
- VERIFY_NON_NULL_RET(gSendQueueHandle, CALEADAPTER_TAG,
- "BleClientReceiverQueue is NULL",
+ VERIFY_NON_NULL_RET(g_sendQueueHandle, CALEADAPTER_TAG,
+ "BleClientReceiverQueue is NULL",
CA_STATUS_FAILED);
- VERIFY_NON_NULL_RET(gBleClientSendDataMutex, CALEADAPTER_TAG,
+ VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
"BleClientSendDataMutex is NULL",
CA_STATUS_FAILED);
- VERIFY_NON_NULL_RET(gSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
+ VERIFY_NON_NULL_RET(g_sendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
CA_STATUS_FAILED);
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
- CABLEData *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
+ CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
if (!bleData)
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
return CA_MEMORY_ALLOC_FAILED;
}
// Add message to send queue
- u_mutex_lock(gBleServerSendDataMutex);
- CAQueueingThreadAddData(gSendQueueHandle, bleData, sizeof(CABLEData));
- u_mutex_unlock(gBleServerSendDataMutex);
+ u_mutex_lock(g_bleServerSendDataMutex);
+ CAQueueingThreadAddData(g_sendQueueHandle, bleData, sizeof(CALEData_t));
+ u_mutex_unlock(g_bleServerSendDataMutex);
- OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT ");
+ OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CABLEServerReceivedData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength)
+ const void *data, uint32_t dataLength, uint32_t *sentLength)
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN");
VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
- VERIFY_NON_NULL_RET(gCABleServerReceiverQueue, CALEADAPTER_TAG, "gCABleServerReceiverQueue",
+ VERIFY_NON_NULL_RET(g_bleServerReceiverQueue, CALEADAPTER_TAG, "g_bleServerReceiverQueue",
CA_STATUS_FAILED);
//Add message to data queue
// Create bleData to add to queue
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
- CABLEData *bleData = CACreateBLEData(remoteEndpoint, data, dataLength);
+ CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLength);
if (!bleData)
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
CAAdapterFreeRemoteEndpoint(remoteEndpoint);
// Add message to send queue
- CAQueueingThreadAddData(gCABleServerReceiverQueue, bleData, sizeof(CABLEData));
+ CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
*sentLength = dataLength;
}
CAResult_t CABLEClientReceivedData(const char *remoteAddress, const char *serviceUUID,
- void *data, uint32_t dataLength, uint32_t *sentLength)
+ const void *data, uint32_t dataLength, uint32_t *sentLength)
{
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "IN");
VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
- VERIFY_NON_NULL_RET(gCABleClientReceiverQueue, CALEADAPTER_TAG, "gCABleClientReceiverQueue",
+ VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG, "g_bleClientReceiverQueue",
CA_STATUS_FAILED);
//Add message to data queue
OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
// Create bleData to add to queue
- CABLEData *bleData = CACreateBLEData(remoteEndpoint, data, dataLength);
+ CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLength);
if (!bleData)
{
OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
CAAdapterFreeRemoteEndpoint(remoteEndpoint);
// Add message to send queue
- CAQueueingThreadAddData(gCABleClientReceiverQueue, bleData, sizeof(CABLEData));
+ CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
*sentLength = dataLength;
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- u_mutex_unlock(gBleAdapterThreadPoolMutex);
- gBleAdapterThreadPool = handle;
- u_mutex_unlock(gBleAdapterThreadPoolMutex);
+ u_mutex_unlock(g_bleAdapterThreadPoolMutex);
+ g_bleAdapterThreadPool = handle;
+ u_mutex_unlock(g_bleAdapterThreadPoolMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
- u_mutex_lock(gBleAdapterReqRespCbMutex);
+ u_mutex_lock(g_bleAdapterReqRespCbMutex);
- gNetworkPacketReceivedCallback = callback;
+ g_networkPacketReceivedCallback = callback;
- u_mutex_unlock(gBleAdapterReqRespCbMutex);
+ u_mutex_unlock(g_bleAdapterReqRespCbMutex);
OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
}
+
#include "caadapterutils.h"
#include "camsgparser.h"
-static CANetworkChangeCallback networkCallback = NULL;
-static bool gServerRunning = false;
#define TAG "LAD"
-#define COAP_MAX_PDU_SIZE 320
+/**
+ * @def MAX_EVENT_COUNT
+ * @brief Maximum number of tries to get the event on BLE Shield address.
+ */
+#define MAX_EVENT_COUNT 20
-static CANetworkPacketReceivedCallback gRespCallback;
-static char *gCoapBuffer = NULL;
-static uint32_t dataLen = 0;
-static uint32_t packetDataLen = 0;
+static CANetworkChangeCallback g_networkCallback = NULL;
+static bool g_serverRunning = false;
+static CANetworkPacketReceivedCallback g_respCallback;
+static char *g_coapBuffer = NULL;
+static uint32_t g_dataLen = 0;
+static uint32_t g_packetDataLen = 0;
/**
- * @brief API to store the networkcallback passed from top layer, register BLE network notification
- * @param net_callback - network notification callback
+ * @brief API to register for BLE network notification.
+ * @param net_callback - network notification callback.
* @return - Error Code
*/
CAResult_t LERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
/**
- * @brief API to send received data to upper layer
- * @param[in] data - data received from BLE characteristics
- * @param[in] dataLen - received data Length
+ * @brief API to send received data to upper layer.
+ * @param[in] data - data received from BLE characteristics.
+ * @param[in] dataLen - received data Length.
* @param[in] senderAdrs - sender Address.
- * @param[in] senderPort - sender port
+ * @param[in] senderPort - sender port.
* @return - Error Code
*/
-void CANotifyCallback(void *data, int32_t dataLen, char *senderAdrs, int32_t senderPort);
+void CANotifyCallback(const void *data, int32_t dataLen, const char *senderAdrs,
+ int32_t senderPort);
/**
- * @brief API to read the data from characteristics and invoke notifyCallback
+ * @brief API to read the data from characteristics and invoke notifyCallback.
* @return - void
*/
void CACheckData();
+/**
+ * @brief API to Send the data.
+ * @return - Number of bytes sent. -1 on error.
+ */
+int32_t CASendLEData(const void *data, uint32_t dataLen);
+
CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
CANetworkPacketReceivedCallback reqRespCallback,
CANetworkChangeCallback netCallback)
OIC_LOG(DEBUG, TAG, "IN");
if (NULL == registerCallback || NULL == reqRespCallback || NULL == netCallback)
{
- OIC_LOG(ERROR, TAG, "error");
+ OIC_LOG(ERROR, TAG, "i/p null");
return CA_STATUS_INVALID_PARAM;
}
CAResult_t result = CALEInitializeNetworkMonitor();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, TAG, "error");
+ OIC_LOG_V(ERROR, TAG, "n/w init fail: %d", result);
return CA_STATUS_FAILED;
}
- gRespCallback = reqRespCallback;
+ g_respCallback = reqRespCallback;
LERegisterNetworkNotifications(netCallback);
CAConnectivityHandler_t connHandler;
- connHandler.startAdapter = NULL;
+ connHandler.startAdapter = CAStartLE;
connHandler.startListenServer = CAStartLEListeningServer;
- connHandler.startDiscoverServer = CAStartLEDiscoveryServer;
+ connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
connHandler.sendData = CASendLEUnicastData;
connHandler.sendDataToAll = CASendLEMulticastData;
connHandler.GetnetInfo = CAGetLEInterfaceInformation;
connHandler.readData = CAReadLEData;
+ connHandler.stopAdapter = CAStopLE;
connHandler.terminate = CATerminateLE;
registerCallback(connHandler, CA_LE);
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
-CAResult_t CAReadLEData()
-{
- if (true == gServerRunning)
- {
- CACheckData();
- }
- return CA_STATUS_OK;
-}
-
-void CATerminateLE()
+CAResult_t CAStartLE()
{
OIC_LOG(DEBUG, TAG, "IN");
- gRespCallback = NULL;
- LERegisterNetworkNotifications(NULL);
- CAStopBleGattServer();
- CALETerminateNetworkMonitor();
- gServerRunning = false;
OIC_LOG(DEBUG, TAG, "OUT");
- return;
+ return CA_STATUS_OK;
}
+
CAResult_t CAStartLEListeningServer()
{
OIC_LOG(DEBUG, TAG, "IN");
- uint32_t iter = 0;
CAResult_t result = CAInitializeBle();
if (CA_STATUS_OK != result)
{
- OIC_LOG(ERROR, TAG, "error");
+ OIC_LOG_V(ERROR, TAG, "ble init fail: %d", result);
return CA_STATUS_FAILED;
}
-
+ uint32_t iter = 0;
/**
* Below for loop is to process the BLE Events received from BLE Shield.
* BLE Events includes BLE Shield Address Added as a patch to RBL Library.
*/
- for (iter = 0; iter < 20; iter++)
+ for (iter = 0; iter < MAX_EVENT_COUNT; iter++)
{
CACheckData();
}
- gServerRunning = true;
+ g_serverRunning = true;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
return CA_STATUS_OK;
}
-uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, void *data,
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, const void *data,
uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "IN");
return 1;
}
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
- uint32_t dataLen)
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+ uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "IN");
- if (NULL == remoteEndpoint)
- {
- OIC_LOG(ERROR, TAG, "error");
- return 0;
- }
-
- char *char_value = (char *)data;
- if (NULL == char_value || dataLen == 0)
- {
- OIC_LOG(ERROR, TAG, "error");
- return 0;
- }
-
- char header[CA_HEADER_LENGTH] = "";
- memset(header, 0, sizeof(char) * CA_HEADER_LENGTH);
-
- CAResult_t result = CAGenerateHeader(header, dataLen);
-
- if (CA_STATUS_OK != result)
+ if (NULL == remoteEndpoint || NULL == data || dataLen == 0)
{
- return 0;
+ OIC_LOG(ERROR, TAG, "i/p null");
+ return -1;
}
-
- int32_t index = 0;
-
- if (!CAIsBleConnected())
- {
- OIC_LOG(DEBUG, TAG, "le not conn");
- return 0;
- }
-
- CAUpdateCharacteristicsInGattServer(header, CA_HEADER_LENGTH);
- int32_t iter = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
-
- for (index = 0; index < iter; index++)
- {
- CAUpdateCharacteristicsInGattServer((char_value + (index * CA_SUPPORTED_BLE_MTU_SIZE)),
- CA_SUPPORTED_BLE_MTU_SIZE);
- CABleDoEvents();
- }
-
- CAUpdateCharacteristicsInGattServer((char_value + (index * CA_SUPPORTED_BLE_MTU_SIZE)),
- dataLen % CA_SUPPORTED_BLE_MTU_SIZE);
- CABleDoEvents();
- OIC_LOG(DEBUG, TAG, "writebytes done");
OIC_LOG(DEBUG, TAG, "OUT");
- // Arduino BLEWrite doesnot return value. So, Return the received DataLength
- return dataLen;
+ return CASendLEData(data, dataLen);
}
-uint32_t CASendLEMulticastData(void *data, uint32_t dataLen)
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "IN");
if (NULL == data || 0 == dataLen)
{
- OIC_LOG(ERROR, TAG, "error");
- return 0;
- }
-
- char *char_value = (char *)data;
-
- char header[CA_HEADER_LENGTH] = "";
- memset(header, 0, sizeof(char) * CA_HEADER_LENGTH);
-
- CAResult_t result = CAGenerateHeader(header, dataLen);
-
- if (CA_STATUS_OK != result)
- {
- return 0;
- }
-
- int32_t index = 0;
-
- if (!CAIsBleConnected())
- {
- OIC_LOG(DEBUG, TAG, "le not conn");
- return 0;
- }
-
- CAUpdateCharacteristicsInGattServer(header, CA_HEADER_LENGTH);
- int32_t iter = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
-
- for (index = 0; index < iter; index++)
- {
- CAUpdateCharacteristicsInGattServer((char_value + (index * CA_SUPPORTED_BLE_MTU_SIZE)),
- CA_SUPPORTED_BLE_MTU_SIZE);
- CABleDoEvents();
+ OIC_LOG(ERROR, TAG, "i/p null");
+ return -1;
}
- CAUpdateCharacteristicsInGattServer((char_value + (index * CA_SUPPORTED_BLE_MTU_SIZE)),
- dataLen % CA_SUPPORTED_BLE_MTU_SIZE);
- CABleDoEvents();
- OIC_LOG(DEBUG, TAG, "writebytes done");
-
OIC_LOG(DEBUG, TAG, "OUT");
- // Arduino BLEWrite doesnot return value. So, Return the received DataLength
- return dataLen;
+ return CASendLEData(data, dataLen);
}
CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
if (NULL == info || NULL == size)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "i/p null");
return CA_STATUS_INVALID_PARAM;
}
(*info) = CAAdapterCreateLocalEndpoint(CA_LE, leAddress);
if (NULL == (*info))
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc fail");
return CA_MEMORY_ALLOC_FAILED;
}
return CA_STATUS_OK;
}
+CAResult_t CAReadLEData()
+{
+ if (true == g_serverRunning)
+ {
+ CACheckData();
+ }
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAStopLE()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ CAStopBleGattServer();
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+void CATerminateLE()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ g_respCallback = NULL;
+ LERegisterNetworkNotifications(NULL);
+ CAResult_t result = CATerminateBle();
+ if (CA_STATUS_OK != result)
+ {
+ OIC_LOG(ERROR, TAG, "ble terminate fail");
+ return;
+ }
+
+ CALETerminateNetworkMonitor();
+ g_serverRunning = false;
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return;
+}
+
CAResult_t LERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
{
OIC_LOG(DEBUG, TAG, "IN");
- networkCallback = netCallback;
+ g_networkCallback = netCallback;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAStopBleGattServer()
{
- // Not Supported
- CAResult_t result = CATerminateBle();
- if (CA_STATUS_OK != result)
- {
- OIC_LOG(ERROR, TAG, "error");
- return CA_STATUS_FAILED;
- }
+ OIC_LOG(DEBUG, TAG, "IN");
+ // There is no server running to stop.
+ OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
-void CANotifyCallback(void *data, int32_t dataLen, char *senderAdrs, int32_t senderPort)
+void CANotifyCallback(const void *data, int32_t dataLen, const char *senderAdrs, int32_t senderPort)
{
OIC_LOG(DEBUG, TAG, "IN");
- if (gRespCallback)
+ if (g_respCallback)
{
/* Cannot get Address as of now */
endPoint.resourceUri = ""; // will be filled by upper layer
endPoint.connectivityType = CA_LE;
- gRespCallback(&endPoint, data, dataLen);
+ g_respCallback(&endPoint, data, dataLen);
}
OIC_LOG(DEBUG, TAG, "OUT");
}
if (CAIsBleDataAvailable())
{
// Allocate Memory for COAP Buffer and do ParseHeader
- if (NULL == gCoapBuffer)
+ if (NULL == g_coapBuffer)
{
OIC_LOG(DEBUG, TAG, "IN");
char headerArray[CA_HEADER_LENGTH] = "";
- while (CAIsBleDataAvailable() && dataLen < CA_HEADER_LENGTH)
+ while (CAIsBleDataAvailable() && g_dataLen < CA_HEADER_LENGTH)
{
- headerArray[dataLen++] = CAReadBleData();
+ headerArray[g_dataLen++] = CAReadBleData();
}
- packetDataLen = CAParseHeader(headerArray);
+ g_packetDataLen = CAParseHeader(headerArray);
- if (packetDataLen > COAP_MAX_PDU_SIZE)
+ if (g_packetDataLen > COAP_MAX_PDU_SIZE)
{
- OIC_LOG(ERROR, TAG, "error");
+ OIC_LOG(ERROR, TAG, "len > pdu_size");
return;
}
- gCoapBuffer = (char *)OICMalloc(packetDataLen);
- if (NULL == gCoapBuffer)
+ g_coapBuffer = (char *)OICCalloc(g_packetDataLen, sizeof(char));
+ if (NULL == g_coapBuffer)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc");
return;
}
OIC_LOG(DEBUG, TAG, "OUT");
- memset(gCoapBuffer, 0, packetDataLen);
- dataLen = 0;
+ g_dataLen = 0;
}
OIC_LOG(DEBUG, TAG, "IN");
while (CAIsBleDataAvailable())
{
OIC_LOG(DEBUG, TAG, "In While loop");
- gCoapBuffer[dataLen++] = CAReadBleData();
- if (dataLen == packetDataLen)
+ g_coapBuffer[g_dataLen++] = CAReadBleData();
+ if (g_dataLen == g_packetDataLen)
{
OIC_LOG(DEBUG, TAG, "Read Comp BLE Pckt");
- gCoapBuffer[dataLen] = '\0';
- if (dataLen > 0)
+ g_coapBuffer[g_dataLen] = '\0';
+ if (g_dataLen > 0)
{
- OIC_LOG_V(DEBUG, TAG, "recv dataLen=%d", dataLen);
- CANotifyCallback((void *)gCoapBuffer, dataLen, "", 0);
+ OIC_LOG_V(DEBUG, TAG, "recv dataLen=%d", g_dataLen);
+ CANotifyCallback((void *)g_coapBuffer, g_dataLen, "", 0);
}
- dataLen = 0;
- OICFree(gCoapBuffer);
- gCoapBuffer = NULL;
+ g_dataLen = 0;
+ OICFree(g_coapBuffer);
+ g_coapBuffer = NULL;
break;
}
}
return;
}
+int32_t CASendLEData(const void *data, uint32_t dataLen)
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ char header[CA_HEADER_LENGTH] = {0};
+
+ CAResult_t result = CAGenerateHeader(header, dataLen);
+
+ if (CA_STATUS_OK != result)
+ {
+ return -1;
+ }
+
+ if (!CAIsBleConnected())
+ {
+ OIC_LOG(DEBUG, TAG, "le not conn");
+ return -1;
+ }
+
+ CAUpdateCharacteristicsInGattServer(header, CA_HEADER_LENGTH);
+ int32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
+ int32_t iter = 0;
+ for (iter = 0; iter < dataLimit; iter++)
+ {
+ CAUpdateCharacteristicsInGattServer((data + (iter * CA_SUPPORTED_BLE_MTU_SIZE)),
+ CA_SUPPORTED_BLE_MTU_SIZE);
+ CABleDoEvents();
+ }
+
+ CAUpdateCharacteristicsInGattServer((data + (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE)),
+ dataLen % CA_SUPPORTED_BLE_MTU_SIZE);
+ CABleDoEvents();
+ OIC_LOG(DEBUG, TAG, "writebytes done");
+ OIC_LOG(DEBUG, TAG, "OUT");
+ // Arduino BLEWrite doesnot return value. So, Return the received DataLength
+ return dataLen;
+}
#define TAG PCF("CA")
-static CANetworkPacketReceivedCallback gLEReceivedCallback = NULL;
-static u_thread_pool_t gThreadPoolHandle = NULL;
+static CANetworkPacketReceivedCallback g_leReceivedCallback = NULL;
+static u_thread_pool_t g_threadPoolHandle = NULL;
CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
{
OIC_LOG_V(DEBUG, TAG, "CAInitializeLE");
- gLEReceivedCallback = reqRespCallback;
- gThreadPoolHandle = handle;
+ g_leReceivedCallback = reqRespCallback;
+ g_threadPoolHandle = handle;
// register handlers
CAConnectivityHandler_t handler;
handler.startAdapter = CAStartLE;
handler.startListenServer = CAStartLEListeningServer;
- handler.startDiscoverServer = CAStartLEDiscoveryServer;
+ handler.startDiscoveryServer = CAStartLEDiscoveryServer;
handler.sendData = CASendLEUnicastData;
handler.sendDataToAll = CASendLEMulticastData;
handler.GetnetInfo = CAGetLEInterfaceInformation;
return CA_STATUS_OK;
}
-uint32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CASendLEUnicastData");
- return 0;
+ return -1;
}
-uint32_t CASendLEMulticastData(void *data, uint32_t dataLen)
+int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
{
OIC_LOG_V(DEBUG, TAG, "CASendLEMulticastData");
- return 0;
+ return -1;
}
CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
{
OIC_LOG_V(DEBUG, TAG, "TerminatLE");
}
+
#include "caqueueingthread.h"
#include "caadapterutils.h"
#include "camsgparser.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
/**
* @def TZ_BLE_CLIENT_TAG
#define BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG "2902"
/**
- * @var gBLEServiceList
+ * @var g_bLEServiceList
* @brief This contains the list of OIC services a client connect tot.
*/
-static BLEServiceList *gBLEServiceList = NULL;
+static BLEServiceList *g_bLEServiceList = NULL;
/**
- * @var gIsBleGattClientStarted
+ * @var g_isBleGattClientStarted
* @brief Boolean variable to keep the state of the GATT Client.
*/
-static CABool_t gIsBleGattClientStarted = CA_FALSE;
+static bool g_isBleGattClientStarted = false;
/**
- * @var gBleServiceListMutex
+ * @var g_bleServiceListMutex
* @brief Mutex to synchronize access to BleServiceList.
*/
-static u_mutex gBleServiceListMutex = NULL;
+static u_mutex g_bleServiceListMutex = NULL;
/**
- * @var gBleReqRespClientCbMutex
+ * @var g_bleReqRespClientCbMutex
* @brief Mutex to synchronize access to the requestResponse callback to be called
* when the data needs to be sent from GATTClient.
*/
-static u_mutex gBleReqRespClientCbMutex = NULL;
+static u_mutex g_bleReqRespClientCbMutex = NULL;
/**
- * @var gBleReqRespClientCbMutex
+ * @var g_bleReqRespClientCbMutex
* @brief Mutex to synchronize access to the requestResponse callback to be called
* when the data needs to be sent from GATTClient.
*/
-static u_mutex gBleClientConnectMutex = NULL;
+static u_mutex g_bleClientConnectMutex = NULL;
/**
- * @var gBleClientStateMutex
+ * @var g_bleClientStateMutex
* @brief Mutex to synchronize the calls to be done to the platform from GATTClient
* interfaces from different threads.
*/
-static u_mutex gBleClientStateMutex = NULL;
+static u_mutex g_bleClientStateMutex = NULL;
/**
- * @var gBleServerBDAddressMutex
+ * @var g_bleServerBDAddressMutex
* @brief Mutex to synchronize the Server BD Address update on client side.
*/
-static u_mutex gBleServerBDAddressMutex = NULL;
+static u_mutex g_bleServerBDAddressMutex = NULL;
/**
- * @var gBleClientSendCondWait
+ * @var g_bleClientSendCondWait
* @brief Condition used for notifying handler the presence of data in send queue.
*/
-static u_cond gBleClientSendCondWait = NULL;
+static u_cond g_bleClientSendCondWait = NULL;
/**
- * @var gDataReceiverHandlerState
- * @brief Stop condition of redvhandler.
- */
-static bool gDataReceiverHandlerState = false;
-
-/**
- * @var gBleClientThreadPoolMutex
+ * @var g_bleClientThreadPoolMutex
* @brief Mutex to synchronize the task to be pushed to thread pool.
*/
-static u_mutex gBleClientThreadPoolMutex = NULL;
+static u_mutex g_bleClientThreadPoolMutex = NULL;
/**
* @var gNetworkPacketReceivedClientCallback
* @brief Maintains the callback to be notified on receival of network packets from other
* BLE devices
*/
-static CABLEClientDataReceivedCallback gCABLEClientDataReceivedCallback = NULL;
+static CABLEClientDataReceivedCallback g_bleClientDataReceivedCallback = NULL;
/**
- * @var gClientUp
- * @brief Boolean variable to maintain the GATT Client state.
- */
-static CABool_t gClientUp = CA_FALSE;
-
-/**
- * @var g_event_loop
+ * @var g_eventLoop
* @brief gmainLoop to manage the threads to receive the callback from the platfrom.
*/
-static GMainLoop *g_event_loop = NULL;
+static GMainLoop *g_eventLoop = NULL;
/**
- * @var gBleClientThreadPool
+ * @var g_bleClientThreadPool
* @brief reference to threadpool
*/
-static u_thread_pool_t gBleClientThreadPool = NULL;
+static u_thread_pool_t g_bleClientThreadPool = NULL;
/**
* @struct stGattServiceInfo_t
* @brief structure to map the service attribute to BD Address.
- *
*/
typedef struct gattService
{
bt_gatt_attribute_h serviceInfo; /**< bluetoth attribute for oic service*/
- char *address; /**< BD Address of */
+ char *address; /**< BD Address of */
} stGattServiceInfo_t;
/**
- * @var gRemoteAddress
+ * @var g_remoteAddress
* @brief Remote address of Gatt Server
*/
-static char *gRemoteAddress = NULL;
+static char *g_remoteAddress = NULL;
void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic,
unsigned char *value,
- int32_t valueLen, void *userData)
+ int valueLen, void *userData)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic value length [%d]", valueLen);
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic value [%s]", value);
- char *data = (char *)OICMalloc(sizeof(char) * valueLen + 1);
+ char *data = (char *)OICMalloc(sizeof(char) * (valueLen + 1));
if (NULL == data)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Malloc failed!");
return;
}
- memset(data, 0x0, valueLen + 1);
- strncpy(data, (char *)value, valueLen);
-
- uint32_t sentLength = 0;
+ strncpy(data, (char *)value, valueLen + 1);
- u_mutex_lock(gBleReqRespClientCbMutex);
- if (NULL == gCABLEClientDataReceivedCallback)
+ u_mutex_lock(g_bleReqRespClientCbMutex);
+ if (NULL == g_bleClientDataReceivedCallback)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gReqRespCallback is NULL!");
- u_mutex_unlock(gBleReqRespClientCbMutex);
+ u_mutex_unlock(g_bleReqRespClientCbMutex);
OICFree(data);
return;
}
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Sending data up !");
- u_mutex_lock(gBleServerBDAddressMutex);
- gCABLEClientDataReceivedCallback(gRemoteAddress, OIC_BLE_SERVICE_ID,
+ u_mutex_lock(g_bleServerBDAddressMutex);
+ uint32_t sentLength = 0;
+ g_bleClientDataReceivedCallback(g_remoteAddress, OIC_BLE_SERVICE_ID,
data, strlen(data), &sentLength);
- u_mutex_unlock(gBleServerBDAddressMutex);
- u_mutex_unlock(gBleReqRespClientCbMutex);
+ OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Sent data Length is %d", sentLength);
+ u_mutex_unlock(g_bleServerBDAddressMutex);
+
+ u_mutex_unlock(g_bleReqRespClientCbMutex);
OICFree(data);
return;
}
-void CABleGattCharacteristicWriteCb(int32_t result, void *userData)
+void CABleGattCharacteristicWriteCb(int result, void *userData)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
}
-void CABleGattDescriptorDiscoveredCb(int32_t result, unsigned char format, int32_t total,
+void CABleGattDescriptorDiscoveredCb(int result, unsigned char format, int total,
bt_gatt_attribute_h descriptor,
bt_gatt_attribute_h characteristic, void *userData)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- stGattCharDescriptor_t *stTemp = (stGattCharDescriptor_t *)OICMalloc(sizeof(
- stGattCharDescriptor_t));
+ stGattCharDescriptor_t *stTemp = (stGattCharDescriptor_t *)OICCalloc(1, sizeof(
+ stGattCharDescriptor_t));
VERIFY_NON_NULL_VOID(stTemp, TZ_BLE_CLIENT_TAG, "malloc failed!");
- memset(stTemp, 0x0, sizeof(stGattCharDescriptor_t));
-
- stTemp->desc = (uint8_t *)OICMalloc(total + 1);
+ stTemp->desc = (uint8_t *)OICMalloc(total);
if (NULL == stTemp->desc)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "malloc failed");
OICFree(stTemp);
return;
}
+ memcpy(stTemp->desc, descriptor, total);
- memset(stTemp->desc, 0x0, total + 1);
-
- memcpy(stTemp->desc, (uint8_t *)descriptor, total);
-
- OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "result[%d] format[%d] total[%d]", result, format, total);
- OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "characteristic [%s]", (const char *) characteristic);
+ OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "result[%d] format[%d] total[%d]", result, format, total);
+ OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "characteristic [%s]", (const char *) characteristic);
bt_gatt_clone_attribute_handle(&(stTemp->characteristic), characteristic);
stTemp->total = total;
- u_mutex_lock(gBleClientThreadPoolMutex);
- if (NULL == gBleClientThreadPool)
+ u_mutex_lock(g_bleClientThreadPoolMutex);
+ if (NULL == g_bleClientThreadPool)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleClientThreadPool is NULL");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
bt_gatt_destroy_attribute_handle(stTemp->characteristic);
OICFree(stTemp->desc);
OICFree(stTemp);
- u_mutex_unlock(gBleClientThreadPoolMutex);
- return ;
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
+ return;
}
- CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool,
- (void *) CASetCharacteristicDescriptorValueThread,
- (void *) stTemp);
+ CAResult_t ret = u_thread_pool_add_task(g_bleClientThreadPool,
+ CASetCharacteristicDescriptorValueThread,
+ stTemp);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed");
bt_gatt_destroy_attribute_handle(stTemp->characteristic);
OICFree(stTemp->desc);
OICFree(stTemp);
- u_mutex_unlock(gBleClientThreadPoolMutex);
- return ;
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
+ return;
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG,
- "LE Client initialization flow complete. Enabling gClientUp state to TRUE ");
- gClientUp = CA_TRUE;
+ "LE Client initialization flow complete");
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-bool CABleGattCharacteristicsDiscoveredCb(int32_t result,
- int32_t inputIndex, int32_t total,
+bool CABleGattCharacteristicsDiscoveredCb(int result,
+ int inputIndex, int total,
bt_gatt_attribute_h characteristic, void *userData)
{
"result [%d] input_index [%d] total [%d]",
result, inputIndex, total);
- char *bdAddress = (char *) userData;
-
BLEServiceInfo *bleServiceInfo = NULL;
- u_mutex_lock(gBleServiceListMutex);
+ u_mutex_lock(g_bleServiceListMutex);
- CAGetBLEServiceInfo(gBLEServiceList, bdAddress, &bleServiceInfo);
+ char *bdAddress = (char *) userData;
+ CAGetBLEServiceInfo(g_bLEServiceList, bdAddress, &bleServiceInfo);
- u_mutex_unlock(gBleServiceListMutex);
+ u_mutex_unlock(g_bleServiceListMutex);
- if ( READ_CHAR_INDEX == inputIndex) // Server will read on this characteristics.
+ if (BLE_GATT_READ_CHAR_INDEX == inputIndex) // Server will read on this characteristics.
{
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "new read Characteristics is obtained [%s]",
(char *)characteristic);
- CAResult_t retVal = CAAppendBLECharInfo(characteristic, READ_CHAR, bleServiceInfo);
+ CAResult_t retVal = CAAppendBLECharInfo(characteristic, BLE_GATT_READ_CHAR, bleServiceInfo);
if (CA_STATUS_OK != retVal)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG , "CAAppendBLECharInfo failed ");
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "new read Characteristics uuid is obtained [%s]",
uuid);
}
- else if ( WRITE_CHAR_INDEX == inputIndex) // Server will write on this characterisctics
+ else if (BLE_GATT_WRITE_CHAR_INDEX == inputIndex) // Server will write on this characterisctics
{
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "new write Characteristics is obtained [%s]",
(char *)characteristic);
- CAResult_t retVal = CAAppendBLECharInfo(characteristic, WRITE_CHAR, bleServiceInfo);
+ CAResult_t retVal = CAAppendBLECharInfo(characteristic, BLE_GATT_WRITE_CHAR, bleServiceInfo);
if (CA_STATUS_OK != retVal)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG , "CAAppendBLECharInfo failed! ");
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "new write Characteristics uuid is obtained [%s]",
uuid);
- stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICMalloc(sizeof(stGattServiceInfo_t));
-
- VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "malloc failed!", false);
+ stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICCalloc(1,
+ sizeof(stGattServiceInfo_t));
- memset(stTemp, 0x0, sizeof(stGattServiceInfo_t));
+ VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "calloc failed!", false);
- int32_t len = strlen(bdAddress);
-
- stTemp->address = (char *)OICMalloc(sizeof(char) * len + 1);
+ size_t len = strlen(bdAddress);
+ stTemp->address = (char *)OICMalloc(sizeof(char) * (len + 1));
if (NULL == stTemp->address)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed! ");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
OICFree(stTemp);
return false;
}
- memset(stTemp->address, 0x0, len + 1);
- strncpy(stTemp->address, bdAddress, len);
+ strncpy(stTemp->address, bdAddress, len + 1);
bt_gatt_clone_attribute_handle(&(stTemp->serviceInfo), characteristic);
- u_mutex_lock(gBleClientThreadPoolMutex);
- if (NULL == gBleClientThreadPool)
+ u_mutex_lock(g_bleClientThreadPoolMutex);
+ if (NULL == g_bleClientThreadPool)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleClientThreadPool is NULL");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp->address);
OICFree(stTemp);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return false;
}
- retVal = u_thread_pool_add_task(gBleClientThreadPool,
- (void *) CADiscoverDescriptorThread,
- (void *) stTemp);
+ retVal = u_thread_pool_add_task(g_bleClientThreadPool,
+ CADiscoverDescriptorThread,
+ stTemp);
if (CA_STATUS_OK != retVal)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp->address);
OICFree(stTemp);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return false;
}
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
return true;
}
-void CABtGattBondCreatedCb(int32_t result, bt_device_info_s *device_info, void *user_data)
+void CABtGattBondCreatedCb(int result, bt_device_info_s *device_info, void *user_data)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
if (BT_ERROR_NONE != result)
VERIFY_NON_NULL_VOID(device_info->remote_address, TZ_BLE_CLIENT_TAG,
"device_info->remote_address is NULL");
- char *bdAddress = device_info->remote_address;
-
BLEServiceInfo *bleServiceInfo = NULL;
- u_mutex_lock(gBleServiceListMutex);
- CAResult_t retVal = CAGetBLEServiceInfo(gBLEServiceList, bdAddress, &bleServiceInfo);
+ u_mutex_lock(g_bleServiceListMutex);
+ CAResult_t retVal = CAGetBLEServiceInfo(g_bLEServiceList, device_info->remote_address, &bleServiceInfo);
+ u_mutex_unlock(g_bleServiceListMutex);
if (CA_STATUS_OK != retVal)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAGetBLEServiceInfo failed! ");
return;
}
- u_mutex_unlock(gBleServiceListMutex);
VERIFY_NON_NULL_VOID(bleServiceInfo, TZ_BLE_CLIENT_TAG,
"bleServiceInfo is NULL");
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its OIC service");
- OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG ,
- " serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
+ OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+ "serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
- stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICMalloc(sizeof(stGattServiceInfo_t));
+ stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICCalloc(1,
+ sizeof(stGattServiceInfo_t));
VERIFY_NON_NULL_VOID(stTemp, TZ_BLE_CLIENT_TAG, "malloc failed");
bt_gatt_clone_attribute_handle(&(stTemp->serviceInfo), bleServiceInfo->service_clone);
- int32_t len = strlen(bleServiceInfo->bdAddress);
-
- stTemp->address = (char *)OICMalloc(sizeof(char) * len + 1);
+ size_t len = strlen(bleServiceInfo->bdAddress);
+ stTemp->address = (char *)OICMalloc(sizeof(char) * (len + 1));
if (NULL == stTemp->address)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed! ");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp);
return;
}
- memset(stTemp->address, 0x0, len + 1);
- strncpy(stTemp->address, bleServiceInfo->bdAddress, len);
+ strncpy(stTemp->address, bleServiceInfo->bdAddress, len + 1);
- u_mutex_lock(gBleClientThreadPoolMutex);
- if (NULL == gBleClientThreadPool)
+ u_mutex_lock(g_bleClientThreadPoolMutex);
+ if (NULL == g_bleClientThreadPool)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleClientThreadPool is NULL");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp->address);
OICFree(stTemp);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return;
}
- CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool,
- (void *) CADiscoverCharThread, (void *) stTemp);
+ CAResult_t ret = u_thread_pool_add_task(g_bleClientThreadPool,
+ CADiscoverCharThread, stTemp);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp->address);
OICFree(stTemp);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return;
}
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
"Callback: is_bonded - %d.", device_info->is_bonded);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int32_t index, int32_t count,
+bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count,
void *userData)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its OIC service");
- //gIsOicDeviceFound = CA_TRUE;
-
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG , "Registering to watch characteristics changes \n");
result = CABleGattWatchCharacteristicChanges(service);
return false;
}
- char *bdAddress = (char *)userData;
-
- stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICMalloc(sizeof(stGattServiceInfo_t));
-
- VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "Malloc Failed", false);
+ stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICCalloc(1,
+ sizeof(stGattServiceInfo_t));
+ VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "Calloc Failed", false);
- memset(stTemp, 0x0, sizeof(stGattServiceInfo_t));
-
- int32_t len = strlen(bdAddress);
+ char *bdAddress = (char *)userData;
+ size_t len = strlen(bdAddress);
- stTemp->address = (char *)OICMalloc(sizeof(char) * len + 1);
+ stTemp->address = (char *)OICMalloc(sizeof(char) * (len + 1));
if (NULL == stTemp->address)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed! ");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc failed!");
OICFree(stTemp);
return false;
}
- memset(stTemp->address, 0x0, len + 1);
- strncpy(stTemp->address, bdAddress, len);
+
+ strncpy(stTemp->address, bdAddress, len + 1);
BLEServiceInfo *bleServiceInfo = NULL;
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG ,
" serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
- u_mutex_lock(gBleServiceListMutex);
- result = CAAddBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo);
+ u_mutex_lock(g_bleServiceListMutex);
+ result = CAAddBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo);
+ u_mutex_unlock(g_bleServiceListMutex);
if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG , "CAAddBLEServiceInfoToList failed!");
OICFree(stTemp);
CAFreeBLEServiceInfo(bleServiceInfo);
bleServiceInfo = NULL;
- u_mutex_unlock(gBleServiceListMutex);
return false;
}
- u_mutex_unlock(gBleServiceListMutex);
- u_mutex_lock(gBleClientThreadPoolMutex);
- if (NULL == gBleClientThreadPool)
+
+ u_mutex_lock(g_bleClientThreadPoolMutex);
+ if (NULL == g_bleClientThreadPool)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleClientThreadPool is NULL");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
OICFree(stTemp->address);
OICFree(stTemp);
- u_mutex_lock(gBleServiceListMutex);
- CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo,
+ u_mutex_lock(g_bleServiceListMutex);
+ CARemoveBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo,
bleServiceInfo->bdAddress);
- u_mutex_unlock(gBleServiceListMutex);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleServiceListMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return false;
}
- result = u_thread_pool_add_task(gBleClientThreadPool,
- (void *) CAGATTCreateBondThread,
- (void *) stTemp);
+ result = u_thread_pool_add_task(g_bleClientThreadPool,
+ CAGATTCreateBondThread,
+ stTemp);
if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
"u_thread_pool_add_task failed with ret [%d]", result);
OICFree(stTemp->address);
OICFree(stTemp);
- u_mutex_lock(gBleServiceListMutex);
- CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo,
+ u_mutex_lock(g_bleServiceListMutex);
+ CARemoveBLEServiceInfoToList(&g_bLEServiceList, bleServiceInfo,
bleServiceInfo->bdAddress);
- u_mutex_unlock(gBleServiceListMutex);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleServiceListMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return false;
}
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
return true;;
}
-void CABleGattConnectionStateChangedCb(int32_t result, bool connected,
+void CABleGattConnectionStateChangedCb(int result, bool connected,
const char *remoteAddress, void *userData)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
{
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Connected to [%s] ", remoteAddress);
+ u_mutex_lock(g_bleServerBDAddressMutex);
- int32_t len = strlen(remoteAddress);
+ g_remoteAddress = OICStrdup(remoteAddress);
- u_mutex_lock(gBleServerBDAddressMutex);
+ u_mutex_unlock(g_bleServerBDAddressMutex);
- gRemoteAddress = OICStrdup(remoteAddress);
-
- u_mutex_unlock(gBleServerBDAddressMutex);
-
- VERIFY_NON_NULL_VOID(gRemoteAddress, TZ_BLE_CLIENT_TAG, "Malloc failed");
+ VERIFY_NON_NULL_VOID(g_remoteAddress, TZ_BLE_CLIENT_TAG, "Malloc failed");
char *addr = OICStrdup(remoteAddress);
- u_mutex_lock(gBleClientThreadPoolMutex);
- if (NULL == gBleClientThreadPool)
+ u_mutex_lock(g_bleClientThreadPoolMutex);
+ if (NULL == g_bleClientThreadPool)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleClientThreadPool is NULL");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
OICFree(addr);
- u_mutex_lock(gBleServerBDAddressMutex);
- OICFree(gRemoteAddress);
- u_mutex_unlock(gBleServerBDAddressMutex);
+ u_mutex_lock(g_bleServerBDAddressMutex);
+ OICFree(g_remoteAddress);
+ u_mutex_unlock(g_bleServerBDAddressMutex);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return;
}
- ret = u_thread_pool_add_task(gBleClientThreadPool, (void *) CADiscoverBLEServicesThread,
- (void *) addr);
+ ret = u_thread_pool_add_task(g_bleClientThreadPool, CADiscoverBLEServicesThread,
+ addr);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed with ret [%d]", ret);
OICFree(addr);
- u_mutex_lock(gBleServerBDAddressMutex);
- OICFree(gRemoteAddress);
- u_mutex_unlock(gBleServerBDAddressMutex);
+ u_mutex_lock(g_bleServerBDAddressMutex);
+ OICFree(g_remoteAddress);
+ u_mutex_unlock(g_bleServerBDAddressMutex);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return;
}
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-void CABtAdapterLeDeviceDiscoveryStateChangedCb(int32_t result,
+void CABtAdapterLeDeviceDiscoveryStateChangedCb(int result,
bt_adapter_le_device_discovery_state_e discoveryState,
bt_adapter_le_device_discovery_info_s *discoveryInfo,
void *userData)
{
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
" LE Discovery state is [%s]",
- discoveryState == BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED ? "Started" : "Finished");
+ discoveryState == BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED ? "Started" : "Finished");
}
else
{
CAPrintDiscoveryInformation(discoveryInfo);
- int i = 0;
if (discoveryInfo->service_uuid == NULL)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "NO UUIDS from device");
}
else
{
- for (i = discoveryInfo->service_count - 1; i > 0; i--)
+ for (int32_t i = discoveryInfo->service_count - 1; i > 0; i--)
{
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "uuid[%d]: [%s]",
i, discoveryInfo->service_uuid[i]);
if (CA_STATUS_OK == res)
{
- int32_t len = strlen(discoveryInfo->remote_address);
-
- char *addr = (char *)OICMalloc(sizeof(char) * len + 1);
+ size_t len = strlen(discoveryInfo->remote_address);
+ char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
VERIFY_NON_NULL_VOID(addr, TZ_BLE_CLIENT_TAG, "Malloc failed");
-
- memset(addr, 0x0, len + 1);
- strncpy(addr, discoveryInfo->remote_address, len);
+ strncpy(addr, discoveryInfo->remote_address, len + 1);
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
- "Trying to do Gatt connection to [%s] ", addr);
+ "Trying to do Gatt connection to [%s]", addr);
- u_mutex_lock(gBleClientThreadPoolMutex);
- if (NULL == gBleClientThreadPool)
+ u_mutex_lock(g_bleClientThreadPoolMutex);
+ if (NULL == g_bleClientThreadPool)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleClientThreadPool is NULL");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_bleClientThreadPool is NULL");
OICFree(addr);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return;
}
- CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool,
- (void *) CAGattConnectThread, (void *) addr);
+ CAResult_t ret = u_thread_pool_add_task(g_bleClientThreadPool,
+ CAGattConnectThread, addr);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
"u_thread_pool_add_task failed with ret [%d]", ret);
OICFree(addr);
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return;
}
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
if (discoveryInfo->adv_data_len > 31 || discoveryInfo->scan_data_len > 31)
{
bt_adapter_le_stop_device_discovery();
}
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
- return;
}
-void CAPrintDiscoveryInformation(bt_adapter_le_device_discovery_info_s *discoveryInfo)
+void CAPrintDiscoveryInformation(const bt_adapter_le_device_discovery_info_s *discoveryInfo)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- u_mutex_unlock(gBleClientThreadPoolMutex);
- gBleClientThreadPool = handle;
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_lock(g_bleClientThreadPoolMutex);
+ g_bleClientThreadPool = handle;
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- u_mutex_lock(gBleReqRespClientCbMutex);
+ u_mutex_lock(g_bleReqRespClientCbMutex);
- gCABLEClientDataReceivedCallback = callback;
+ g_bleClientDataReceivedCallback = callback;
- u_mutex_unlock(gBleReqRespClientCbMutex);
+ u_mutex_unlock(g_bleReqRespClientCbMutex);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- CAResult_t retVal = CAInitGattClientMutexVaraibles();
+ CAResult_t retVal = CAInitGattClientMutexVariables();
if (CA_STATUS_OK != retVal)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAInitGattClientMutexVaraibles failed!");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAInitGattClientMutexVariables failed!");
CATerminateGattClientMutexVariables();
return CA_STATUS_FAILED;
}
- u_mutex_lock(gBleClientThreadPoolMutex);
- if (NULL == gBleClientThreadPool)
+ u_mutex_lock(g_bleClientThreadPoolMutex);
+ if (NULL == g_bleClientThreadPool)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleServerThreadPool is NULL");
CATerminateGattClientMutexVariables();
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return CA_STATUS_FAILED;
}
- retVal = u_thread_pool_add_task(gBleClientThreadPool, (void *) CAStartBleGattClientThread,
- (void *) NULL);
+ retVal = u_thread_pool_add_task(g_bleClientThreadPool, CAStartBleGattClientThread,
+ NULL);
if (CA_STATUS_OK != retVal)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed");
CATerminateGattClientMutexVariables();
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
return CA_STATUS_FAILED;
}
- u_mutex_unlock(gBleClientThreadPoolMutex);
+ u_mutex_unlock(g_bleClientThreadPoolMutex);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
return CA_STATUS_OK;
}
-void *CAStartBleGattClientThread(void *data)
+void CAStartBleGattClientThread(void *data)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- u_mutex_lock(gBleClientStateMutex);
+ u_mutex_lock(g_bleClientStateMutex);
- if (CA_TRUE == gIsBleGattClientStarted)
+ if (true == g_isBleGattClientStarted)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Gatt Client is already running!!");
- u_mutex_unlock(gBleClientStateMutex);
- return NULL;
+ u_mutex_unlock(g_bleClientStateMutex);
+ return;
}
CAResult_t ret = CABleGattSetScanParameter();
if (CA_STATUS_OK != ret)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleSetScanParameter Failed");
- u_mutex_unlock(gBleClientStateMutex);
+ u_mutex_unlock(g_bleClientStateMutex);
CATerminateBLEGattClient();
- return NULL;
+ return;
}
ret = CABleGattSetCallbacks();
if (CA_STATUS_OK != ret)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattSetCallbacks Failed");
- u_mutex_unlock(gBleClientStateMutex);
+ u_mutex_unlock(g_bleClientStateMutex);
CATerminateBLEGattClient();
- return NULL;
+ return;
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Starting LE device discovery");
if (CA_STATUS_OK != ret)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_start_device_discovery Failed");
- u_mutex_unlock(gBleClientStateMutex);
+ u_mutex_unlock(g_bleClientStateMutex);
CATerminateBLEGattClient();
- return NULL;
+ return;
}
- gIsBleGattClientStarted = CA_TRUE;
+ g_isBleGattClientStarted = true;
- u_mutex_unlock(gBleClientStateMutex);
+ u_mutex_unlock(g_bleClientStateMutex);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Giveing the control to threadPool");
- GMainContext *thread_context = NULL;
-
- thread_context = g_main_context_new();
+ GMainContext *thread_context = g_main_context_new();
- g_event_loop = g_main_loop_new(thread_context, FALSE);
+ g_eventLoop = g_main_loop_new(thread_context, FALSE);
g_main_context_push_thread_default(thread_context);
- g_main_loop_run(g_event_loop);
+ g_main_loop_run(g_eventLoop);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
-
- return NULL;
}
void CAStopBLEGattClient()
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- u_mutex_lock(gBleClientStateMutex);
+ u_mutex_lock(g_bleClientStateMutex);
- if (CA_FALSE == gIsBleGattClientStarted)
+ if (false == g_isBleGattClientStarted)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Gatt Client is not running to stop");
- u_mutex_unlock(gBleClientStateMutex);
+ u_mutex_unlock(g_bleClientStateMutex);
return;
}
- u_mutex_unlock(gBleClientStateMutex);
-
- // Stop data send and receive handlers
- if ( gDataReceiverHandlerState)
- {
- gDataReceiverHandlerState = CA_FALSE;
- }
+ u_mutex_unlock(g_bleClientStateMutex);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
void CATerminateBLEGattClient()
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+ u_mutex_lock(g_bleClientStateMutex);
- gClientUp = CA_FALSE;
-
- u_mutex_lock(gBleClientStateMutex);
GMainContext *context_event_loop = NULL;
// Required for waking up the thread which is running in gmain loop
- if (NULL != g_event_loop)
+ if (NULL != g_eventLoop)
{
- context_event_loop = g_main_loop_get_context(g_event_loop);
+ context_event_loop = g_main_loop_get_context(g_eventLoop);
}
if (context_event_loop)
{
- OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "g_event_loop context %x", context_event_loop);
+ OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "g_eventLoop context %x", context_event_loop);
g_main_context_wakeup(context_event_loop);
// Kill g main loops and kill threads.
- g_main_loop_quit(g_event_loop);
+ g_main_loop_quit(g_eventLoop);
}
else
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_event_loop context is NULL");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "g_eventLoop context is NULL");
}
- u_mutex_lock(gBleServerBDAddressMutex);
+ u_mutex_lock(g_bleServerBDAddressMutex);
- OICFree(gRemoteAddress);
+ OICFree(g_remoteAddress);
- u_mutex_unlock(gBleServerBDAddressMutex);
+ u_mutex_unlock(g_bleServerBDAddressMutex);
CABleGattUnWatchCharacteristicChanges();
CABleGattStopDeviceDiscovery();
- u_mutex_lock(gBleServiceListMutex);
- CAFreeBLEServiceList(gBLEServiceList);
- gBLEServiceList = NULL;
- u_mutex_unlock(gBleServiceListMutex);
+ u_mutex_lock(g_bleServiceListMutex);
+ CAFreeBLEServiceList(g_bLEServiceList);
+ g_bLEServiceList = NULL;
+ u_mutex_unlock(g_bleServiceListMutex);
CAResetRegisteredServiceCount();
- gIsBleGattClientStarted = CA_FALSE;
- u_mutex_unlock(gBleClientStateMutex);
+ g_isBleGattClientStarted = false;
+ u_mutex_unlock(g_bleClientStateMutex);
CATerminateGattClientMutexVariables();
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-
-CAResult_t CAInitGattClientMutexVaraibles()
+CAResult_t CAInitGattClientMutexVariables()
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- u_mutex_init();
- if (NULL == gBleClientStateMutex)
+ if (NULL == g_bleClientStateMutex)
{
- gBleClientStateMutex = u_mutex_new();
- if (NULL == gBleClientStateMutex)
+ g_bleClientStateMutex = u_mutex_new();
+ if (NULL == g_bleClientStateMutex)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleServiceListMutex)
+ if (NULL == g_bleServiceListMutex)
{
- gBleServiceListMutex = u_mutex_new();
- if (NULL == gBleServiceListMutex)
+ g_bleServiceListMutex = u_mutex_new();
+ if (NULL == g_bleServiceListMutex)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleReqRespClientCbMutex)
+ if (NULL == g_bleReqRespClientCbMutex)
{
- gBleReqRespClientCbMutex = u_mutex_new();
- if (NULL == gBleReqRespClientCbMutex)
+ g_bleReqRespClientCbMutex = u_mutex_new();
+ if (NULL == g_bleReqRespClientCbMutex)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleClientThreadPoolMutex)
+ if (NULL == g_bleClientThreadPoolMutex)
{
- gBleClientThreadPoolMutex = u_mutex_new();
- if (NULL == gBleClientThreadPoolMutex)
+ g_bleClientThreadPoolMutex = u_mutex_new();
+ if (NULL == g_bleClientThreadPoolMutex)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleClientConnectMutex)
+ if (NULL == g_bleClientConnectMutex)
{
- gBleClientConnectMutex = u_mutex_new();
- if (NULL == gBleClientConnectMutex)
+ g_bleClientConnectMutex = u_mutex_new();
+ if (NULL == g_bleClientConnectMutex)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleClientSendCondWait)
+ if (NULL == g_bleClientSendCondWait)
{
- gBleClientSendCondWait = u_cond_new();
- if (NULL == gBleClientSendCondWait)
+ g_bleClientSendCondWait = u_cond_new();
+ if (NULL == g_bleClientSendCondWait)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "u_cond_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleServerBDAddressMutex)
+ if (NULL == g_bleServerBDAddressMutex)
{
- gBleServerBDAddressMutex = u_mutex_new();
- if (NULL == gBleServerBDAddressMutex)
+ g_bleServerBDAddressMutex = u_mutex_new();
+ if (NULL == g_bleServerBDAddressMutex)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- u_mutex_free(gBleClientStateMutex);
- gBleClientStateMutex = NULL;
+ u_mutex_free(g_bleClientStateMutex);
+ g_bleClientStateMutex = NULL;
- u_mutex_free(gBleServiceListMutex);
- gBleServiceListMutex = NULL;
+ u_mutex_free(g_bleServiceListMutex);
+ g_bleServiceListMutex = NULL;
- u_mutex_free(gBleReqRespClientCbMutex);
- gBleReqRespClientCbMutex = NULL;
+ u_mutex_free(g_bleReqRespClientCbMutex);
+ g_bleReqRespClientCbMutex = NULL;
- u_mutex_free(gBleClientConnectMutex);
- gBleClientConnectMutex = NULL;
+ u_mutex_free(g_bleClientConnectMutex);
+ g_bleClientConnectMutex = NULL;
- u_mutex_free(gBleClientThreadPoolMutex);
- gBleClientThreadPoolMutex = NULL;
+ u_mutex_free(g_bleClientThreadPoolMutex);
+ g_bleClientThreadPoolMutex = NULL;
- u_mutex_free(gBleServerBDAddressMutex);
- gBleServerBDAddressMutex = NULL;
+ u_mutex_free(g_bleServerBDAddressMutex);
+ g_bleServerBDAddressMutex = NULL;
- u_cond_free(gBleClientSendCondWait);
- gBleClientSendCondWait = NULL;
+ u_cond_free(g_bleClientSendCondWait);
+ g_bleClientSendCondWait = NULL;
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
scan_param.interval = 1560;
scan_param.window = 160;
- int32_t ret = bt_adapter_le_set_scan_parameter(&scan_param);
+ int ret = bt_adapter_le_set_scan_parameter(&scan_param);
if (BT_ERROR_NONE != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_set_scan_parameter Failed with ret [%d]", ret);
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- int32_t ret = bt_gatt_set_connection_state_changed_cb(CABleGattConnectionStateChangedCb, NULL);
+ int ret = bt_gatt_set_connection_state_changed_cb(CABleGattConnectionStateChangedCb, NULL);
if (BT_ERROR_NONE != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-
- int32_t ret = bt_gatt_watch_characteristic_changes(service);
+ int ret = bt_gatt_watch_characteristic_changes(service);
if (BT_ERROR_NONE != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
- "bt_gatt_watch_characteristic_changes failed with [%s] \n", CABTGetErrorMsg(ret));
+ "bt_gatt_watch_characteristic_changes failed with [%s] \n",
+ CABTGetErrorMsg(ret));
return CA_STATUS_FAILED;
}
int32_t count = CAGetRegisteredServiceCount();
- int32_t index = 0;
-
- for (index = 0; index < count; index++)
+ for (int32_t index = 0; index < count; index++)
{
BLEServiceInfo *bleServiceInfo = NULL;
- u_mutex_lock(gBleServiceListMutex);
+ u_mutex_lock(g_bleServiceListMutex);
- CAResult_t result = CAGetBLEServiceInfoByPosition(gBLEServiceList, index, &bleServiceInfo);
- if (CA_STATUS_OK == result && NULL != bleServiceInfo && NULL != bleServiceInfo->service_clone)
+ CAResult_t result = CAGetBLEServiceInfoByPosition(g_bLEServiceList, index, &bleServiceInfo);
+ if (CA_STATUS_OK == result && NULL != bleServiceInfo
+ && NULL != bleServiceInfo->service_clone)
{
bt_gatt_unwatch_characteristic_changes(bleServiceInfo->service_clone);
OIC_LOG(INFO, TZ_BLE_CLIENT_TAG, "bt_gatt_unwatch_characteristic_changes done");
}
- u_mutex_unlock(gBleServiceListMutex);
+ u_mutex_unlock(g_bleServiceListMutex);
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- int32_t ret = bt_adapter_le_start_device_discovery();
+ int ret = bt_adapter_le_start_device_discovery();
if (BT_ERROR_NONE != ret)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_start_device_discovery Failed");
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
}
-void *CAGattConnectThread (void *remoteAddress)
+void CAGattConnectThread (void *remoteAddress)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
- VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL", NULL);
+ VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
char *address = (char *)remoteAddress;
if (CA_STATUS_OK != result)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_connect failed for [%s]", address);
- OICFree(address);
- return NULL;
}
OICFree(address);
- address = NULL;
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
- return NULL;
}
CAResult_t CABleGattConnect(const char *remoteAddress)
VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
"remote address is NULL", CA_STATUS_FAILED);
+ //Because of the platform issue, we added. Once platform is stablized, then it will be removed
sleep(1);
- u_mutex_lock(gBleClientConnectMutex);
+ u_mutex_lock(g_bleClientConnectMutex);
- int32_t ret = bt_gatt_connect(remoteAddress, true);
+ int ret = bt_gatt_connect(remoteAddress, true);
if (BT_ERROR_NONE != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_connect Failed with ret value [%s] ",
CABTGetErrorMsg(ret));
+ u_mutex_unlock(g_bleClientConnectMutex);
return CA_STATUS_FAILED;
}
- u_mutex_unlock(gBleClientConnectMutex);
+ u_mutex_unlock(g_bleClientConnectMutex);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
return CA_STATUS_OK;
return CA_STATUS_OK;
}
-void *CADiscoverBLEServicesThread (void *remoteAddress)
+void CADiscoverBLEServicesThread (void *remoteAddress)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL", NULL);
+ VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
char *address = (char *)remoteAddress;
CAResult_t result = CABleGattDiscoverServices(address);
if (CA_STATUS_OK != result)
{
- OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattDiscoverServices failed");
- OICFree(address);
- return NULL;
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CABleGattDiscoverServices failed");
}
OICFree(address);
- address = NULL;
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
- return NULL;
}
CAResult_t CABleGattDiscoverServices(const char *remoteAddress)
VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
"remote address is NULL", CA_STATUS_FAILED);
- int32_t len = strlen(remoteAddress);
-
- char *addr = (char *)OICMalloc(sizeof(char) * len + 1);
+ size_t len = strlen(remoteAddress);
+ char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+ VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
- VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG,
- "Malloc failed", CA_STATUS_FAILED);
-
- memset(addr, 0x0, len + 1);
- strncpy(addr, remoteAddress, len);
+ strncpy(addr, remoteAddress, len + 1);
int32_t ret = bt_gatt_foreach_primary_services(remoteAddress, CABleGattPrimaryServiceCb,
(void *)addr); // addr memory will be free in callback.
return CA_STATUS_OK;
}
-void *CADiscoverCharThread(void *stServiceInfo)
+void CADiscoverCharThread(void *stServiceInfo)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- VERIFY_NON_NULL_RET(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL", NULL);
+ VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)stServiceInfo;
- VERIFY_NON_NULL_RET(stTemp->address, TZ_BLE_CLIENT_TAG, "stTemp->address is NULL", NULL);
+ VERIFY_NON_NULL_VOID(stTemp->address, TZ_BLE_CLIENT_TAG, "stTemp->address is NULL");
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address [%s]", stTemp->address);
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp->address);
OICFree(stTemp);
- return NULL;
+ return;
}
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp->address);
OICFree(stTemp);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
- return NULL;
}
CAResult_t CABleGattDiscoverCharacteristics(bt_gatt_attribute_h service,
VERIFY_NON_NULL_RET(remoteAddress, NULL, "remoteAddress is NULL", CA_STATUS_FAILED);
- int32_t len = strlen(remoteAddress);
+ size_t len = strlen(remoteAddress);
- char *addr = (char *)OICMalloc(sizeof(char) * len + 1);
- VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG,
- "Malloc failed", CA_STATUS_FAILED);
-
- memset(addr, 0x0, len + 1);
- strncpy(addr, remoteAddress, len);
+ char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
+ VERIFY_NON_NULL_RET(addr, TZ_BLE_CLIENT_TAG, "Malloc failed", CA_STATUS_FAILED);
+ strncpy(addr, remoteAddress, len + 1);
int32_t ret = bt_gatt_discover_characteristics(service, CABleGattCharacteristicsDiscoveredCb,
(void *)addr); // addr will be freed in callback.
return CA_STATUS_OK;
}
-void *CADiscoverDescriptorThread(void *stServiceInfo)
+void CADiscoverDescriptorThread(void *stServiceInfo)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, " IN");
- VERIFY_NON_NULL_RET(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL", NULL);
+ VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)stServiceInfo;
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp->address);
OICFree(stTemp);
- return NULL;
+ return;
}
bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
OICFree(stTemp);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
- return NULL;
}
CAResult_t CABleGattDiscoverDescriptor(bt_gatt_attribute_h service, const char *remoteAddress)
VERIFY_NON_NULL_RET(service, NULL, "service is NULL", CA_STATUS_FAILED);
- int32_t ret = bt_gatt_discover_characteristic_descriptor(service,
+ int ret = bt_gatt_discover_characteristic_descriptor(service,
CABleGattDescriptorDiscoveredCb, NULL);
if (BT_ERROR_NONE != ret)
{
return CA_STATUS_OK;
}
-void *CASetCharacteristicDescriptorValueThread(void *stServiceInfo)
+void CASetCharacteristicDescriptorValueThread(void *stServiceInfo)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- VERIFY_NON_NULL_RET(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL", NULL);
+ VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
stGattCharDescriptor_t *stTemp = (stGattCharDescriptor_t *)stServiceInfo;
bt_gatt_destroy_attribute_handle(stTemp->characteristic);
OICFree(stTemp->desc);
OICFree(stTemp);
- return NULL;
+ return;
}
bt_gatt_destroy_attribute_handle(stTemp->characteristic);
OICFree(stTemp->desc);
OICFree(stTemp);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
- return NULL;
}
CAResult_t CASetCharacteristicDescriptorValue(stGattCharDescriptor_t *stGattCharDescInfo)
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
unsigned char noti[4] = {0,};
- char *strUUID = NULL;
- strUUID = (char *)OICMalloc(sizeof(char) * 5);
+ char *strUUID = (char *)OICCalloc(5, sizeof(char));
- VERIFY_NON_NULL_RET(strUUID, TZ_BLE_CLIENT_TAG, "malloc failed", CA_STATUS_FAILED);
+ VERIFY_NON_NULL_RET(strUUID, TZ_BLE_CLIENT_TAG, "calloc failed", CA_STATUS_FAILED);
- memset(strUUID, 0x0, sizeof(char) * 5);
snprintf(strUUID, 4, "%x%x", stGattCharDescInfo->desc[3], stGattCharDescInfo->desc[2]);
noti[0] = stGattCharDescInfo->desc[0];
noti[1] = stGattCharDescInfo->desc[1];
noti[2] = 0x01;
noti[3] = 0x00;
- OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x0 [%x]", stGattCharDescInfo->desc[0]);
+ OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x0 [%x]", stGattCharDescInfo->desc[0]);
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x1 [%x]", stGattCharDescInfo->desc[1]);
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x2 [%x]", stGattCharDescInfo->desc[2]);
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "desc x3 [%x]", stGattCharDescInfo->desc[3]);
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "setting notification/indication for descriptor");
- int32_t ret = bt_gatt_set_characteristic_desc_value_request(
+ int ret = bt_gatt_set_characteristic_desc_value_request(
stGattCharDescInfo->characteristic,
noti, 4, CABleGattCharacteristicWriteCb);
if (BT_ERROR_NONE != ret)
return CA_STATUS_OK;
}
-void *CAGATTCreateBondThread(void *stServiceInfo)
+void CAGATTCreateBondThread(void *stServiceInfo)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
- VERIFY_NON_NULL_RET(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL", NULL);
+ VERIFY_NON_NULL_VOID(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)stServiceInfo;
- VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "stTemp is NULL", NULL);
+ VERIFY_NON_NULL_VOID(stTemp, TZ_BLE_CLIENT_TAG, "stTemp is NULL");
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address [%s]",
stTemp->address);
"CABleGattDiscoverCharacteristics failed!");
OICFree(stTemp->address);
OICFree(stTemp);
- return NULL;
+ return;
}
OICFree(stTemp->address);
OICFree(stTemp);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
- return NULL;
}
CAResult_t CABleGATTCreateBond(const char *remoteAddress)
VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
"remote address is NULL", CA_STATUS_FAILED);
- int32_t ret = bt_device_create_bond(remoteAddress);
+ int ret = bt_device_create_bond(remoteAddress);
if (BT_ERROR_NONE != ret)
{
CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
const char *data, const int32_t dataLen,
- TRANSFER_TYPE type, const int32_t position)
+ CALETransferType_t type, const int32_t position)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
BLEServiceInfo *bleServiceInfo = NULL;
- u_mutex_lock(gBleServiceListMutex);
CAResult_t ret = CA_STATUS_FAILED;
- if ( UNICAST == type)
+
+ u_mutex_lock(g_bleServiceListMutex);
+ if ( LE_UNICAST == type)
{
VERIFY_NON_NULL(remoteAddress, NULL, "remoteAddress is NULL");
- ret = CAGetBLEServiceInfo(gBLEServiceList, remoteAddress, &bleServiceInfo);
+ ret = CAGetBLEServiceInfo(g_bLEServiceList, remoteAddress, &bleServiceInfo);
}
- else if ( MULTICAST == type)
+ else if ( LE_MULTICAST == type)
{
- ret = CAGetBLEServiceInfoByPosition(gBLEServiceList, position, &bleServiceInfo);
+ ret = CAGetBLEServiceInfoByPosition(g_bLEServiceList, position, &bleServiceInfo);
}
+ u_mutex_unlock(g_bleServiceListMutex);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "CAGetBLEServiceInfoByPosition is failed");
- u_mutex_unlock(gBleServiceListMutex);
return CA_STATUS_FAILED;
}
- u_mutex_unlock(gBleServiceListMutex);
VERIFY_NON_NULL(bleServiceInfo, NULL, "bleServiceInfo is NULL");
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Updating to write char [%s]",
bleServiceInfo->read_char);
- unsigned char *value = (unsigned char *) OICMalloc(sizeof(char) * (dataLen + 1));
+ char *value = (char *) OICMalloc(sizeof(char) * (dataLen + 1));
VERIFY_NON_NULL_RET(value, TZ_BLE_CLIENT_TAG, "malloc failed", CA_STATUS_FAILED);
-
- memset(value, 0x0, (dataLen + 1));
- strncpy((char *)value, data, dataLen);
+ strncpy((char *)value, data, dataLen + 1);
OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
"Updating the data of length [%d] to [%s] and size of data is [%d] ", dataLen,
bleServiceInfo->bdAddress, strlen(value));
- int32_t result = bt_gatt_set_characteristic_value_request(bleServiceInfo->read_char, value,
+ int result = bt_gatt_set_characteristic_value_request(bleServiceInfo->read_char, (unsigned char *)value,
dataLen,
CABleGattCharacteristicWriteCb);
if (BT_ERROR_NONE != result)
}
CAResult_t CAUpdateCharacteristicsToAllGattServers(const char *data,
- const int32_t dataLen)
+ int32_t dataLen)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
return CA_STATUS_INVALID_PARAM;
}
- int32_t pos = 0;
+ int numOfServersConnected = CAGetRegisteredServiceCount();
- int32_t NumberOfServersConnected = CAGetRegisteredServiceCount();
-
- for (pos = 0; pos < NumberOfServersConnected ; pos++)
+ for (int32_t pos = 0; pos < numOfServersConnected; pos++)
{
/*remoteAddress will be NULL.
- Since we have to send to all the address. pos will be used for getting remote address.
- */
- int32_t ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, MULTICAST, pos);
+ Since we have to send to all destinations. pos will be used for getting remote address.
+ */
+ int32_t ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, LE_MULTICAST, pos);
if (CA_STATUS_OK != ret)
{
return CA_STATUS_OK;
}
+
#include "logger.h"
#include "uthreadpool.h"
#include "caleinterface.h"
+#include "oic_malloc.h"
/**
* @param userData [IN] The user data passed from the request function
* @return NONE
*/
-void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic, unsigned char *value,
- int32_t valueLen, void *userData);
+void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic,
+ unsigned char *value, int valueLen, void *userData);
/**
* @brief This is the callback which will be called after the characteristics changed.
*
*
* @return NONE
*/
-void CABleGattCharacteristicWriteCb(int32_t result, void *userData);
+void CABleGattCharacteristicWriteCb(int result, void *userData);
/**
* @brief This is the callback which will be called when descriptor of characteristics is found.
* @param userData [IN] The user data passed from the request function
* @return NONE
*/
-void CABleGattDescriptorDiscoveredCb(int32_t result, unsigned char format, int32_t total,
+void CABleGattDescriptorDiscoveredCb(int result, unsigned char format, int total,
bt_gatt_attribute_h descriptor,
bt_gatt_attribute_h characteristic, void *userData);
*
* @return 0 on failure and 1 on success.
*/
-bool CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex, int32_t total,
+bool CABleGattCharacteristicsDiscoveredCb(int result, int inputIndex, int total,
bt_gatt_attribute_h characteristic, void *userData);
/**
* @param userData [IN] The user data passed from the request function
* @return NONE
*/
-void CABtGattBondCreatedCb(int32_t result, bt_device_info_s *device_info, void *user_data);
+void CABtGattBondCreatedCb(int result, bt_device_info_s *device_info, void *user_data);
/**
* @brief This is the callback which will be called when we get the primary services repeatedly.
*
* @return 0 on failure and 1 on success.
*/
-bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int32_t index, int32_t count,
+bool CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, int index, int count,
void *userData);
/**
*
* @return NONE
*/
-void CABleGattConnectionStateChangedCb(int32_t result, bool connected, const char *remoteAddress,
- void *userData);
+void CABleGattConnectionStateChangedCb(int result, bool connected,
+ const char *remoteAddress,void *userData);
/**
* @brief This is the callback which will be called when the device discovery state changes.
*
* @return NONE
*/
-void CABtAdapterLeDeviceDiscoveryStateChangedCb(int32_t result,
+void CABtAdapterLeDeviceDiscoveryStateChangedCb(int result,
bt_adapter_le_device_discovery_state_e discoveryState,
bt_adapter_le_device_discovery_info_s *discoveryInfo,
void *userData);
* @param discoveryInfo [IN] Device information structure.
* @return NONE
*/
-void CAPrintDiscoveryInformation(bt_adapter_le_device_discovery_info_s *discoveryInfo);
+void CAPrintDiscoveryInformation(const bt_adapter_le_device_discovery_info_s *discoveryInfo);
/**
* @brief This thread will be used to initialize the Gatt Client and start device discovery.
* @return NONE
*
*/
-void *CAStartBleGattClientThread(void *data);
+void CAStartBleGattClientThread(void *data);
/**
* @brief Used to initialize all required mutex variable for Gatt Client implementation.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitGattClientMutexVaraibles();
+CAResult_t CAInitGattClientMutexVariables();
/**
* @brief Used to terminate all required mutex variable for Gatt Client implementation.
* @param remoteAddress [IN] MAC address of remote device to connect
* @return NONE
*/
-void *CAGattConnectThread (void *remoteAddress);
+void CAGattConnectThread (void *remoteAddress);
/**
* @brief Used to do connection with remote device
* @param remoteAddress [IN] Mac address of the remote device in which we want to search services.
* @return NONE
*/
-void *CADiscoverBLEServicesThread (void *remoteAddress);
+void CADiscoverBLEServicesThread (void *remoteAddress);
/**
* @brief Used to discover the services that is advertised by Gatt Server asynchrounously.
* handle and characteristic handle.
* @return NONE
*/
-void *CADiscoverCharThread(void *stServiceInfo);
+void CADiscoverCharThread(void *stServiceInfo);
/**
* @brief Used to discover characteristics of service using bt_gatt_discover_characteristics api.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABleGattDiscoverCharacteristics(bt_gatt_attribute_h service, const char *remoteAddress);
+CAResult_t CABleGattDiscoverCharacteristics(bt_gatt_attribute_h service,
+ const char *remoteAddress);
/**
* @brief This is the thread which will be used for finding descriptor of characteristic.
* handle and characteristic handle.
* @return NONE
*/
-void *CADiscoverDescriptorThread(void *stServiceInfo);
+void CADiscoverDescriptorThread(void *stServiceInfo);
/**
* @brief This is thread which will be used for calling CASetCharacteristicDescriptorValue api.
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABleGattDiscoverDescriptor(bt_gatt_attribute_h service, const char *remoteAddress);
+CAResult_t CABleGattDiscoverDescriptor(bt_gatt_attribute_h service,
+ const char *remoteAddress);
/**
* @brief This is thread which will be used for calling CASetCharacteristicDescriptorValue api.
* handle and characteristic handle.
* @return NONE
*/
-void *CASetCharacteristicDescriptorValueThread(void *stServiceInfo);
+void CASetCharacteristicDescriptorValueThread(void *stServiceInfo);
/**
* @brief Used to set characteristic descriptor value using
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CASetCharacteristicDescriptorValue(stGattCharDescriptor_t *stGattCharDescriptorInfo);
+CAResult_t CASetCharacteristicDescriptorValue
+ (stGattCharDescriptor_t *stGattCharDescriptorInfo);
/**
* @brief This is the thread which will be used for creating bond with remote device.
* handle, characteristic handle.
* @return NONE
*/
-void *CAGATTCreateBondThread(void *stServiceInfo);
+void CAGATTCreateBondThread(void *stServiceInfo);
/**
* @brief Used to make LE bond with remote device(pairng the device) using bt_device_create_bond
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABleClientSenderQueueEnqueueMessage(const CARemoteEndpoint_t *remoteEndpoint,
- void *data, uint32_t dataLen);
+CAResult_t CABleClientSenderQueueEnqueueMessage
+ (const CARemoteEndpoint_t *remoteEndpoint,
+ const void *data, uint32_t dataLen);
/**
* @brief This is the thread which will be used for processing sender queue.
*
* @return NONE
*/
-void *CABleClientSenderQueueProcessor();
+void CABleClientSenderQueueProcessor();
/**
* @brief Synchronous function for reading characteristic value.
CAResult_t CALEReadDataFromLEClient();
#endif //#ifndef _BLE_CLIENT_
+
#define TZ_LE_NWK_MONITOR_TAG "TZ_BLE_ADAPTER_CONTROLLER"
/**
- * @var gCALEDeviceStateChangedCallback
+ * @var g_bleDeviceStateChangedCallback
* @brief Maintains the callback to be notified on device state changed.
*/
-static CALEDeviceStateChangedCallback gCALEDeviceStateChangedCallback = NULL;
+static CALEDeviceStateChangedCallback g_bleDeviceStateChangedCallback = NULL;
/**
- * @var gCALEDeviceStateChangedCbMutex
+ * @var g_bleDeviceStateChangedCbMutex
* @brief Mutex to synchronize access to the deviceStateChanged Callback when the state
* of the LE adapter gets change.
*/
-static u_mutex gCALEDeviceStateChangedCbMutex = NULL;
+static u_mutex g_bleDeviceStateChangedCbMutex = NULL;
/**
* @fn CALEAdapterStateChangedCb
* @brief This is the callback which will be called when the adapter state gets changed.
*
-* @param[in] result result of the query done to the platform.
-* @param[in] adapter_state State of the LE adapter.
-* @param[in] user_data Any user_data passed by the caller when querying for the state changed cb.
+* @param result [IN] Result of the query done to the platform.
+* @param adapter_state [IN] State of the LE adapter.
+* @param user_data [IN] Any user_data passed by the caller when querying for the state changed cb.
*
* @return None.
-*
*/
-void CALEAdapterStateChangedCb(int32_t result, bt_adapter_state_e adapter_state, void *user_data);
+void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
+ void *user_data);
-CAResult_t CAInitializeLENwkMonitor()
+CAResult_t CAInitializeLENetworkMonitor()
{
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
- CAResult_t res = CAInitLENwkMonitorMutexVaraibles();
+ CAResult_t res = CAInitLENetworkMonitorMutexVariables();
if (CA_STATUS_OK != res)
{
- OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "CAInitLENwkMonitorMutexVaraibles() failed");
+ OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "CAInitLENetworkMonitorMutexVariables() failed");
return CA_STATUS_FAILED;
}
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
-
}
-void CATerminateLENwkMonitorMutexVariables()
+void CATerminateLENetworkMonitorMutexVariables()
{
- OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+ OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
- u_mutex_free(gCALEDeviceStateChangedCbMutex);
- gCALEDeviceStateChangedCbMutex = NULL;
+ u_mutex_free(g_bleDeviceStateChangedCbMutex);
+ g_bleDeviceStateChangedCbMutex = NULL;
- OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
- return;
+ OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
}
-void CATerminateLENwkMonitor()
+void CATerminateLENetworkMonitor()
{
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
- CATerminateLENwkMonitorMutexVariables();
+ CATerminateLENetworkMonitorMutexVariables();
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
-
- return ;
-
}
CAResult_t CAInitializeLEAdapter()
{
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
- CAResult_t res = bt_initialize();
- if (CA_STATUS_OK != res)
+ int ret = bt_initialize();
+ if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_initialize failed");
return CA_STATUS_FAILED;
}
- int32_t ret = bt_adapter_set_visibility(BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, 0);
+ ret = bt_adapter_set_visibility(BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE, 0);
if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_set_visibility failed");
CAResult_t CAGetLEAdapterState()
{
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
- bt_error_e err = BT_ERROR_NONE;
- bt_adapter_state_e adapterState;
+
+ bt_adapter_state_e adapterState = BT_ADAPTER_DISABLED;
//Get Bluetooth adapter state
- if (BT_ERROR_NONE != (err = bt_adapter_get_state(&adapterState)))
+ int ret = bt_adapter_get_state(&adapterState);
+ if (BT_ERROR_NONE != ret)
{
OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "Bluetooth get state failed!, error num [%x]",
- err);
+ ret);
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+ VERIFY_NON_NULL_VOID(local_address, TZ_LE_NWK_MONITOR_TAG, "local_address is null")
+
char *address = NULL;
- bt_adapter_get_address(&address);
+ int ret = bt_adapter_get_address(&address);
+ if (BT_ERROR_NONE != ret || !address)
+ {
+ OIC_LOG_V(ERROR, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_get_address failed!, error num [%x]",
+ ret);
+ return;
+ }
OIC_LOG_V(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bd address[%s]", address);
*local_address = address;
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
- return ;
}
CAResult_t CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCallback callback)
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Setting CALEDeviceStateChangedCallback");
- u_mutex_lock(gCALEDeviceStateChangedCbMutex);
- gCALEDeviceStateChangedCallback = callback;
- u_mutex_unlock(gCALEDeviceStateChangedCbMutex);
+ u_mutex_lock(g_bleDeviceStateChangedCbMutex);
+ g_bleDeviceStateChangedCallback = callback;
+ u_mutex_unlock(g_bleDeviceStateChangedCbMutex);
- int32_t ret = bt_adapter_set_state_changed_cb(CALEAdapterStateChangedCb, NULL);
- if (0 != ret)
+ int ret = bt_adapter_set_state_changed_cb(CALEAdapterStateChangedCb, NULL);
+ if (BT_ERROR_NONE != ret)
{
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_set_state_changed_cb failed");
return CA_STATUS_FAILED;
return CA_STATUS_OK;
}
-void CALEAdapterStateChangedCb(int32_t result, bt_adapter_state_e adapter_state, void *user_data)
+void CALEAdapterStateChangedCb(int result, bt_adapter_state_e adapter_state,
+ void *user_data)
{
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
- u_mutex_lock(gCALEDeviceStateChangedCbMutex);
+ u_mutex_lock(g_bleDeviceStateChangedCbMutex);
- if ( BT_ADAPTER_DISABLED == adapter_state)
+ if (NULL == g_bleDeviceStateChangedCallback)
{
- OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Adapter is disabled");
- if (NULL == gCALEDeviceStateChangedCallback)
- {
- OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "gReqRespCallback is NULL!");
- u_mutex_unlock(gCALEDeviceStateChangedCbMutex);
- return;
- }
+ OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "g_bleDeviceStateChangedCallback is NULL!");
+ u_mutex_unlock(g_bleDeviceStateChangedCbMutex);
+ return;
+ }
- gCALEDeviceStateChangedCallback(CA_ADAPTER_DISABLED);
- u_mutex_unlock(gCALEDeviceStateChangedCbMutex);
+ if (BT_ADAPTER_DISABLED == adapter_state)
+ {
+ OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Adapter is disabled");
+ g_bleDeviceStateChangedCallback(CA_ADAPTER_DISABLED);
+ u_mutex_unlock(g_bleDeviceStateChangedCbMutex);
return;
}
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "Adapter is Enabled");
- gCALEDeviceStateChangedCallback(CA_ADAPTER_ENABLED);
- u_mutex_unlock(gCALEDeviceStateChangedCbMutex);
+ g_bleDeviceStateChangedCallback(CA_ADAPTER_ENABLED);
+ u_mutex_unlock(g_bleDeviceStateChangedCbMutex);
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
- return;
}
{
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
- int32_t ret = bt_adapter_unset_state_changed_cb();
- if (ret != 0)
+ int ret = bt_adapter_unset_state_changed_cb();
+ if (BT_ERROR_NONE != ret)
{
- OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_set_state_changed_cb failed");
+ OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "bt_adapter_unset_state_changed_cb failed");
return CA_STATUS_FAILED;
}
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
-
}
-CAResult_t CAInitLENwkMonitorMutexVaraibles()
+CAResult_t CAInitLENetworkMonitorMutexVariables()
{
- OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
- u_mutex_init();
- if (NULL == gCALEDeviceStateChangedCbMutex)
+ OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "IN");
+ if (NULL == g_bleDeviceStateChangedCbMutex)
{
- gCALEDeviceStateChangedCbMutex = u_mutex_new();
- if (NULL == gCALEDeviceStateChangedCbMutex)
+ g_bleDeviceStateChangedCbMutex = u_mutex_new();
+ if (NULL == g_bleDeviceStateChangedCbMutex)
{
OIC_LOG(ERROR, TZ_LE_NWK_MONITOR_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
OIC_LOG(DEBUG, TZ_LE_NWK_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
-
}
-
-
-
#include "caadapterutils.h"
#include "camsgparser.h"
#include "cableutil.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
/**
* @def TZ_BLE_SERVER_TAG
#define CA_BLE_WRITE_CHAR_UUID "713D0003-503E-4C75-BA94-3148F18D941E"
/**
- * @var gGattSvcPath
+ * @def CA_BLE_INITIAL_BUF_SIZE
+ * @brief Initial buffer size for Gatt Server.
+ */
+#define CA_BLE_INITIAL_BUF_SIZE 512
+
+/**
+ * @var g_gattSvcPath
* @brief attribute handler for OIC server attribute.
*/
-static char *gGattSvcPath = NULL;
+static char *g_gattSvcPath = NULL;
/**
- * @var gGattReadCharPath
+ * @var g_gattReadCharPath
* @brief attribute handler for readCharacteristic of OIC server
*/
-static char *gGattReadCharPath = NULL;
+static char *g_gattReadCharPath = NULL;
/**
- * @var gGattWriteCharPath
+ * @var g_gattWriteCharPath
* @brief attribute handler for writeCharacteristic of OIC server
*/
-static char *gGattWriteCharPath = NULL;
+static char *g_gattWriteCharPath = NULL;
/**
- * @var hAdvertiser
+ * @var g_hAdvertiser
* @brief handler for OIC advertiser.
*/
-static bt_advertiser_h hAdvertiser = NULL;
+static bt_advertiser_h g_hAdvertiser = NULL;
/**
- * @var gCABLEServerDataReceivedCallback
+ * @var g_bleServerDataReceivedCallback
* @brief Maintains the callback to be notified on receival of network packets from other
* BLE devices
*/
-static CABLEServerDataReceivedCallback gCABLEServerDataReceivedCallback = NULL;
+static CABLEServerDataReceivedCallback g_bleServerDataReceivedCallback = NULL;
/**
- * @var gIsBleGattServerStarted
+ * @var g_isBleGattServerStarted
* @brief Boolean variable to keep the state of the GATTServer
*/
-static CABool_t gIsBleGattServerStarted = CA_FALSE;
+static bool g_isBleGattServerStarted = false;
/**
- * @var gBleServerStateMutex
+ * @var g_bleServerStateMutex
* @brief Mutex to synchronize the calls to be done to the platform from GATTServer
* interfaces from different threads.
*/
-static u_mutex gBleServerStateMutex = NULL;
+static u_mutex g_bleServerStateMutex = NULL;
/**
- * @var gBleCharacteristicMutex
+ * @var g_bleCharacteristicMutex
* @brief Mutex to synchronize writing operations on the characteristics.
*/
-static u_mutex gBleCharacteristicMutex = NULL;
+static u_mutex g_bleCharacteristicMutex = NULL;
/**
- * @var gBleServiceMutex
+ * @var g_bleServiceMutex
* @brief Mutex to synchronize to create the OIC service..
*/
-static u_mutex gBleServiceMutex = NULL;
+static u_mutex g_bleServiceMutex = NULL;
/**
- * @var gBleClientBDAddressMutex
+ * @var g_bleClientBDAddressMutex
* @brief Mutex to synchronize the client BD Address update on server side.
*/
-static u_mutex gBleClientBDAddressMutex = NULL;
+static u_mutex g_bleClientBDAddressMutex = NULL;
/**
- * @var gBleReqRespCbMutex
+ * @var g_bleReqRespCbMutex
* @brief Mutex to synchronize access to the requestResponse callback to be called
* when the data needs to be sent from GATTClient.
*/
-static u_mutex gBleReqRespCbMutex = NULL;
+static u_mutex g_bleReqRespCbMutex = NULL;
/**
- * @var gBleServerThreadPoolMutex
+ * @var g_bleServerThreadPoolMutex
* @brief Mutex to synchronize the task to be pushed to thread pool.
*/
-static u_mutex gBleServerThreadPoolMutex = NULL;
-
-/**
- * @var gBleServerSendCondWait
- * @brief Condition used for notifying handler the presence of data in send queue.
- */
-static u_cond gBleServerSendCondWait = NULL;
-
-/**
- * @var gReceiverDataCond
- * @brief Condition used for notifying handler the presence of data in recv queue.
- */
-static u_cond gReceiverDataCond = NULL;
-
-/**
- * @var gDataReceiverHandlerState
- * @brief Stop condition of redvhandler.
- */
-static bool gDataReceiverHandlerState = false;
+static u_mutex g_bleServerThreadPoolMutex = NULL;
/**
* @struct gRemoteAddress
* @brief Remote address of Gatt client
*
*/
-static char *gRemoteClientAddress = NULL;
+static char *g_remoteClientAddress = NULL;
/**
- * @var g_event_loop
+ * @var g_eventLoop
* @brief gmainLoop to manage the threads to receive the callback from the platfrom.
*/
-static GMainLoop *g_event_loop = NULL;
+static GMainLoop *g_eventLoop = NULL;
/**
- * @var gBleServerThreadPool
+ * @var g_bleServerThreadPool
* @brief reference to threadpool
*/
-static u_thread_pool_t gBleServerThreadPool = NULL;
+static u_thread_pool_t g_bleServerThreadPool = NULL;
-/**
- * @var gServerUp
- * @brief Boolean variable to maintain the GATT Server state.
- */
-static CABool_t gServerUp = CA_FALSE;
-
-void CABleGattServerConnectionStateChangedCb(int32_t result, bool connected,
+void CABleGattServerConnectionStateChangedCb(int result, bool connected,
const char *remoteAddress, void *userData)
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
{
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Connected to [%s]", remoteAddress);
- u_mutex_lock(gBleClientBDAddressMutex);
- gRemoteClientAddress = OICStrdup(remoteAddress);
- u_mutex_unlock(gBleClientBDAddressMutex);
+ u_mutex_lock(g_bleClientBDAddressMutex);
+ g_remoteClientAddress = OICStrdup(remoteAddress);
+ u_mutex_unlock(g_bleClientBDAddressMutex);
- VERIFY_NON_NULL_VOID(gRemoteClientAddress, TZ_BLE_SERVER_TAG, "Malloc failed");
+ VERIFY_NON_NULL_VOID(g_remoteClientAddress, TZ_BLE_SERVER_TAG, "Malloc failed");
}
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
}
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- CAResult_t ret = CAInitGattServerMutexVaraibles();
-
+ CAResult_t ret = CAInitGattServerMutexVariables();
if (CA_STATUS_OK != ret )
{
- OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAInitGattServerMutexVaraibles failed!");
- CATerminateGattServerMutexVaraibles();
+ OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAInitGattServerMutexVariables failed!");
+ CATerminateGattServerMutexVariables();
return CA_SERVER_NOT_STARTED;
}
- u_mutex_lock(gBleServerThreadPoolMutex);
- if (NULL == gBleServerThreadPool)
+ u_mutex_lock(g_bleServerThreadPoolMutex);
+ if (NULL == g_bleServerThreadPool)
{
- OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gBleServerThreadPool is NULL");
- u_mutex_unlock(gBleServerThreadPoolMutex);
+ OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_bleServerThreadPool is NULL");
+ u_mutex_unlock(g_bleServerThreadPoolMutex);
return CA_STATUS_FAILED;
}
- ret = u_thread_pool_add_task(gBleServerThreadPool, (void *) CAStartBleGattServerThread,
- (void *) NULL);
+ ret = u_thread_pool_add_task(g_bleServerThreadPool, CAStartBleGattServerThread,
+ NULL);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "u_thread_pool_add_task failed with ret [%d]", ret);
- u_mutex_unlock(gBleServerThreadPoolMutex);
+ u_mutex_unlock(g_bleServerThreadPoolMutex);
return CA_STATUS_FAILED;
}
- gDataReceiverHandlerState = true;
-
- u_mutex_unlock(gBleServerThreadPoolMutex);
+ u_mutex_unlock(g_bleServerThreadPoolMutex);
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
return CA_STATUS_OK;
}
-void *CAStartBleGattServerThread(void *data)
+void CAStartBleGattServerThread(void *data)
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- u_mutex_lock(gBleServerStateMutex);
- if (CA_TRUE == gIsBleGattServerStarted)
+ u_mutex_lock(g_bleServerStateMutex);
+ if (true == g_isBleGattServerStarted)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Gatt Server is already running");
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
CATerminateBleGattServer();
- return NULL;
+ return;
}
CAResult_t ret = CAInitBleGattService();
if (CA_STATUS_OK != ret )
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_init_service failed");
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
CATerminateBleGattServer();
- return NULL;
+ return;
}
- sleep(5); // Sleep is must. otherwise its crashing
+ sleep(5); // Sleep is must because of the platform issue.
char *serviceUUID = CA_BLE_SERVICE_UUID;
if (CA_STATUS_OK != ret )
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewBleServiceInGattServer failed");
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
CATerminateBleGattServer();
- return NULL;
+ return;
}
char *charReadUUID = CA_BLE_READ_CHAR_UUID;
- char charReadValue[4] = {33, 44, 55, 66};
+ char charReadValue[] = {33, 44, 55, 66}; // These are initial random values
- ret = CAAddNewCharacteristicsToGattServer(gGattSvcPath, charReadUUID, charReadValue, 512 ,
- 0); // For Read Characteristics.
+ ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charReadUUID, charReadValue,
+ CA_BLE_INITIAL_BUF_SIZE, false); // For Read Characteristics.
if (CA_STATUS_OK != ret )
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
CATerminateBleGattServer();
- return NULL;
+ return;
}
char *charWriteUUID = CA_BLE_WRITE_CHAR_UUID;
- char charWriteValue[4] = {33, 44, 55, 66};
+ char charWriteValue[] = {33, 44, 55, 66}; // These are initial random values
- ret = CAAddNewCharacteristicsToGattServer(gGattSvcPath, charWriteUUID, charWriteValue, 512 ,
- 1); // For Write Characteristics.
+ ret = CAAddNewCharacteristicsToGattServer(g_gattSvcPath, charWriteUUID, charWriteValue,
+ CA_BLE_INITIAL_BUF_SIZE, true); // For Write Characteristics.
if (CA_STATUS_OK != ret )
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CAAddNewCharacteristicsToGattServer failed");
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
CATerminateBleGattServer();
- return NULL;
+ return;
}
- ret = CARegisterBleServicewithGattServer(gGattSvcPath);
+ ret = CARegisterBleServicewithGattServer(g_gattSvcPath);
if (CA_STATUS_OK != ret )
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "CARegisterBleServicewithGattServer failed");
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
CATerminateBleGattServer();
- return NULL;
+ return;
}
- int32_t res = bt_gatt_set_connection_state_changed_cb(CABleGattServerConnectionStateChangedCb,
+ int res = bt_gatt_set_connection_state_changed_cb(CABleGattServerConnectionStateChangedCb,
NULL);
if (BT_ERROR_NONE != res)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
"bt_gatt_set_connection_state_changed_cb Failed with return as [%s]",
CABTGetErrorMsg(res));
- return NULL;
+ return;
}
- bt_adapter_le_create_advertiser(&hAdvertiser);
- if (NULL == hAdvertiser)
+ bt_adapter_le_create_advertiser(&g_hAdvertiser);
+ if (NULL == g_hAdvertiser)
{
- OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "hAdvertiser is NULL");
- u_mutex_unlock(gBleServerStateMutex);
+ OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_hAdvertiser is NULL");
+ u_mutex_unlock(g_bleServerStateMutex);
CATerminateBleGattServer();
- return NULL;
+ return;
}
- int32_t retVal = bt_adapter_le_start_advertising(hAdvertiser, NULL, NULL, NULL);
- if (BT_ERROR_NONE != retVal)
+ res = bt_adapter_le_start_advertising(g_hAdvertiser, NULL, NULL, NULL);
+ if (BT_ERROR_NONE != res)
{
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "bt_adapter_le_start_advertising failed with ret [%d] ",
- retVal);
- u_mutex_unlock(gBleServerStateMutex);
+ res);
+ u_mutex_unlock(g_bleServerStateMutex);
CATerminateBleGattServer();
- return NULL;
+ return;
}
- gIsBleGattServerStarted = CA_TRUE;
+ g_isBleGattServerStarted = true;
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG,
- "LE Server initialization complete. Enabling gServerUp state to TRUE ");
- gServerUp = CA_TRUE;
+ "LE Server initialization complete.");
GMainContext *thread_context = NULL;
thread_context = g_main_context_new();
- g_event_loop = g_main_loop_new(thread_context, FALSE);
+ g_eventLoop = g_main_loop_new(thread_context, FALSE);
g_main_context_push_thread_default(thread_context);
- g_main_loop_run(g_event_loop);
+ g_main_loop_run(g_eventLoop);
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
-
- return NULL;
-
}
CAResult_t CAStopBleGattServer()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- u_mutex_lock(gBleServerStateMutex);
+ u_mutex_lock(g_bleServerStateMutex);
- if (CA_FALSE == gIsBleGattServerStarted)
+ if (false == g_isBleGattServerStarted)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Gatt Server is not running to stop");
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
return CA_STATUS_OK;
}
- u_mutex_unlock(gBleServerStateMutex);
-
- // Stop data send and receive handlers
- if (gDataReceiverHandlerState)
- {
- u_cond_signal(gReceiverDataCond);
- }
+ u_mutex_unlock(g_bleServerStateMutex);
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- gIsBleGattServerStarted = CA_FALSE;
- gServerUp = CA_FALSE;
- u_cond_signal(gBleServerSendCondWait);
+ g_isBleGattServerStarted = false;
- u_mutex_lock(gBleServerStateMutex);
+ u_mutex_lock(g_bleServerStateMutex);
GMainContext *context_event_loop = NULL;
// Required for waking up the thread which is running in gmain loop
- if ( NULL != g_event_loop)
+ if ( NULL != g_eventLoop)
{
- context_event_loop = g_main_loop_get_context(g_event_loop);
+ context_event_loop = g_main_loop_get_context(g_eventLoop);
}
if (context_event_loop)
{
- OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "g_event_loop context %x", context_event_loop);
+ OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "g_eventLoop context %x", context_event_loop);
g_main_context_wakeup(context_event_loop);
// Kill g main loops and kill threads
- g_main_loop_quit(g_event_loop);
+ g_main_loop_quit(g_eventLoop);
}
else
{
- OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_event_loop context is NULL");
+ OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_eventLoop context is NULL");
}
- int32_t ret = 0;
- if (NULL != hAdvertiser )
+ if (NULL != g_hAdvertiser )
{
- ret = bt_adapter_le_stop_advertising(hAdvertiser);
+ int ret = 0;
+ ret = bt_adapter_le_stop_advertising(g_hAdvertiser);
if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
"bt_adapter_le_stop_advertising failed with ret [%d]", ret);
}
- ret = bt_adapter_le_destroy_advertiser(hAdvertiser);
+ ret = bt_adapter_le_destroy_advertiser(g_hAdvertiser);
if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
"bt_adapter_le_destroy_advertiser failed with ret [%d]", ret);
}
- hAdvertiser = NULL;
+ g_hAdvertiser = NULL;
}
- ret = CARemoveAllBleServicesFromGattServer();
- if (0 != ret)
+ CAResult_t res = CARemoveAllBleServicesFromGattServer();
+ if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "removeAllBleServicesFromGattServer failed");
}
- ret = CADeInitBleGattService();
- if (0 != ret)
+ res = CADeInitBleGattService();
+ if (CA_STATUS_OK != res)
{
- OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", ret);
+ OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", res);
}
- u_mutex_lock(gBleClientBDAddressMutex);
- OICFree(gRemoteClientAddress);
- u_mutex_unlock(gBleClientBDAddressMutex);
+ u_mutex_lock(g_bleClientBDAddressMutex);
+ OICFree(g_remoteClientAddress);
+ u_mutex_unlock(g_bleClientBDAddressMutex);
// free service Path(unique identifier for ble service)
- u_mutex_lock(gBleServiceMutex);
- OICFree(gGattSvcPath);
- gGattSvcPath = NULL;
- u_mutex_unlock(gBleServiceMutex);
+ u_mutex_lock(g_bleServiceMutex);
+ OICFree(g_gattSvcPath);
+ g_gattSvcPath = NULL;
+ u_mutex_unlock(g_bleServiceMutex);
// freeing characteristics
- u_mutex_lock(gBleCharacteristicMutex);
- OICFree(gGattReadCharPath);
- gGattReadCharPath = NULL;
- OICFree(gGattWriteCharPath);
- gGattWriteCharPath = NULL;
- u_mutex_unlock(gBleCharacteristicMutex);
+ u_mutex_lock(g_bleCharacteristicMutex);
+ OICFree(g_gattReadCharPath);
+ g_gattReadCharPath = NULL;
+ OICFree(g_gattWriteCharPath);
+ g_gattWriteCharPath = NULL;
+ u_mutex_unlock(g_bleCharacteristicMutex);
- u_mutex_unlock(gBleServerStateMutex);
+ u_mutex_unlock(g_bleServerStateMutex);
// Terminating all mutex variables.
- CATerminateGattServerMutexVaraibles();
+ CATerminateGattServerMutexVariables();
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
}
-CAResult_t CAInitGattServerMutexVaraibles()
+CAResult_t CAInitGattServerMutexVariables()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- u_mutex_init();
- if (NULL == gBleServerStateMutex)
+ if (NULL == g_bleServerStateMutex)
{
- gBleServerStateMutex = u_mutex_new();
- if (NULL == gBleServerStateMutex)
+ g_bleServerStateMutex = u_mutex_new();
+ if (NULL == g_bleServerStateMutex)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleServiceMutex)
+ if (NULL == g_bleServiceMutex)
{
- gBleServiceMutex = u_mutex_new();
- if (NULL == gBleServiceMutex)
+ g_bleServiceMutex = u_mutex_new();
+ if (NULL == g_bleServiceMutex)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleCharacteristicMutex)
+ if (NULL == g_bleCharacteristicMutex)
{
- gBleCharacteristicMutex = u_mutex_new();
- if (NULL == gBleCharacteristicMutex)
+ g_bleCharacteristicMutex = u_mutex_new();
+ if (NULL == g_bleCharacteristicMutex)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleReqRespCbMutex)
+ if (NULL == g_bleReqRespCbMutex)
{
- gBleReqRespCbMutex = u_mutex_new();
- if (NULL == gBleReqRespCbMutex)
+ g_bleReqRespCbMutex = u_mutex_new();
+ if (NULL == g_bleReqRespCbMutex)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
}
}
- if (NULL == gBleClientBDAddressMutex)
+ if (NULL == g_bleClientBDAddressMutex)
{
- gBleClientBDAddressMutex = u_mutex_new();
- if (NULL == gBleClientBDAddressMutex)
+ g_bleClientBDAddressMutex = u_mutex_new();
+ if (NULL == g_bleClientBDAddressMutex)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "u_mutex_new failed");
return CA_STATUS_FAILED;
return CA_STATUS_OK;
}
-void CATerminateGattServerMutexVaraibles()
+
+void CATerminateGattServerMutexVariables()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- u_mutex_free(gBleServerStateMutex);
- gBleServerStateMutex = NULL;
+ u_mutex_free(g_bleServerStateMutex);
+ g_bleServerStateMutex = NULL;
- u_mutex_free(gBleClientBDAddressMutex);
- gBleClientBDAddressMutex = NULL;
+ u_mutex_free(g_bleClientBDAddressMutex);
+ g_bleClientBDAddressMutex = NULL;
- gBleServerStateMutex = NULL;
- u_mutex_free(gBleServiceMutex);
- gBleServiceMutex = NULL;
- u_mutex_free(gBleCharacteristicMutex);
- gBleCharacteristicMutex = NULL;
- u_mutex_free(gBleReqRespCbMutex);
- gBleReqRespCbMutex = NULL;
+ g_bleServerStateMutex = NULL;
+ u_mutex_free(g_bleServiceMutex);
+ g_bleServiceMutex = NULL;
+ u_mutex_free(g_bleCharacteristicMutex);
+ g_bleCharacteristicMutex = NULL;
+ u_mutex_free(g_bleReqRespCbMutex);
+ g_bleReqRespCbMutex = NULL;
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
}
+
CAResult_t CAInitBleGattService()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- int32_t ret = _bt_gatt_init_service();
+
+ int ret = _bt_gatt_init_service();
if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", ret);
return CA_STATUS_FAILED;
}
+
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
return CA_STATUS_OK;
}
-
CAResult_t CADeInitBleGattService()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- int32_t ret = _bt_gatt_deinit_service();
+ int ret = _bt_gatt_deinit_service();
if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "_bt_gatt_deinit_service failed with ret [%d]", ret);
return CA_STATUS_FAILED;
}
+
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
return CA_STATUS_OK;
}
void CASetBleServerThreadPoolHandle(u_thread_pool_t handle)
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- u_mutex_lock(gBleServerThreadPoolMutex);
- gBleServerThreadPool = handle;
- u_mutex_unlock(gBleServerThreadPoolMutex);
+ u_mutex_lock(g_bleServerThreadPoolMutex);
+ g_bleServerThreadPool = handle;
+ u_mutex_unlock(g_bleServerThreadPoolMutex);
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
}
char *svcPath = NULL;
- int32_t ret = bt_gatt_add_service(serviceUUID, &svcPath);
+ int ret = bt_gatt_add_service(serviceUUID, &svcPath);
if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_add_service failed with ret [%d]", ret);
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
"AddNewBleServiceInGattServer ServicePath obtained is %s", svcPath);
- u_mutex_lock(gBleServiceMutex);
+ u_mutex_lock(g_bleServiceMutex);
- if (NULL != gGattSvcPath)
+ if (NULL != g_gattSvcPath)
{
- OICFree(gGattSvcPath);
- gGattSvcPath = NULL;
+ OICFree(g_gattSvcPath);
+ g_gattSvcPath = NULL;
}
- gGattSvcPath = svcPath;
+ g_gattSvcPath = svcPath;
- u_mutex_unlock(gBleServiceMutex);
+ u_mutex_unlock(g_bleServiceMutex);
}
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
VERIFY_NON_NULL(svcPath, NULL, "Param svcPath is NULL");
- int32_t ret = bt_gatt_remove_service(svcPath);
+ int ret = bt_gatt_remove_service(svcPath);
if (0 != ret)
{
CAResult_t CARemoveAllBleServicesFromGattServer()
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- int32_t ret = bt_gatt_delete_services();
+ int ret = bt_gatt_delete_services();
if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG, "bt_gatt_delete_services failed with ret [%d]", ret);
void CABleGattRemoteCharacteristicWriteCb(char *charPath,
unsigned char *charValue,
- int32_t charValueLen, void *userData)
+ int charValueLen, void *userData)
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "charPath = [%s] charValue = [%s] len [%d]", charPath,
charValue, charValueLen);
- char *data = (char *)OICMalloc(sizeof(char) * charValueLen + 1);
+ char *data = (char *)OICMalloc(sizeof(char) * charValueLen);
if (NULL == data)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "Malloc failed!");
return;
}
- memset(data, 0x0, charValueLen + 1);
strncpy(data, (char *)charValue, charValueLen);
- uint32_t sentLength = 0;
-
- u_mutex_lock(gBleReqRespCbMutex);
- if (NULL == gCABLEServerDataReceivedCallback)
+ u_mutex_lock(g_bleReqRespCbMutex);
+ if (NULL == g_bleServerDataReceivedCallback)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gReqRespCallback is NULL!");
- u_mutex_unlock(gBleReqRespCbMutex);
+ u_mutex_unlock(g_bleReqRespCbMutex);
OICFree(data);
return;
}
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "Sending data up !");
- u_mutex_lock(gBleClientBDAddressMutex);
- gCABLEServerDataReceivedCallback(gRemoteClientAddress, OIC_BLE_SERVICE_ID,
- data, strlen(data), &sentLength);
- u_mutex_unlock(gBleClientBDAddressMutex);
+ u_mutex_lock(g_bleClientBDAddressMutex);
+ uint32_t sentLength = 0;
+ g_bleServerDataReceivedCallback(g_remoteClientAddress, OIC_BLE_SERVICE_ID,
+ data, charValueLen, &sentLength);
+ u_mutex_unlock(g_bleClientBDAddressMutex);
- u_mutex_unlock(gBleReqRespCbMutex);
+ u_mutex_unlock(g_bleReqRespCbMutex);
OICFree(data);
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "svcPath:%s", svcPath);
- int32_t ret = bt_gatt_register_service(svcPath, CABleGattRemoteCharacteristicWriteCb, NULL);
+ int ret = bt_gatt_register_service(svcPath, CABleGattRemoteCharacteristicWriteCb, NULL);
if (0 != ret)
{
return CA_STATUS_OK;
}
-CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, char *charUUID,
- char *charValue, int32_t charValueLen, int32_t read)
+CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *charUUID,
+ const char *charValue, int charValueLen, bool read)
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- const char *charFlags[4] = {"read", "write", "notify", "indicate"};
-
- char *charPath = NULL;
+ static const char *charFlags[] = {"read", "write", "notify", "indicate"};
- int32_t flagLen = 4;
+ static const size_t flagLen = sizeof(charFlags) / sizeof(charFlags[0]);
- int32_t ret = bt_gatt_add_characteristic(charUUID, charValue, charValueLen, charFlags, flagLen,
+ char *charPath = NULL;
+ int ret = bt_gatt_add_characteristic(charUUID, charValue, charValueLen, charFlags, flagLen,
svcPath, &charPath);
if (0 != ret || NULL == charPath)
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG,
"bt_gatt_add_characteristic charPath obtained: %s", charPath);
- u_mutex_lock(gBleCharacteristicMutex);
+ u_mutex_lock(g_bleCharacteristicMutex);
- if (0 == read)
+ if (!read)
{
- if (NULL != gGattReadCharPath)
+ if (NULL != g_gattReadCharPath)
{
- OICFree(gGattReadCharPath);
- gGattReadCharPath = NULL;
+ OICFree(g_gattReadCharPath);
+ g_gattReadCharPath = NULL;
}
- gGattReadCharPath = charPath;
+ g_gattReadCharPath = charPath;
}
else
{
- if (NULL != gGattWriteCharPath)
+ if (NULL != g_gattWriteCharPath)
{
- OICFree(gGattWriteCharPath);
- gGattWriteCharPath = NULL;
+ OICFree(g_gattWriteCharPath);
+ g_gattWriteCharPath = NULL;
}
- gGattWriteCharPath = charPath;
+ g_gattWriteCharPath = charPath;
}
- u_mutex_unlock(gBleCharacteristicMutex);
+ u_mutex_unlock(g_bleCharacteristicMutex);
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(charValue, NULL, "Param charValue is NULL");
- u_mutex_lock(gBleCharacteristicMutex);
+ u_mutex_lock(g_bleCharacteristicMutex);
- if (NULL == gGattWriteCharPath)
+ if (NULL == g_gattWriteCharPath)
{
- OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gGattWriteCharPath is NULL");
- u_mutex_unlock(gBleCharacteristicMutex);
+ OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "g_gattWriteCharPath is NULL");
+ u_mutex_unlock(g_bleCharacteristicMutex);
return CA_STATUS_FAILED;
}
if (NULL == data)
{
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "malloc failed!");
- u_mutex_unlock(gBleCharacteristicMutex);
+ u_mutex_unlock(g_bleCharacteristicMutex);
return CA_STATUS_FAILED;
}
- memset(data, 0x0, (charValueLen + 1));
- strncpy(data, charValue, charValueLen);
+ strncpy(data, charValue, charValueLen + 1);
OIC_LOG_V(DEBUG, TZ_BLE_SERVER_TAG, "updating characteristics char [%s] data [%s] dataLen [%d]",
- (const char *)gGattWriteCharPath, data, charValueLen);
+ (const char *)g_gattWriteCharPath, data, charValueLen);
- int32_t ret = bt_gatt_update_characteristic(gGattWriteCharPath, data, charValueLen);
+ int ret = bt_gatt_update_characteristic(g_gattWriteCharPath, data, charValueLen);
if (0 != ret)
{
OIC_LOG_V(ERROR, TZ_BLE_SERVER_TAG,
"bt_gatt_update_characteristic failed with return [%d]", ret);
OICFree(data);
data = NULL;
- u_mutex_unlock(gBleCharacteristicMutex);
+ u_mutex_unlock(g_bleCharacteristicMutex);
return CA_STATUS_FAILED;
}
OICFree(data);
- u_mutex_unlock(gBleCharacteristicMutex);
+ u_mutex_unlock(g_bleCharacteristicMutex);
OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN");
- u_mutex_lock(gBleReqRespCbMutex);
+ u_mutex_lock(g_bleReqRespCbMutex);
- gCABLEServerDataReceivedCallback = callback;
+ g_bleServerDataReceivedCallback = callback;
- u_mutex_unlock(gBleReqRespCbMutex);
+ u_mutex_unlock(g_bleReqRespCbMutex);
OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
}
-
* @param data [IN] Currently it will be NULL.
* @return NONE
*/
-void *CAStartBleGattServerThread(void *data);
+void CAStartBleGattServerThread(void *data);
/**
* @brief Used to initialize gatt service using _bt_gatt_init_service api.
CAResult_t CADeInitBleGattService();
/**
- * @brief Used to initialize all required mutex varaibles for GATT server implementation.
+ * @brief Used to initialize all required mutex variables for GATT server implementation.
*
* @return #CA_STATUS_OK or Appropriate error code
* @retval #CA_STATUS_OK Successful
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAInitGattServerMutexVaraibles();
+CAResult_t CAInitGattServerMutexVariables();
/**
- * @brief Used to terminate all required mutex varaibles for GATT server implementation.
+ * @brief Used to terminate all required mutex variables for GATT server implementation.
* @return NONE
*/
-void CATerminateGattServerMutexVaraibles();
+void CATerminateGattServerMutexVariables();
/**
* @brief Used to add new OIC service in GATT server using bt_gatt_add_service api and
* write characteristics.
* @return #CA_STATUS_OK or Appropriate error code
*/
-CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, char *charUUID,
- char *charValue, int32_t charValueLen,
- int32_t read);
+CAResult_t CAAddNewCharacteristicsToGattServer(const char *svcPath, const char *charUUID,
+ const char *charValue, int charValueLen,
+ bool read);
/**
* @brief Used to remove characteristics(Read/Write) from the service in Gatt Server.
* @return NONE
*/
void CABleGattRemoteCharacteristicWriteCb(char *charPath, unsigned char *charValue,
- int32_t charValueLen, void *userData);
+ int charValueLen, void *userData);
/**
* @brief This is the callback which will be called whenever there is change in gatt connection
*
* @return NONE
*/
-void CABleGattServerConnectionStateChangedCb(int32_t result, bool connected,
+void CABleGattServerConnectionStateChangedCb(int result, bool connected,
const char *remoteAddress, void *userData);
/**
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CABleServerSenderQueueEnqueueMessage(const CARemoteEndpoint_t *remoteEndpoint,
- void *data, uint32_t dataLen);
+CAResult_t CABleServerSenderQueueEnqueueMessage
+ (const CARemoteEndpoint_t *remoteEndpoint, const void *data, uint32_t dataLen);
/**
* @brief This is the thread which will be used for processing receiver queue.
void *CABleServerSenderQueueProcessor();
#endif //#ifndef __TZ_BLE_SERVER_H_
+
#include "caadapterutils.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
+/**
+ * @def TZ_BLE_CLIENT_UTIL_TAG
+ * @brief Logging tag for module name
+ */
#define TZ_BLE_CLIENT_UTIL_TAG "TZ_BLE_GATT_CLIENT_UTIL"
-static int32_t gNumberOfServiceConnected = 0;
+/**
+ * @var g_numberOfServiceConnected
+ * @brief Number of services connected.
+ */
+static int32_t g_numberOfServiceConnected = 0;
void CAIncrementRegisteredServiceCount()
{
- gNumberOfServiceConnected++;
+ g_numberOfServiceConnected++;
}
void CADecrementRegisteredServiceCount()
{
- gNumberOfServiceConnected--;
+ g_numberOfServiceConnected--;
}
void CAResetRegisteredServiceCount()
{
- gNumberOfServiceConnected = 0;
+ g_numberOfServiceConnected = 0;
}
int32_t CAGetRegisteredServiceCount()
{
- return gNumberOfServiceConnected ;
+ return g_numberOfServiceConnected ;
}
CAResult_t CACreateBLEServiceInfo(const char *bdAddress, bt_gatt_attribute_h service,
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
- VERIFY_NON_NULL(bdAddress, NULL, " Param bdAddress is NULL");
- VERIFY_NON_NULL(service, NULL, " Param service is NULL");
+ VERIFY_NON_NULL(bdAddress, NULL, "Param bdAddress is NULL");
+ VERIFY_NON_NULL(service, NULL, "Param service is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, NULL, "Param bleServiceInfo is NULL");
- *bleServiceInfo = (BLEServiceInfo *) OICMalloc(sizeof(BLEServiceInfo));
+ *bleServiceInfo = (BLEServiceInfo *) OICCalloc(1, sizeof(BLEServiceInfo));
if (NULL == *bleServiceInfo)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, " Malloc failed!");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
return CA_STATUS_FAILED;
}
- memset(*bleServiceInfo, 0x0, sizeof(BLEServiceInfo));
- int32_t len = strlen(bdAddress);
- (*bleServiceInfo)->bdAddress = (char *) OICMalloc(sizeof(char) * len + 1);
+ size_t len = strlen(bdAddress);
+ (*bleServiceInfo)->bdAddress = (char *) OICMalloc(sizeof(char) * (len + 1));
if (NULL == (*bleServiceInfo)->bdAddress)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, " Malloc failed!");
-
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
OICFree(*bleServiceInfo);
return CA_STATUS_FAILED;
}
- memset((*bleServiceInfo)->bdAddress, 0x0, len + 1);
- strncpy((*bleServiceInfo)->bdAddress, bdAddress, len);
+ strncpy((*bleServiceInfo)->bdAddress, bdAddress, len + 1);
if (service)
{
-
int32_t ret = bt_gatt_clone_attribute_handle(&((*bleServiceInfo)->service_clone), service);
if (BT_ERROR_NONE != ret)
{
- OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, " service handle clone failed with ret [%d]",
+ OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "service handle clone failed with ret [%d]",
ret);
OICFree((*bleServiceInfo)->bdAddress);
OICFree(*bleServiceInfo);
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
- VERIFY_NON_NULL(characteristic, NULL, " Param characteristic is NULL");
- VERIFY_NON_NULL(bleServiceInfo, NULL, " Param bleServiceInfo is NULL");
+ VERIFY_NON_NULL(characteristic, NULL, "Param characteristic is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, NULL, "Param bleServiceInfo is NULL");
- if (READ_CHAR == type )
+ if (BLE_GATT_READ_CHAR == type )
{
- int32_t ret = bt_gatt_clone_attribute_handle(&((bleServiceInfo)->read_char), characteristic);
+ int ret = bt_gatt_clone_attribute_handle(&((bleServiceInfo)->read_char),
+ characteristic);
if (BT_ERROR_NONE != ret)
{
- OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, " read_char clone failed with ret [%d]",
+ OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "read_char clone failed with ret [%d]",
ret);
return CA_STATUS_FAILED;
}
}
- else if (WRITE_CHAR == type)
+ else if (BLE_GATT_WRITE_CHAR == type)
{
- int32_t ret = bt_gatt_clone_attribute_handle(&((bleServiceInfo)->write_char), characteristic);
+ int ret = bt_gatt_clone_attribute_handle(&((bleServiceInfo)->write_char),
+ characteristic);
if (BT_ERROR_NONE != ret)
{
- OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, " write_char clone failed with ret [%d]",
+ OIC_LOG_V(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "write_char clone failed with ret [%d]",
ret);
return CA_STATUS_FAILED;
}
return CA_STATUS_OK;
}
-CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList, BLEServiceInfo *bleServiceInfo)
+CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList,
+ BLEServiceInfo *bleServiceInfo)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
- VERIFY_NON_NULL(serviceList, NULL, " Param serviceList is NULL");
- VERIFY_NON_NULL(bleServiceInfo, NULL, " Param bleServiceInfo is NULL");
+ VERIFY_NON_NULL(serviceList, NULL, "Param serviceList is NULL");
+ VERIFY_NON_NULL(bleServiceInfo, NULL, "Param bleServiceInfo is NULL");
- BLEServiceList *node = (BLEServiceList *) OICMalloc(sizeof(BLEServiceList));
+ BLEServiceList *node = (BLEServiceList *) OICCalloc(1, sizeof(BLEServiceList));
if (NULL == node)
{
- OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "[ERROR]Malloc failed!");
+ OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Malloc failed!");
OICFree(bleServiceInfo->bdAddress);
OICFree(bleServiceInfo);
return CA_STATUS_FAILED;
}
- memset(node, 0x0, sizeof(BLEServiceList));
node->serviceInfo = bleServiceInfo;
node->next = NULL;
- if (*serviceList == NULL) //Empty list
+ if (*serviceList == NULL) // Empty list
{
*serviceList = node;
}
- else //Add at front end
+ else // Add at front end
{
node->next = *serviceList;
*serviceList = node;
CAIncrementRegisteredServiceCount();
- OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "Device [%s] added to list", bleServiceInfo->bdAddress);
+ OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "Device [%s] added to list",
+ bleServiceInfo->bdAddress);
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
VERIFY_NON_NULL(*serviceList, NULL, "Param *serviceList is NULL");
VERIFY_NON_NULL(bdAddress, NULL, "Param bdAddress is NULL");
- BLEServiceList *cur = NULL;
BLEServiceList *prev = NULL;
-
- cur = *serviceList;
+ BLEServiceList *cur = *serviceList;
while (cur != NULL)
{
if (!strcasecmp(cur->serviceInfo->bdAddress, bdAddress))
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, " OUT");
return CA_STATUS_FAILED;
-
}
CAResult_t CAGetBLEServiceInfo(BLEServiceList *serviceList, const char *bdAddress,
OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "Position Invalid input !");
return CA_STATUS_INVALID_PARAM;
}
- BLEServiceList *cur = serviceList;
+
*bleServiceInfo = NULL;
int32_t count = 0;
-
+ BLEServiceList *cur = serviceList;
while (cur != NULL)
{
if (position == count)
OICFree(temp);
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
- return ;
}
void CAFreeBLEServiceInfo(BLEServiceInfo *bleServiceInfo)
OICFree(bleServiceInfo);
}
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "OUT");
- return ;
}
-
CAResult_t CAVerifyOICServiceByUUID(const char* serviceUUID)
{
OIC_LOG(DEBUG, TZ_BLE_CLIENT_UTIL_TAG, "IN");
VERIFY_NON_NULL(serviceUUID, NULL, "Param serviceHandle is NULL");
-/*
- int32_t ret = 0;
- char *uuid = NULL;
- ret = bt_gatt_get_service_uuid(serviceHandle, &uuid);
-
- if (0 != ret)
- {
- OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "bt_gatt_get_service_uuid failed !");
- return CA_STATUS_FAILED;
- }
-*/
if (strcasecmp(serviceUUID, OIC_BLE_SERVICE_ID) != 0)
{
OIC_LOG(ERROR, TZ_BLE_CLIENT_UTIL_TAG, "It is not OIC service!");
VERIFY_NON_NULL(serviceHandle, NULL, "Param serviceHandle is NULL");
- int32_t ret = 0;
char *uuid = NULL;
-
- ret = bt_gatt_get_service_uuid(serviceHandle, &uuid);
+ int ret = bt_gatt_get_service_uuid(serviceHandle, &uuid);
if (0 != ret)
{
return errStr;
}
+
#include <bluetooth.h>
#include "cacommon.h"
-#include "logger.h"
-
/**
* @struct BLEServiceInfo
*/
typedef struct
{
- bt_gatt_attribute_h service_clone; /**< gatt_attribute handler for the OIC service. */
- bt_gatt_attribute_h
- read_char; /**<gatt_attribute handler for OIC read characteristic. Server will read.*/
- bt_gatt_attribute_h
- write_char; /**<gatt_attribute handler for OIC write characteristic. server will write*/
- char *bdAddress; /**< BD address where OIC service is running. */
+ bt_gatt_attribute_h service_clone; /**< GATT attribute handler for the OIC service. */
+ bt_gatt_attribute_h read_char; /**< GATT attribute handler for OIC read characteristic.
+ Server will read.*/
+ bt_gatt_attribute_h write_char; /**< GATT attribute handler for OIC write characteristic.
+ server will write*/
+ char *bdAddress; /**< BD address where OIC service is running. */
} BLEServiceInfo;
/**
*/
typedef enum
{
- WRITE_CHAR, /**< write_char This will be used to get the unicast response */
- READ_CHAR, /**< read_char This will be used update value to OIC server */
- NOTIFY_CHAR /**< Reserved char for the time being. */
+ BLE_GATT_WRITE_CHAR = 0, /**< write_char This will be used to get the unicast response */
+ BLE_GATT_READ_CHAR, /**< read_char This will be used update value to OIC server */
+ BLE_GATT_NOTIFY_CHAR /**< Reserved char for the time being. */
} CHAR_TYPE;
/**
*/
typedef enum
{
- READ_CHAR_INDEX = 1, /**< read_char index */
- WRITE_CHAR_INDEX = 2, /**< write_char index */
- NOTIFY_CHAR_INDEX = 3 /**< Reserved char index for the time being. */
+ BLE_GATT_READ_CHAR_INDEX = 1, /**< read_char index */
+ BLE_GATT_WRITE_CHAR_INDEX = 2, /**< write_char index */
+ BLE_GATT_NOTIFY_CHAR_INDEX = 3 /**< Reserved char index for the time being. */
} CHAR_INDEX;
* @brief Used to append the characteristic info to the already created serviceInfo structure.
*
* @param characteristic [IN] Charecteristic attribute handler.
- * @param type [IN] Specifies whether its READ_CHAR or WRITE_CHAR
+ * @param type [IN] Specifies whether its BLE_GATT_READ_CHAR or BLE_GATT_WRITE_CHAR
* @param bleServiceInfo [IN] Pointer where serviceInfo structure needs to be appended with
* char info.
* @return #CA_STATUS_OK or Appropriate error code
* @retval #CA_STATUS_INVALID_PARAM Invalid input argumets
* @retval #CA_STATUS_FAILED Operation failed
*/
-CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList, BLEServiceInfo *bleServiceInfo);
+CAResult_t CAAddBLEServiceInfoToList(BLEServiceList **serviceList,
+ BLEServiceInfo *bleServiceInfo);
/**
* @brief Used to remove the ServiceInfo structure from the Service List.
*/
const char *CABTGetErrorMsg(bt_error_e err);
-#endif //#ifndef _BLE_UTIL_H_
\ No newline at end of file
+#endif //#ifndef _BLE_UTIL_H_
{
OIC_LOG_V(DEBUG, TAG, "CAInitialize");
- CAResult_t res = CAInitializeMessageHandler();
-
- return res;
+ return CAInitializeMessageHandler();;
}
void CATerminate()
CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri, connectivityType);
- *remoteEndpoint = remote;
-
if (remote == NULL)
+ {
+ OIC_LOG_V(DEBUG, TAG, "remote is NULL!");
return CA_STATUS_FAILED;
+ }
+
+ *remoteEndpoint = remote;
return CA_STATUS_OK;
}
}
-CAResult_t CASendRequest(const CARemoteEndpoint_t *object, CARequestInfo_t *requestInfo)
+CAResult_t CASendRequest(const CARemoteEndpoint_t *object,const CARequestInfo_t *requestInfo)
{
OIC_LOG_V(DEBUG, TAG, "CASendGetRequest");
return CADetachRequestToAllMessage(object, requestInfo);
}
-CAResult_t CASendNotification(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo)
+CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
+ const CAResponseInfo_t *responseInfo)
{
OIC_LOG_V(DEBUG, TAG, "CASendNotification");
}
-CAResult_t CASendResponse(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo)
+CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
+ const CAResponseInfo_t *responseInfo)
{
OIC_LOG_V(DEBUG, TAG, "CASendResponse");
}
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAToken_t token,
- CAHeaderOption_t *options, uint8_t numOptions)
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
+ const CAHeaderOption_t *options,const uint8_t numOptions)
{
OIC_LOG_V(DEBUG, TAG, "CAAdvertiseResource");
{
return CA_NOT_SUPPORTED;
}
- CAResult_t res;
+ CAResult_t res =CA_STATUS_OK;
if (interestedNetwork & CA_ETHERNET)
{
res = CAAddNetworkType(CA_ETHERNET);
- if (res != CA_STATUS_OK)
- {
- return res;
- }
+ OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_ETHERNET) function returns error : %d", res);
}
if (interestedNetwork & CA_WIFI)
{
res = CAAddNetworkType(CA_WIFI);
- if (res != CA_STATUS_OK)
- {
- return res;
- }
+ OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_WIFI) function returns error : %d", res);
}
if (interestedNetwork & CA_EDR)
{
res = CAAddNetworkType(CA_EDR);
- if (res != CA_STATUS_OK)
- {
- return res;
- }
+ OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_EDR) function returns error : %d", res);
}
if (interestedNetwork & CA_LE)
{
res = CAAddNetworkType(CA_LE);
- if (res != CA_STATUS_OK)
- {
- return res;
- }
+ OIC_LOG_V(DEBUG, TAG, "CAAddNetworkType(CA_LE) function returns error : %d", res);
}
- return CA_STATUS_OK;
+ return res;
}
CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork)
return CA_NOT_SUPPORTED;
}
- CAResult_t res;
-
+ CAResult_t res = CA_STATUS_OK;
if (nonInterestedNetwork & CA_ETHERNET)
{
res = CARemoveNetworkType(CA_ETHERNET);
- if (res != CA_STATUS_OK)
- {
- return res;
- }
+ OIC_LOG_V(DEBUG, TAG, "CARemoveNetworkType(CA_ETHERNET) function returns error : %d", res);
}
if (nonInterestedNetwork & CA_WIFI)
{
res = CARemoveNetworkType(CA_WIFI);
- if (res != CA_STATUS_OK)
- {
- return res;
- }
+ OIC_LOG_V(DEBUG, TAG, "CARemoveNetworkType(CA_WIFI) function returns error : %d", res);
}
if (nonInterestedNetwork & CA_EDR)
{
res = CARemoveNetworkType(CA_EDR);
- if (res != CA_STATUS_OK)
- {
- return res;
- }
+ OIC_LOG_V(DEBUG, TAG, "CARemoveNetworkType(CA_EDR) function returns error : %d", res);
}
if (nonInterestedNetwork & CA_LE)
{
res = CARemoveNetworkType(CA_LE);
- if (res != CA_STATUS_OK)
- {
- return res;
- }
+ OIC_LOG_V(DEBUG, TAG, "CARemoveNetworkType(CA_LE) function returns error : %d", res);
}
- return CA_STATUS_OK;
+ return res;
}
CAResult_t CAHandleRequestResponse()
return CA_STATUS_OK;
}
+
#define TAG "CM_ST"
-static void CAMessageHandler(CAToken_t token, CAResult_t res)
-{
- // TODO
- // it will notify the result for the each action.
-
-}
-
CAResult_t CAInitialize()
{
OIC_LOG(DEBUG, TAG, "IN");
- CASetMessageHandlerCallback(CAMessageHandler);
-
- CAResult_t res = CAInitializeMessageHandler();
-
- if (res != CA_STATUS_OK)
- {
- return res;
- }
- OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+ return CAInitializeMessageHandler();
}
void CATerminate()
CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri,connectivityType);
- *remoteEndpoint = remote;
-
if (remote == NULL)
+ {
+ OIC_LOG(ERROR, TAG, "remote endpoint is NULL");
return CA_STATUS_FAILED;
+ }
+
+ *remoteEndpoint = remote;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token)
{
OIC_LOG(DEBUG, TAG, "IN");
- CAResult_t res = CADetachMessageResourceUri(resourceUri, token, NULL, 0);
- OIC_LOG(DEBUG, TAG, "OUT");
- return res;
+
+ return CADetachMessageResourceUri(resourceUri, token, NULL, 0);
+
}
-CAResult_t CASendRequest(const CARemoteEndpoint_t *object, CARequestInfo_t *requestInfo)
+CAResult_t CASendRequest(const CARemoteEndpoint_t *object,const CARequestInfo_t *requestInfo)
{
return CADetachRequestMessage(object, requestInfo);
}
return CADetachRequestToAllMessage(object, requestInfo);
}
-CAResult_t CASendNotification(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo)
+CAResult_t CASendNotification(const CARemoteEndpoint_t *object,
+ const CAResponseInfo_t *responseInfo)
{
return CADetachResponseMessage(object, responseInfo);
}
-CAResult_t CASendResponse(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo)
+CAResult_t CASendResponse(const CARemoteEndpoint_t *object,
+ const CAResponseInfo_t *responseInfo)
{
return CADetachResponseMessage(object, responseInfo);
}
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAToken_t token,
- CAHeaderOption_t *options,
- uint8_t numOptions)
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri,const CAToken_t token,
+ const CAHeaderOption_t *options,
+ const uint8_t numOptions)
{
return CADetachMessageResourceUri(resourceUri, token, options, numOptions);
}
if (!(interestedNetwork & 0xf))
{
+ OIC_LOG(ERROR, TAG, "not supported");
return CA_NOT_SUPPORTED;
}
- CAResult_t res;
+ CAResult_t res = CA_STATUS_OK;
if (interestedNetwork & CA_ETHERNET)
{
res = CAAddNetworkType(CA_ETHERNET);
if (res != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
return res;
}
}
res = CAAddNetworkType(CA_WIFI);
if (res != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
return res;
}
}
res = CAAddNetworkType(CA_EDR);
if (res != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
return res;
}
}
res = CAAddNetworkType(CA_LE);
if (res != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, TAG, "Failed to Add n/w type");
return res;
}
}
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+ return res;
}
CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork)
if (!(nonInterestedNetwork & 0xf))
{
+ OIC_LOG(ERROR, TAG, "not supported");
return CA_NOT_SUPPORTED;
}
- CAResult_t res;
+ CAResult_t res = CA_STATUS_OK;
if (nonInterestedNetwork & CA_ETHERNET)
{
res = CARemoveNetworkType(CA_ETHERNET);
if (res != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
return res;
}
}
res = CARemoveNetworkType(CA_WIFI);
if (res != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
return res;
}
}
res = CARemoveNetworkType(CA_EDR);
if (res != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
return res;
}
}
res = CARemoveNetworkType(CA_LE);
if (res != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, TAG, "Failed to remove n/w type");
return res;
}
}
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+ return res;
}
CAResult_t CAHandleRequestResponse()
return CA_STATUS_OK;
}
+
#define TAG PCF("CA")
#define CA_MEMORY_ALLOC_CHECK(arg) {if (arg == NULL) \
- {OIC_LOG_V(DEBUG, TAG, "memory error");goto memory_error_exit;} }
+ {OIC_LOG_V(ERROR, TAG, "memory error");goto memory_error_exit;} }
#define CA_CONNECTIVITY_TYPE_NUM 4
-static CAConnectivityHandler_t gAdapterHandler[CA_CONNECTIVITY_TYPE_NUM];
+static CAConnectivityHandler_t g_adapterHandler[CA_CONNECTIVITY_TYPE_NUM];
-static CANetworkPacketReceivedCallback gNetworkPacketReceivedCallback = NULL;
+static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
-static CANetworkChangeCallback gNetworkChangeCallback = NULL;
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
-static int8_t CAGetAdapterIndex(CAConnectivityType_t cType)
+static int CAGetAdapterIndex(CAConnectivityType_t cType)
{
switch (cType)
{
case CA_LE:
return 3;
}
+
+ OIC_LOG(DEBUG, TAG, "CA_CONNECTIVITY_TYPE_NUM is not 4");
+
return -1;
}
static void CARegisterCallback(CAConnectivityHandler_t handler, CAConnectivityType_t cType)
{
OIC_LOG(DEBUG, TAG, "CARegisterCallback - Entry");
- int8_t index = -1;
- index = CAGetAdapterIndex(cType);
+ if(handler.startAdapter == NULL ||
+ handler.startListenServer == NULL ||
+ handler.startDiscoveryServer == NULL ||
+ handler.sendData == NULL ||
+ handler.sendDataToAll == NULL ||
+ handler.GetnetInfo == NULL ||
+ handler.readData == NULL ||
+ handler.stopAdapter == NULL ||
+ handler.terminate == NULL)
+ {
+ OIC_LOG(DEBUG, TAG, "connectivity handler is not enough to be used!");
+ return;
+ }
+
+ int index = CAGetAdapterIndex(cType);
if (index == -1)
{
return;
}
- memcpy(&gAdapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
+ memcpy(&g_adapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", cType);
}
OIC_LOG(DEBUG, TAG, "receivedPacketCallback in interface controller");
// Call the callback.
- if (gNetworkPacketReceivedCallback != NULL)
+ if (g_networkPacketReceivedCallback != NULL)
{
- gNetworkPacketReceivedCallback(endpoint, data, dataLen);
+ g_networkPacketReceivedCallback(endpoint, data, dataLen);
+ }
+ else
+ {
+ OICFree(endpoint);
+ endpoint = NULL;
+ OICFree(data);
+ data = NULL;
+
+ OIC_LOG(DEBUG, TAG, "network packet received callback is NULL!");
}
}
OIC_LOG(DEBUG, TAG, "Network Changed callback");
// Call the callback.
- if (gNetworkChangeCallback != NULL)
+ if (g_networkChangeCallback != NULL)
{
- gNetworkChangeCallback(info, status);
+ g_networkChangeCallback(info, status);
}
}
{
OIC_LOG(DEBUG, TAG, "initialize adapters..");
- memset(gAdapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM);
+ memset(g_adapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM);
// Initialize adapters and register callback.
#ifdef ETHERNET_ADAPTER
{
OIC_LOG(DEBUG, TAG, "Set packet received callback");
- gNetworkPacketReceivedCallback = callback;
+ g_networkPacketReceivedCallback = callback;
}
void CASetNetworkChangeCallback(CANetworkChangeCallback callback)
{
OIC_LOG(DEBUG, TAG, "Set network change callback");
- gNetworkChangeCallback = callback;
+ g_networkChangeCallback = callback;
}
-void CAStartAdapter(CAConnectivityType_t cType)
+CAResult_t CAStartAdapter(CAConnectivityType_t cType)
{
OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", cType);
- int8_t index = -1;
-
- index = CAGetAdapterIndex(cType);
+ int index = CAGetAdapterIndex(cType);
if (index == -1)
{
OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
- return;
+ return CA_STATUS_FAILED;
}
- if (gAdapterHandler[index].startAdapter != NULL)
+ if (g_adapterHandler[index].startAdapter != NULL)
{
- gAdapterHandler[index].startAdapter();
+ g_adapterHandler[index].startAdapter();
}
+
+ return CA_STATUS_OK;
}
void CAStopAdapter(CAConnectivityType_t cType)
{
OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CAConnectivityType[%d]", cType);
- int8_t index = -1;
-
- index = CAGetAdapterIndex(cType);
+ int index = CAGetAdapterIndex(cType);
if (index == -1)
{
return;
}
- if (gAdapterHandler[index].stopAdapter != NULL)
+ if (g_adapterHandler[index].stopAdapter != NULL)
{
- gAdapterHandler[index].stopAdapter();
+ g_adapterHandler[index].stopAdapter();
}
}
CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size)
{
CAResult_t res = CA_STATUS_FAILED;
- int8_t index = 0;
- int8_t i = 0;
-
- CALocalConnectivity_t *resInfo = NULL;
- uint32_t resSize = 0;
CALocalConnectivity_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM];
uint32_t tempSize[CA_CONNECTIVITY_TYPE_NUM];
memset(tempSize, 0, sizeof(uint32_t) * CA_CONNECTIVITY_TYPE_NUM);
// #1. get information each adapter
+ uint8_t index = 0;
for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
{
- if (gAdapterHandler[index].GetnetInfo != NULL)
+ if (g_adapterHandler[index].GetnetInfo != NULL)
{
- res = gAdapterHandler[index].GetnetInfo(&tempInfo[index], &tempSize[index]);
+ res = g_adapterHandler[index].GetnetInfo(&tempInfo[index], &tempSize[index]);
OIC_LOG_V(DEBUG, TAG, "%d adapter network info size is %d res:%d", index,
tempSize[index], res);
}
}
- resSize = 0;
+ uint32_t resSize = 0;
for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
{
// check information
// #3. add data into result
// memory allocation
- resInfo = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t) * resSize);
+
+ CALocalConnectivity_t *resInfo = (CALocalConnectivity_t *) OICCalloc(resSize, sizeof(CALocalConnectivity_t));
CA_MEMORY_ALLOC_CHECK(resInfo);
- memset(resInfo, 0, sizeof(CALocalConnectivity_t) * resSize);
- i = 0;
+ uint8_t pos = 0;
for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
{
// check information
continue;
}
- memcpy(resInfo + i, tempInfo[index], sizeof(CALocalConnectivity_t) * tempSize[index]);
+ memcpy(resInfo + pos, tempInfo[index], sizeof(CALocalConnectivity_t) * tempSize[index]);
- i += tempSize[index];
+ pos += tempSize[index];
// free adapter data
OICFree(tempInfo[index]);
+ tempInfo[index] = NULL;
}
// #5. save data
- *info = resInfo;
- *size = resSize;
+ if ( info != NULL )
+ {
+ *info = resInfo;
+ }
+
+ if (size)
+ {
+ *size = resSize;
+ }
+
res = CA_STATUS_OK;
OIC_LOG_V(DEBUG, TAG, "each network info save success!");
// memory error label.
memory_error_exit:
+ for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+ {
+
+ OICFree(tempInfo[index]);
+ tempInfo[index] = NULL;
+ }
+
return CA_MEMORY_ALLOC_FAILED;
}
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t length)
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length)
{
OIC_LOG(DEBUG, TAG, "Send unicast data to enabled interface..");
- int8_t index = -1;
CAResult_t res = CA_STATUS_FAILED;
- uint32_t sentDataLen = 0;
if (endpoint == NULL)
{
CAConnectivityType_t type = endpoint->connectivityType;
- index = CAGetAdapterIndex(type);
+ int index = CAGetAdapterIndex(type);
if (index == -1)
{
return CA_STATUS_INVALID_PARAM;
}
- if (gAdapterHandler[index].sendData != NULL)
+ uint32_t sentDataLen = 0;
+
+ if (g_adapterHandler[index].sendData != NULL)
{
- sentDataLen = gAdapterHandler[index].sendData(endpoint, data, length);
+ sentDataLen = g_adapterHandler[index].sendData(endpoint, data, length);
}
- if (sentDataLen == length)
+ if (sentDataLen != -1)
{
res = CA_STATUS_OK;
}
return res;
}
-CAResult_t CASendMulticastData(void *data, uint32_t length)
+CAResult_t CASendMulticastData(const void *data, uint32_t length)
{
OIC_LOG(DEBUG, TAG, "Send multicast data to enabled interface..");
- uint8_t i = 0;
- CAConnectivityType_t connType;
- int8_t index = -1;
- uint32_t sentDataLen = 0;
CAResult_t res = CA_STATUS_FAILED;
u_arraylist_t *list = CAGetSelectedNetworkList();
return CA_STATUS_FAILED;
}
+ int i = 0;
for (i = 0; i < u_arraylist_length(list); i++)
{
void* ptrType = u_arraylist_get(list, i);
continue;
}
- connType = *(CAConnectivityType_t *) ptrType;
+ CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType;
- index = CAGetAdapterIndex(connType);
+ int index = CAGetAdapterIndex(connType);
if (index == -1)
{
continue;
}
- if (gAdapterHandler[index].sendDataToAll != NULL)
+ uint32_t sentDataLen = 0;
+
+ if (g_adapterHandler[index].sendDataToAll != NULL)
{
void *payload = (void *) OICMalloc(length);
if (!payload)
return CA_MEMORY_ALLOC_FAILED;
}
memcpy(payload, data, length);
- sentDataLen = gAdapterHandler[index].sendDataToAll(payload, length);
+ sentDataLen = g_adapterHandler[index].sendDataToAll(payload, length);
OICFree(payload);
}
+
if (sentDataLen == length)
{
res = CA_STATUS_OK;
}
+ else
+ {
+ OIC_LOG_V(ERROR, TAG, "sendDataToAll failed!");
+ }
}
+
return res;
}
{
OIC_LOG(DEBUG, TAG, "Start listening server from adapters..");
- uint8_t i = 0;
- CAConnectivityType_t connType;
- int8_t index = -1;
u_arraylist_t *list = CAGetSelectedNetworkList();
-
if (!list)
{
OIC_LOG(DEBUG, TAG, "No selected network");
return CA_STATUS_FAILED;
}
+ int i = 0;
for (i = 0; i < u_arraylist_length(list); i++)
{
void* ptrType = u_arraylist_get(list, i);
continue;
}
- connType = *(CAConnectivityType_t *) ptrType;
+ CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType;
- index = CAGetAdapterIndex(connType);
+ int index = CAGetAdapterIndex(connType);
if (index == -1)
{
OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
continue;
}
- if (gAdapterHandler[index].startListenServer != NULL)
+ if (g_adapterHandler[index].startListenServer != NULL)
{
- gAdapterHandler[index].startListenServer();
+ g_adapterHandler[index].startListenServer();
}
}
{
OIC_LOG(DEBUG, TAG, "Start discovery server from adapters..");
- uint8_t i = 0;
- CAConnectivityType_t connType;
- int8_t index = -1;
u_arraylist_t *list = CAGetSelectedNetworkList();
if (!list)
return CA_STATUS_FAILED;
}
+ int i = 0;
for (i = 0; i < u_arraylist_length(list); i++)
{
void* ptrType = u_arraylist_get(list, i);
continue;
}
- connType = *(CAConnectivityType_t *) ptrType;
+ CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType;
- index = CAGetAdapterIndex(connType);
+ int index = CAGetAdapterIndex(connType);
if (index == -1)
{
continue;
}
- if (gAdapterHandler[index].startDiscoverServer != NULL)
+ if (g_adapterHandler[index].startDiscoveryServer != NULL)
{
- gAdapterHandler[index].startDiscoverServer();
+ g_adapterHandler[index].startDiscoveryServer();
}
}
{
OIC_LOG(DEBUG, TAG, "terminate all adapters..");
- uint8_t index;
-
+ int index;
for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
{
- if (gAdapterHandler[index].stopAdapter != NULL)
+ if (g_adapterHandler[index].stopAdapter != NULL)
{
- gAdapterHandler[index].stopAdapter();
+ g_adapterHandler[index].stopAdapter();
}
- if (gAdapterHandler[index].terminate != NULL)
+ if (g_adapterHandler[index].terminate != NULL)
{
- gAdapterHandler[index].terminate();
+ g_adapterHandler[index].terminate();
}
}
}
+
#define TAG "CAIFCNT_ST"
-#define MEMORY_ALLOC_CHECK(arg) { if (arg == NULL) {OIC_LOG(DEBUG, TAG, "Out of memory");\
+#define CA_MEMORY_ALLOC_CHECK(arg) { if (arg == NULL) {OIC_LOG(ERROR, TAG, "Out of memory");\
goto memory_error_exit;} }
#define CA_CONNECTIVITY_TYPE_NUM 4
-static CAConnectivityHandler_t gAdapterHandler[CA_CONNECTIVITY_TYPE_NUM];
+static CAConnectivityHandler_t g_adapterHandler[CA_CONNECTIVITY_TYPE_NUM];
-static CANetworkPacketReceivedCallback gNetworkPacketReceivedCallback = NULL;
+static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
-static CANetworkChangeCallback gNetworkChangeCallback = NULL;
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
-static int8_t CAGetAdapterIndex(CAConnectivityType_t cType)
+static int CAGetAdapterIndex(CAConnectivityType_t cType)
{
switch (cType)
{
case CA_LE:
return 3;
}
+
+ OIC_LOG(DEBUG, TAG, "CA_CONNECTIVITY_TYPE_NUM is not 4");
+
return -1;
}
static void CARegisterCallback(CAConnectivityHandler_t handler, CAConnectivityType_t cType)
{
OIC_LOG(DEBUG, TAG, "IN");
- int8_t index = -1;
- index = CAGetAdapterIndex(cType);
+ if(handler.startAdapter == NULL ||
+ handler.startListenServer == NULL ||
+ handler.startDiscoveryServer == NULL ||
+ handler.sendData == NULL ||
+ handler.sendDataToAll == NULL ||
+ handler.GetnetInfo == NULL ||
+ handler.readData == NULL ||
+ handler.stopAdapter == NULL ||
+ handler.terminate == NULL)
+ {
+ OIC_LOG(ERROR, TAG, "connectivity handler is not enough to be used!");
+ return;
+ }
+
+ int index = CAGetAdapterIndex(cType);
if (index == -1)
{
return;
}
- memcpy(&gAdapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
+ memcpy(&g_adapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
OIC_LOG_V(DEBUG, TAG, "%d type adapter", cType);
OIC_LOG(DEBUG, TAG, "OUT");
OIC_LOG(DEBUG, TAG, "IN");
// Call the callback.
- if (gNetworkPacketReceivedCallback != NULL)
+ if (g_networkPacketReceivedCallback != NULL)
{
- gNetworkPacketReceivedCallback(endpoint, data, dataLen);
+ g_networkPacketReceivedCallback(endpoint, data, dataLen);
}
OIC_LOG(DEBUG, TAG, "OUT");
}
OIC_LOG(DEBUG, TAG, "IN");
// Call the callback.
- if (gNetworkChangeCallback != NULL)
+ if (g_networkChangeCallback != NULL)
{
- gNetworkChangeCallback(info, status);
+ g_networkChangeCallback(info, status);
}
OIC_LOG(DEBUG, TAG, "OUT");
}
{
OIC_LOG(DEBUG, TAG, "IN");
- memset(gAdapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM);
-
+ memset(g_adapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM);
// Initialize adapters and register callback.
#ifdef ETHERNET_ADAPTER
{
OIC_LOG(DEBUG, TAG, "IN");
- gNetworkPacketReceivedCallback = callback;
+ g_networkPacketReceivedCallback = callback;
OIC_LOG(DEBUG, TAG, "OUT");
}
{
OIC_LOG(DEBUG, TAG, "IN");
- gNetworkChangeCallback = callback;
+ g_networkChangeCallback = callback;
OIC_LOG(DEBUG, TAG, "OUT");
}
-void CAStartAdapter(CAConnectivityType_t cType)
+CAResult_t CAStartAdapter(CAConnectivityType_t cType)
{
OIC_LOG_V(DEBUG, TAG, "cType[%d]", cType);
- int8_t index = -1;
-
- index = CAGetAdapterIndex(cType);
+ int index = CAGetAdapterIndex(cType);
if (index == -1)
{
OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
- return;
+ return CA_STATUS_FAILED;
}
- if (gAdapterHandler[index].startAdapter != NULL)
+ if (g_adapterHandler[index].startAdapter != NULL)
{
- gAdapterHandler[index].startAdapter();
+ g_adapterHandler[index].startAdapter();
}
OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
}
void CAStopAdapter(CAConnectivityType_t cType)
{
OIC_LOG_V(DEBUG, TAG, "cType[%d]", cType);
- int8_t index = -1;
-
- index = CAGetAdapterIndex(cType);
+ int index = CAGetAdapterIndex(cType);
if (index == -1)
{
return;
}
- if (gAdapterHandler[index].stopAdapter != NULL)
+ if (g_adapterHandler[index].stopAdapter != NULL)
{
- gAdapterHandler[index].stopAdapter();
+ g_adapterHandler[index].stopAdapter();
}
OIC_LOG(DEBUG, TAG, "OUT");
}
CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, TAG, "IN");
- CAResult_t res = CA_STATUS_FAILED;
- int8_t index = 0;
- int8_t i = 0;
+ VERIFY_NON_NULL(info, TAG, "info");
+ VERIFY_NON_NULL(size, TAG, "size");
- CALocalConnectivity_t *resInfo = NULL;
- uint32_t resSize = 0;
-
- CALocalConnectivity_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM];
- uint32_t tempSize[CA_CONNECTIVITY_TYPE_NUM];
+ CAResult_t res = CA_STATUS_FAILED;
- memset(tempInfo, 0, sizeof(CALocalConnectivity_t *) * CA_CONNECTIVITY_TYPE_NUM);
- memset(tempSize, 0, sizeof(int8_t) * CA_CONNECTIVITY_TYPE_NUM);
+ CALocalConnectivity_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM] = { 0 };
+ uint32_t tempSize[CA_CONNECTIVITY_TYPE_NUM] = { 0 };
+ uint8_t index = 0;
// #1. get information each adapter
for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
{
- if (gAdapterHandler[index].GetnetInfo != NULL)
+ if (g_adapterHandler[index].GetnetInfo != NULL)
{
- res = gAdapterHandler[index].GetnetInfo(&tempInfo[index], &tempSize[index]);
+ res = g_adapterHandler[index].GetnetInfo(&tempInfo[index], &tempSize[index]);
OIC_LOG_V (DEBUG, TAG, "%d adapter network info size is %d", index, tempSize[index]);
}
}
- resSize = 0;
+ uint32_t resSize = 0;
for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
{
// check information
// #3. add data into result
// memory allocation
- resInfo = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t) * resSize);
- MEMORY_ALLOC_CHECK(resInfo);
- memset(resInfo, 0, sizeof(CALocalConnectivity_t) * resSize);
+ CALocalConnectivity_t *resInfo =
+ (CALocalConnectivity_t *) OICCalloc(resSize, sizeof(CALocalConnectivity_t));
+ CA_MEMORY_ALLOC_CHECK(resInfo);
- i = 0;
+ uint8_t i = 0;
for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
{
// check information
// memory error label.
memory_error_exit:
+ for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+ {
+
+ OICFree(tempInfo[index]);
+ }
+
return CA_MEMORY_ALLOC_FAILED;
}
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t length)
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t length)
{
OIC_LOG(DEBUG, TAG, "IN");
- int8_t index = -1;
- uint32_t sentDataLen = 0;
CAResult_t res = CA_STATUS_FAILED;
if (endpoint == NULL)
CAConnectivityType_t type = endpoint->connectivityType;
- index = CAGetAdapterIndex(type);
+ int index = CAGetAdapterIndex(type);
if (index == -1)
{
return CA_STATUS_INVALID_PARAM;
}
- if (gAdapterHandler[index].sendData != NULL)
+ uint32_t sentDataLen = 0;
+ if (g_adapterHandler[index].sendData != NULL)
{
- sentDataLen = gAdapterHandler[index].sendData(endpoint, data, length);
+ sentDataLen = g_adapterHandler[index].sendData(endpoint, data, length);
}
if (sentDataLen == length)
return res;
}
-CAResult_t CASendMulticastData(void *data, uint32_t length)
+CAResult_t CASendMulticastData(const void *data, uint32_t length)
{
OIC_LOG(DEBUG, TAG, "IN");
- uint8_t i = 0;
- CAConnectivityType_t connType;
- int8_t index = -1;
- uint32_t sentDataLen = 0;
CAResult_t res = CA_STATUS_FAILED;
u_arraylist_t *list = CAGetSelectedNetworkList();
if (!list)
{
OIC_LOG(DEBUG, TAG, "No selected network");
- return CA_STATUS_FAILED;
+ return res;
}
- void *ptrType = NULL;
+ uint8_t i = 0;
for (i = 0; i < u_arraylist_length(list); i++)
{
- ptrType = u_arraylist_get(list, i);
+ void* ptrType = u_arraylist_get(list, i);
if (NULL == ptrType)
{
- OIC_LOG(ERROR, TAG, "error");
- return CA_STATUS_FAILED;
+ continue;
}
- connType = *(CAConnectivityType_t *) ptrType;
+ CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType;
- index = CAGetAdapterIndex(connType);
+ int index = CAGetAdapterIndex(connType);
if (index == -1)
{
continue;
}
- if (gAdapterHandler[index].sendDataToAll != NULL)
+ uint32_t sentDataLen = 0;
+ if (g_adapterHandler[index].sendDataToAll != NULL)
{
- sentDataLen = gAdapterHandler[index].sendDataToAll(data, length);
+ sentDataLen = g_adapterHandler[index].sendDataToAll(data, length);
}
if (sentDataLen == length)
{
OIC_LOG(DEBUG, TAG, "IN");
- uint8_t i = 0;
- CAConnectivityType_t connType;
- int8_t index = -1;
u_arraylist_t *list = CAGetSelectedNetworkList();
if (!list)
return CA_STATUS_FAILED;
}
- void *ptrType = NULL;
+ uint8_t i = 0;
for (i = 0; i < u_arraylist_length(list); i++)
{
- ptrType = u_arraylist_get(list, i);
+ void* ptrType = u_arraylist_get(list, i);
if (NULL == ptrType)
{
- OIC_LOG(ERROR, TAG, "error");
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, TAG, "Invalid conn type");
+ continue;
}
- connType = *(CAConnectivityType_t *) ptrType;
+ CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType;
- index = CAGetAdapterIndex(connType);
+ int index = CAGetAdapterIndex(connType);
if (index == -1)
{
continue;
}
- if (gAdapterHandler[index].startListenServer != NULL)
+ if (g_adapterHandler[index].startListenServer != NULL)
{
- gAdapterHandler[index].startListenServer();
+ g_adapterHandler[index].startListenServer();
}
}
OIC_LOG(DEBUG, TAG, "OUT");
{
OIC_LOG(DEBUG, TAG, "IN");
- uint8_t i = 0;
- CAConnectivityType_t connType;
- int8_t index = -1;
u_arraylist_t *list = CAGetSelectedNetworkList();
if (!list)
return CA_STATUS_FAILED;
}
- void *ptrType = NULL;
+ uint8_t i = 0;
for (i = 0; i < u_arraylist_length(list); i++)
{
- ptrType = u_arraylist_get(list, i);
+ void* ptrType = u_arraylist_get(list, i);
if (NULL == ptrType)
{
- OIC_LOG(ERROR, TAG, "error");
- return CA_STATUS_FAILED;
+ continue;
}
- connType = *(CAConnectivityType_t *) ptrType;
+ CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType;
- index = CAGetAdapterIndex(connType);
+ int index = CAGetAdapterIndex(connType);
if (index == -1)
{
continue;
}
- if (gAdapterHandler[index].startDiscoverServer != NULL)
+ if (g_adapterHandler[index].startDiscoveryServer != NULL)
{
- gAdapterHandler[index].startDiscoverServer();
+ g_adapterHandler[index].startDiscoveryServer();
}
}
OIC_LOG(DEBUG, TAG, "OUT");
for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
{
- if (gAdapterHandler[index].terminate != NULL)
+ if (g_adapterHandler[index].stopAdapter != NULL)
+ {
+ g_adapterHandler[index].stopAdapter();
+ }
+ if (g_adapterHandler[index].terminate != NULL)
{
- gAdapterHandler[index].terminate();
+ g_adapterHandler[index].terminate();
}
}
+
OIC_LOG(DEBUG, TAG, "OUT");
}
CAResult_t CAReadData()
{
-
- uint8_t i = 0;
- CAConnectivityType_t connType;
- int8_t index = -1;
-
+ OIC_LOG(DEBUG, TAG, "IN");
u_arraylist_t *list = CAGetSelectedNetworkList();
if (!list)
{
return CA_STATUS_FAILED;
}
- void *ptrType = NULL;
+
+ uint8_t i = 0;
for (i = 0; i < u_arraylist_length(list); i++)
{
- ptrType = u_arraylist_get(list, i);
+ void *ptrType = u_arraylist_get(list, i);
if (NULL == ptrType)
{
- OIC_LOG(ERROR, TAG, "error");
+ OIC_LOG(ERROR, TAG, "get list fail");
return CA_STATUS_FAILED;
}
- connType = *(CAConnectivityType_t *) ptrType;
- index = CAGetAdapterIndex(connType);
+ CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType;
+
+ int index = CAGetAdapterIndex(connType);
if (-1 == index)
{
continue;
}
- if (gAdapterHandler[index].readData != NULL)
+ if (g_adapterHandler[index].readData != NULL)
{
- gAdapterHandler[index].readData();
+ g_adapterHandler[index].readData();
}
}
+ OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
+
#include "caretransmission.h"
#include "umutex.h"
#include "oic_malloc.h"
+#include "caadapterutils.h"
+#include "canetworkconfigurator.h"
#define TAG PCF("CA")
#define SINGLE_HANDLE
-#define MEMORY_ALLOC_CHECK(arg) { if (arg == NULL) {OIC_LOG_V(DEBUG, TAG, "memory error"); \
+#define CA_MEMORY_ALLOC_CHECK(arg) { if (arg == NULL) {OIC_LOG_V(ERROR, TAG, "Out of memory"); \
goto memory_error_exit;} }
#define MAX_THREAD_POOL_SIZE 20
} CAData_t;
// thread pool handle
-static u_thread_pool_t gThreadPoolHandle = NULL;
+static u_thread_pool_t g_threadPoolHandle = NULL;
// message handler main thread
-static CAQueueingThread_t gSendThread;
-static CAQueueingThread_t gReceiveThread;
+static CAQueueingThread_t g_sendThread;
+static CAQueueingThread_t g_receiveThread;
-static CARetransmission_t gRetransmissionContext;
+static CARetransmission_t g_retransmissionContext;
// handler field
-static CARequestCallback gRequestHandler = NULL;
-static CAResponseCallback gResponseHandler = NULL;
+static CARequestCallback g_requestHandler = NULL;
+static CAResponseCallback g_responseHandler = NULL;
-static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, void *pdu, uint32_t size)
+static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
{
CARemoteEndpoint_t* ep = CACloneRemoteEndpoint(endpoint);
if (ep == NULL)
return;
}
- CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICMalloc(sizeof(CAResponseInfo_t));
+ CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
if (resInfo == NULL)
{
CADestroyRemoteEndpointInternal(ep);
return;
}
- memset(resInfo, 0, sizeof(CAResponseInfo_t));
CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
resInfo->info.type = type;
resInfo->info.messageId = messageId;
- CAData_t *cadata = (CAData_t *) OICMalloc(sizeof(CAData_t));
+ CAData_t *cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
if (cadata == NULL)
{
OIC_LOG(DEBUG, TAG, "memory allocation failed !");
OICFree(resInfo);
return;
}
- memset(cadata, 0, sizeof(CAData_t));
cadata->type = SEND_TYPE_UNICAST;
cadata->remoteEndpoint = ep;
cadata->requestInfo = NULL;
cadata->responseInfo = resInfo;
- CAQueueingThreadAddData(&gReceiveThread, cadata, sizeof(CAData_t));
+ CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
}
static void CADataDestroyer(void *data, uint32_t size)
{
- OIC_LOG(DEBUG, TAG, "CADataDestroyer is ran!");
CAData_t *cadata = (CAData_t *) data;
if (cadata == NULL)
static void CAReceiveThreadProcess(void *threadData)
{
// Currently not supported
- // This will be enabled when RI supports multi threading
+ // This will be enabled when RI supports multi threading
#ifndef SINGLE_HANDLE
CAData_t *data = (CAData_t *) threadData;
if (data->requestInfo != NULL)
{
- if (gRequestHandler)
+ if (g_requestHandler)
{
- gRequestHandler(rep, data->requestInfo);
+ g_requestHandler(rep, data->requestInfo);
}
}
if (data->responseInfo != NULL)
{
- if (gResponseHandler)
+ if (g_responseHandler)
{
- gResponseHandler(rep, data->responseInfo);
+ g_responseHandler(rep, data->responseInfo);
}
}
#endif
if (data == NULL)
{
- OIC_LOG(DEBUG, TAG, "thread data error!!");
+ OIC_LOG(ERROR, TAG, "thread data error!!");
return;
}
OIC_LOG_V(DEBUG, TAG, "PDU Maker - token : %s", pdu->hdr->token);
- OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %s", pdu->hdr);
-
res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
// for retransmission
- CARetransmissionSentData(&gRetransmissionContext, data->remoteEndpoint, pdu->hdr,
+ CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
pdu->length);
coap_delete_pdu(pdu);
}
else if (type == SEND_TYPE_MULTICAST)
{
- OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
-
coap_pdu_t *pdu = NULL;
- CAInfo_t info;
- memset(&info, 0, sizeof(CAInfo_t));
+ CAInfo_t info = {};
info.options = data->options;
info.numOptions = data->numOptions;
OIC_LOG_V(DEBUG, TAG, "PDU Maker - token : %s", pdu->hdr->token);
- OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %s", pdu->hdr);
-
res = CASendMulticastData(pdu->hdr, pdu->length);
coap_delete_pdu(pdu);
}
return;
}
- char uri[CA_MAX_URI_LENGTH] =
- { 0, };
+ char uri[CA_MAX_URI_LENGTH] = { 0, };
+ uint32_t bufLen = CA_MAX_URI_LENGTH;
if (code == CA_GET || code == CA_POST || code == CA_PUT || code == CA_DELETE)
{
CARequestInfo_t *ReqInfo;
- ReqInfo = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
+ ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
if (ReqInfo == NULL)
{
OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
coap_delete_pdu(pdu);
+ CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- memset(ReqInfo, 0, sizeof(CARequestInfo_t));
- CAGetRequestInfoFromPdu(pdu, ReqInfo, uri);
+ CAGetRequestInfoFromPdu(pdu, ReqInfo, uri, bufLen);
if (NULL != ReqInfo->info.options)
{
OIC_LOG_V(DEBUG, TAG, "Request- payload: %s", ReqInfo->info.payload);
}
OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
- OIC_LOG_V(DEBUG, TAG, "Request- token : %s", ReqInfo->info.token);
- OIC_LOG_V(DEBUG, TAG, "Request- msgID: %d", ReqInfo->info.messageId);
+ if (NULL != ReqInfo->info.token)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Request- token : %s", ReqInfo->info.token);
+ }
if (NULL != endpoint)
{
- endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
+ endpoint->resourceUri = (char *) OICCalloc(bufLen + 1, sizeof(char));
if (endpoint->resourceUri == NULL)
{
OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
OICFree(ReqInfo);
coap_delete_pdu(pdu);
+ CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- memset(endpoint->resourceUri, 0, strlen(uri) + 1);
- memcpy(endpoint->resourceUri, uri, strlen(uri));
- OIC_LOG_V(DEBUG, TAG, "resource URI : %s", endpoint->resourceUri);
+ memcpy(endpoint->resourceUri, uri, bufLen);
+ OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
}
// store the data at queue.
CAData_t *cadata = NULL;
- cadata = (CAData_t *) OICMalloc(sizeof(CAData_t));
+ cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
if (cadata == NULL)
{
OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
OICFree(endpoint->resourceUri);
OICFree(ReqInfo);
coap_delete_pdu(pdu);
+ CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- memset(cadata, 0, sizeof(CAData_t));
cadata->type = SEND_TYPE_UNICAST;
cadata->remoteEndpoint = endpoint;
cadata->requestInfo = ReqInfo;
cadata->responseInfo = NULL;
- CAQueueingThreadAddData(&gReceiveThread, cadata, sizeof(CAData_t));
+ CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
}
else
{
CAResponseInfo_t *ResInfo;
- ResInfo = (CAResponseInfo_t *) OICMalloc(sizeof(CAResponseInfo_t));
+ ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
if (ResInfo == NULL)
{
OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
coap_delete_pdu(pdu);
+ CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- memset(ResInfo, 0, sizeof(CAResponseInfo_t));
- CAGetResponseInfoFromPdu(pdu, ResInfo, uri);
+ CAGetResponseInfoFromPdu(pdu, ResInfo, uri, bufLen);
if (NULL != ResInfo->info.options)
{
OIC_LOG_V(DEBUG, TAG, "Response- list: %s", ResInfo->info.options[i].optionData);
}
+ if (NULL != ResInfo->info.payload)
+ {
+ OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
+ }
+ OIC_LOG_V(DEBUG, TAG, "Response- code: %d", ResInfo->result);
}
- if (NULL != ResInfo->info.payload)
- {
- OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
- }
-
- OIC_LOG_V(DEBUG, TAG, "Response- response code: %d", ResInfo->result);
- OIC_LOG_V(DEBUG, TAG, "Response- token : %s", ResInfo->info.token);
- OIC_LOG_V(DEBUG, TAG, "Response- msgID: %d", ResInfo->info.messageId);
-
if (NULL != endpoint)
{
- endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
+ endpoint->resourceUri = (char *) OICCalloc(bufLen + 1, sizeof(char));
if (endpoint->resourceUri == NULL)
{
OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
OICFree(ResInfo);
coap_delete_pdu(pdu);
+ CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- memset(endpoint->resourceUri, 0, strlen(uri) + 1);
- memcpy(endpoint->resourceUri, uri, strlen(uri));
- OIC_LOG_V(DEBUG, TAG, "resource URI : %s", endpoint->resourceUri);
+ memcpy(endpoint->resourceUri, uri, bufLen);
+ OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
}
// store the data at queue.
CAData_t *cadata = NULL;
- cadata = (CAData_t *) OICMalloc(sizeof(CAData_t));
+ cadata = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
if (cadata == NULL)
{
OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
OICFree(endpoint->resourceUri);
OICFree(ResInfo);
coap_delete_pdu(pdu);
+ CAAdapterFreeRemoteEndpoint(endpoint);
return;
}
- memset(cadata, 0, sizeof(CAData_t));
cadata->type = SEND_TYPE_UNICAST;
cadata->remoteEndpoint = endpoint;
cadata->requestInfo = NULL;
-
- // for retransmission
- void *retransmissionPdu = NULL;
- CARetransmissionReceivedData(&gRetransmissionContext, endpoint, pdu->hdr, pdu->length, &retransmissionPdu);
-
- // get token from saved data in retransmission list
- if(retransmissionPdu && CA_EMPTY == code)
- {
- CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu, &(ResInfo->info));
- OICFree(retransmissionPdu);
- }
cadata->responseInfo = ResInfo;
- CAQueueingThreadAddData(&gReceiveThread, cadata, sizeof(CAData_t));
+ CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
+
+ // for retransmission
+ CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr, pdu->length);
}
if(pdu)
{
OIC_LOG_V(DEBUG, TAG, "CAHandleRequestResponseCallbacks IN");
-#ifdef SINGLE_HANDLE
// parse the data and call the callbacks.
// #1 parse the data
// #2 get endpoint
- u_mutex_lock(gReceiveThread.threadMutex);
+ u_mutex_lock(g_receiveThread.threadMutex);
- u_queue_message_t *item = u_queue_get_element(gReceiveThread.dataQueue);
+ u_queue_message_t *item = u_queue_get_element(g_receiveThread.dataQueue);
- u_mutex_unlock(gReceiveThread.threadMutex);
+ u_mutex_unlock(g_receiveThread.threadMutex);
if (item == NULL)
return;
if (td->requestInfo != NULL)
{
- if (gRequestHandler)
- {
- OIC_LOG_V(DEBUG, TAG, "callback will be sent : %d", td->requestInfo->info.numOptions);
- gRequestHandler(rep, td->requestInfo);
- }
-
- if (NULL != td->requestInfo->info.options)
- {
- OICFree(td->requestInfo->info.options);
- }
-
- if (NULL != td->requestInfo->info.payload)
+ if (g_requestHandler)
{
- OICFree(td->requestInfo->info.payload);
+ g_requestHandler(rep, td->requestInfo);
}
- if (NULL != td->requestInfo->info.token)
- {
- OICFree(td->requestInfo->info.token);
- }
+ OICFree(td->requestInfo->info.options);
+ OICFree(td->requestInfo->info.payload);
+ OICFree(td->requestInfo->info.token);
OICFree(td->requestInfo);
}
if (td->responseInfo != NULL)
{
- if (gResponseHandler)
- {
- gResponseHandler(rep, td->responseInfo);
- }
-
- if (NULL != td->responseInfo->info.options)
+ if (g_responseHandler)
{
- OICFree(td->responseInfo->info.options);
+ g_responseHandler(rep, td->responseInfo);
}
- if (NULL != td->responseInfo->info.payload)
- {
- OICFree(td->responseInfo->info.payload);
- }
-
- if (NULL != td->responseInfo->info.token)
- {
- OICFree(td->responseInfo->info.token);
- }
+ OICFree(td->responseInfo->info.options);
+ OICFree(td->responseInfo->info.payload);
+ OICFree(td->responseInfo->info.token);
OICFree(td->responseInfo);
}
}
OICFree(rep);
-
-
-#endif
OIC_LOG_V(DEBUG, TAG, "CAHandleRequestResponseCallbacks OUT");
}
CARemoteEndpoint_t *remoteEndpoint = NULL;
CARequestInfo_t *requestInfo = NULL;
- CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
- MEMORY_ALLOC_CHECK(data);
-
- // initialize
- memset(data, 0, sizeof(CAData_t));
+ CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+ CA_MEMORY_ALLOC_CHECK(data);
// clone remote endpoint
remoteEndpoint = CACloneRemoteEndpoint(object);
- MEMORY_ALLOC_CHECK(remoteEndpoint);
+ CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
// clone request info
requestInfo = CACloneRequestInfo(request);
- MEMORY_ALLOC_CHECK(requestInfo);
+ CA_MEMORY_ALLOC_CHECK(requestInfo);
// save data
data->type = SEND_TYPE_UNICAST;
data->responseInfo = NULL;
// add thread
- CAQueueingThreadAddData(&gSendThread, data, sizeof(CAData_t));
+ CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
return CA_STATUS_OK;
CARemoteEndpoint_t *remoteEndpoint = NULL;
CARequestInfo_t *requestInfo = NULL;
- CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
- MEMORY_ALLOC_CHECK(data);
-
- // initialize
- memset(data, 0, sizeof(CAData_t));
+ CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+ CA_MEMORY_ALLOC_CHECK(data);
CAAddress_t addr;
memset(&addr, 0, sizeof(CAAddress_t));
// clone request info
requestInfo = CACloneRequestInfo(request);
- MEMORY_ALLOC_CHECK(requestInfo);
+ CA_MEMORY_ALLOC_CHECK(requestInfo);
// save data
data->type = SEND_TYPE_MULTICAST;
data->responseInfo = NULL;
// add thread
- CAQueueingThreadAddData(&gSendThread, data, sizeof(CAData_t));
+ CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
return CA_STATUS_OK;
CARemoteEndpoint_t *remoteEndpoint = NULL;
CAResponseInfo_t *responseInfo = NULL;
- CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
- MEMORY_ALLOC_CHECK(data);
-
- // initialize
- memset(data, 0, sizeof(CAData_t));
+ CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+ CA_MEMORY_ALLOC_CHECK(data);
// clone remote endpoint
remoteEndpoint = CACloneRemoteEndpoint(object);
- MEMORY_ALLOC_CHECK(remoteEndpoint);
+ CA_MEMORY_ALLOC_CHECK(remoteEndpoint);
// clone response info
responseInfo = CACloneResponseInfo(response);
- MEMORY_ALLOC_CHECK(responseInfo);
+ CA_MEMORY_ALLOC_CHECK(responseInfo);
// save data
data->type = SEND_TYPE_UNICAST;
data->responseInfo = responseInfo;
// add thread
- CAQueueingThreadAddData(&gSendThread, data, sizeof(CAData_t));
+ CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
return CA_STATUS_OK;
}
CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
- const CAHeaderOption_t *options, uint8_t numOptions)
+ const CAHeaderOption_t *options,const uint8_t numOptions)
{
if (resourceUri == NULL)
{
CAToken_t tempToken = NULL;
CARemoteEndpoint_t *remoteEndpoint = NULL;
- CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
- MEMORY_ALLOC_CHECK(data);
-
- // initialize
- memset(data, 0, sizeof(CAData_t));
+ CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+ CA_MEMORY_ALLOC_CHECK(data);
- CAAddress_t addr;
- memset(&addr, 0, sizeof(CAAddress_t));
+ CAAddress_t addr = {};
remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE);
// create request info
- ReqInfo = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
- MEMORY_ALLOC_CHECK(ReqInfo);
- memset(ReqInfo, 0, sizeof(CARequestInfo_t));
+ ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
+ CA_MEMORY_ALLOC_CHECK(ReqInfo);
// copy token value
if (token != NULL)
{
int32_t len = strlen(token);
- tempToken = (char *) OICMalloc(sizeof(char) * (len + 1));
- MEMORY_ALLOC_CHECK(tempToken);
- memset(tempToken, 0, sizeof(char) * (len + 1));
+ tempToken = (char *) OICCalloc((len + 1), sizeof(char));
+ CA_MEMORY_ALLOC_CHECK(tempToken);
strncpy(tempToken, token, len);
}
if (options != NULL && numOptions > 0)
{
// copy data
- CAHeaderOption_t *temp = (CAHeaderOption_t *) OICMalloc(
- sizeof(CAHeaderOption_t) * numOptions);
+ CAHeaderOption_t *temp = (CAHeaderOption_t *) OICCalloc(numOptions,
+ sizeof(CAHeaderOption_t));
+ CA_MEMORY_ALLOC_CHECK(temp);
- MEMORY_ALLOC_CHECK(temp);
-
- memset(temp, 0, sizeof(CAHeaderOption_t) * numOptions);
memcpy(temp, options, sizeof(CAHeaderOption_t) * numOptions);
data->options = temp;
}
// add thread
- CAQueueingThreadAddData(&gSendThread, data, sizeof(CAData_t));
+ CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, TAG, "set request, response handler callback.");
- gRequestHandler = ReqHandler;
- gResponseHandler = RespHandler;
+ g_requestHandler = ReqHandler;
+ g_responseHandler = RespHandler;
}
CAResult_t CAInitializeMessageHandler()
// create thread pool
CAResult_t res;
- res = u_thread_pool_init(MAX_THREAD_POOL_SIZE, &gThreadPoolHandle);
+ res = u_thread_pool_init(MAX_THREAD_POOL_SIZE, &g_threadPoolHandle);
if (res != CA_STATUS_OK)
{
- OIC_LOG_V(DEBUG, TAG, "thread pool initialize error.");
+ OIC_LOG_V(ERROR, TAG, "thread pool initialize error.");
return res;
}
// send thread initialize
- CAQueueingThreadInitialize(&gSendThread, gThreadPoolHandle, CASendThreadProcess,
+ CAQueueingThreadInitialize(&g_sendThread, g_threadPoolHandle, CASendThreadProcess,
CADataDestroyer);
// start send thread
- res = CAQueueingThreadStart(&gSendThread);
+ res = CAQueueingThreadStart(&g_sendThread);
if (res != CA_STATUS_OK)
{
- OIC_LOG_V(DEBUG, TAG, "thread start error(send thread).");
+ OIC_LOG_V(ERROR, TAG, "thread start error(send thread).");
+ u_thread_pool_free(g_threadPoolHandle);
+ g_threadPoolHandle = NULL;
return res;
}
// receive thread initialize
- CAQueueingThreadInitialize(&gReceiveThread, gThreadPoolHandle, CAReceiveThreadProcess,
+ CAQueueingThreadInitialize(&g_receiveThread, g_threadPoolHandle, CAReceiveThreadProcess,
CADataDestroyer);
-#ifndef SINGLE_HANDLE// This will be enabled when RI supports multi threading
+#ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
// start receive thread
res = CAQueueingThreadStart(&gReceiveThread);
#endif
// retransmission initialize
- CARetransmissionInitialize(&gRetransmissionContext, gThreadPoolHandle, CASendUnicastData,
+ CARetransmissionInitialize(&g_retransmissionContext, g_threadPoolHandle, CASendUnicastData,
CATimeoutCallback, NULL);
// start retransmission
- res = CARetransmissionStart(&gRetransmissionContext);
+ res = CARetransmissionStart(&g_retransmissionContext);
if (res != CA_STATUS_OK)
{
- OIC_LOG_V(DEBUG, TAG, "thread start error(retransmission thread).");
+ OIC_LOG_V(ERROR, TAG, "thread start error(retransmission thread).");
return res;
}
// initialize interface adapters by controller
- CAInitializeAdapters(gThreadPoolHandle);
+ CAInitializeAdapters(g_threadPoolHandle);
return CA_STATUS_OK;
}
void CATerminateMessageHandler()
{
- // terminate interface adapters by controller
- CATerminateAdapters();
+ uint8_t i = 0;
+ CAConnectivityType_t connType;
+ u_arraylist_t *list = CAGetSelectedNetworkList();
+ uint32_t length = u_arraylist_length(list);
+
+ for (i = 0; i < length; i++)
+ {
+ void* ptrType = u_arraylist_get(list, i);
+
+ if (ptrType == NULL)
+ {
+ continue;
+ }
+
+ connType = *(CAConnectivityType_t *) ptrType;
+ CAStopAdapter(connType);
+ }
// stop retransmission
- if(gRetransmissionContext.threadMutex != NULL) {
- CARetransmissionStop(&gRetransmissionContext);
- CARetransmissionDestroy(&gRetransmissionContext);
+ if (g_retransmissionContext.threadMutex != NULL)
+ {
+ CARetransmissionStop(&g_retransmissionContext);
}
// stop thread
// delete thread data
- if(gSendThread.threadMutex != NULL) {
- CAQueueingThreadStop(&gSendThread);
- CAQueueingThreadDestroy(&gSendThread);
+ if (g_sendThread.threadMutex != NULL)
+ {
+ CAQueueingThreadStop(&g_sendThread);
}
// stop thread
// delete thread data
- if(gReceiveThread.threadMutex != NULL) {
- #ifndef SINGLE_HANDLE// This will be enabled when RI supports multi threading
- // CAQueueingThreadStop(&gReceiveThread);
- #endif
- CAQueueingThreadDestroy(&gReceiveThread);
+ if (g_receiveThread.threadMutex != NULL)
+ {
+#ifndef SINGLE_HANDLE // This will be enabled when RI supports multi threading
+ CAQueueingThreadStop(&gReceiveThread);
+#endif
}
// destroy thread pool
- if(gThreadPoolHandle != NULL) {
- u_thread_pool_free(gThreadPoolHandle);
- gThreadPoolHandle = NULL;
+ if (g_threadPoolHandle != NULL)
+ {
+ u_thread_pool_free(g_threadPoolHandle);
+ g_threadPoolHandle = NULL;
}
+ CARetransmissionDestroy(&g_retransmissionContext);
+ CAQueueingThreadDestroy(&g_sendThread);
+ CAQueueingThreadDestroy(&g_receiveThread);
+
+ // terminate interface adapters by controller
+ CATerminateAdapters();
+
OIC_LOG_V(DEBUG, TAG, "message handler termination is complete!");
}
#define TAG "CAMH_ST"
-#define MEMORY_ALLOC_CHECK(arg) { if (arg == NULL) {OIC_LOG(DEBUG, TAG, "Out of memory");\
+#define CA_MEMORY_ALLOC_CHECK(arg) { if (arg == NULL) {OIC_LOG(DEBUG, TAG, "Out of memory");\
goto memory_error_exit;} }
-#define MAX_THREAD_POOL_SIZE 10
#define CA_MAX_RT_ARRAY_SIZE 3
typedef enum
uint8_t numOptions;
} CAData_t;
-// message handler callback
-static CAMessageHandlerCallback gHandlerCallback = NULL;
-static CARetransmission_t gRetransmissionContext;
+static CARetransmission_t g_retransmissionContext;
// handler field
-static CARequestCallback gRequestHandler = NULL;
-static CAResponseCallback gResponseHandler = NULL;
+static CARequestCallback g_requestHandler = NULL;
+static CAResponseCallback g_responseHandler = NULL;
static void CAProcessData(CAData_t *data)
{
OIC_LOG(DEBUG, TAG, "reqInfo avlbl");
pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri,
- data->requestInfo->method,
- data->requestInfo->info);
+ data->requestInfo->method, data->requestInfo->info);
}
else if (data->responseInfo != NULL)
{
OIC_LOG(DEBUG, TAG, "resInfo avlbl");
+
pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri,
data->responseInfo->result,
data->responseInfo->info);
// interface controller function call.
if (NULL != pdu)
{
- OIC_LOG_V(DEBUG, TAG, "payload: %s", pdu->data);
-
- OIC_LOG_V(DEBUG, TAG, "code: %d", pdu->hdr->code);
-
- OIC_LOG_V(DEBUG, TAG, "buffer: %s", pdu->hdr);
+ CALogPDUData(pdu);
res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
-
+ if(CA_STATUS_OK != res)
+ {
+ OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+ coap_delete_pdu(pdu);
+ return;
+ }
// for retransmission
- CARetransmissionSentData(&gRetransmissionContext, data->remoteEndpoint, pdu->hdr,
+ CARetransmissionSentData(&g_retransmissionContext, data->remoteEndpoint, pdu->hdr,
pdu->length);
}
coap_delete_pdu(pdu);
OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
coap_pdu_t *pdu = NULL;
- CAInfo_t info;
- memset(&info, 0, sizeof(CAInfo_t));
+ CAInfo_t info = { 0 };
info.options = data->options;
info.numOptions = data->numOptions;
if (NULL != pdu)
{
- OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data);
-
- OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type);
-
- OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code);
-
- OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", pdu->hdr->id);
-
- OIC_LOG_V(DEBUG, TAG, "PDU Maker - token : %s", pdu->hdr->token);
- OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %s", pdu->hdr);
-
+ CALogPDUData(pdu);
res = CASendMulticastData(pdu->hdr, pdu->length);
+ if(CA_STATUS_OK != res)
+ {
+ OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
+ coap_delete_pdu(pdu);
+ return;
+ }
}
coap_delete_pdu(pdu);
}
- else
- {
- OIC_LOG(DEBUG, TAG, "unknown type!");
- }
- if (gHandlerCallback != NULL)
- {
- gHandlerCallback("", res);
- }
OIC_LOG(DEBUG, TAG, "OUT");
}
-static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, void *pdu, uint32_t size)
+static void CATimeoutCallback(const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
{
OIC_LOG(DEBUG, TAG, "IN");
CARemoteEndpoint_t* ep = CACloneRemoteEndpoint(endpoint);
if (ep == NULL)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "clone failed");
return;
}
- CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICMalloc(sizeof(CAResponseInfo_t));
+ CAResponseInfo_t* resInfo = (CAResponseInfo_t*) OICCalloc(1, sizeof(CAResponseInfo_t));
if (resInfo == NULL)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "calloc failed");
CADestroyRemoteEndpointInternal(ep);
return;
}
- memset(resInfo, 0, sizeof(CAResponseInfo_t));
-
- CAMessageType_t type = CAGetMessageTypeFromPduBinaryData(pdu, size);
- uint16_t messageId = CAGetMessageIdFromPduBinaryData(pdu, size);
resInfo->result = CA_RETRANSMIT_TIMEOUT;
- resInfo->info.type = type;
- resInfo->info.messageId = messageId;
+ resInfo->info.type = CAGetMessageTypeFromPduBinaryData(pdu, size);;
+ resInfo->info.messageId = CAGetMessageIdFromPduBinaryData(pdu, size);;
- if (gResponseHandler)
+ if (g_responseHandler)
{
- gResponseHandler(ep, resInfo);
+ g_responseHandler(ep, resInfo);
}
+
CADestroyRemoteEndpointInternal(ep);
OICFree(resInfo);
OIC_LOG(DEBUG, TAG, "OUT");
}
static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data,
- uint32_t dataLen)
+ uint32_t dataLen)
{
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_VOID(data, TAG, "data");
- coap_pdu_t *pdu;
uint32_t code = CA_NOT_FOUND;
- pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
- //OICFree(data);
-
- if(NULL == pdu)
+ coap_pdu_t *pdu = (coap_pdu_t *) CAParsePDU((const char *) data, dataLen, &code);
+ if (NULL == pdu)
{
- OIC_LOG(ERROR, TAG, "pdu is null");
+ OIC_LOG(ERROR, TAG, "Parse PDU failed");
return;
}
+ //OICFree(data);
char uri[CA_MAX_URI_LENGTH] = { 0, };
+ uint32_t bufLen = sizeof(uri);
if (CA_GET == code || CA_POST == code || CA_PUT == code || CA_DELETE == code )
{
- CARequestInfo_t *ReqInfo;
- ReqInfo = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
+ CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
if (ReqInfo == NULL)
{
- OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
+ OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
coap_delete_pdu(pdu);
return;
}
- memset(ReqInfo, 0, sizeof(CARequestInfo_t));
- CAGetRequestInfoFromPdu(pdu, ReqInfo, uri);
+ CAGetRequestInfoFromPdu(pdu, ReqInfo, uri, bufLen);
if (NULL != ReqInfo->info.options)
{
uint32_t i;
OIC_LOG_V(DEBUG, TAG, "Request- code: %d", ReqInfo->method);
OIC_LOG_V(DEBUG, TAG, "Request- token : %s", ReqInfo->info.token);
- OIC_LOG_V(DEBUG, TAG, "Request- msgID : %d", ReqInfo->info.messageId);
+
if (NULL != endpoint)
{
- endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
+ endpoint->resourceUri = (char *) OICCalloc(bufLen + 1, sizeof(char));
if (endpoint->resourceUri == NULL)
{
- OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
+ OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
coap_delete_pdu(pdu);
OICFree(ReqInfo);
return;
}
- memset(endpoint->resourceUri, 0, strlen(uri) + 1);
- memcpy(endpoint->resourceUri, uri, strlen(uri));
+ memcpy(endpoint->resourceUri, uri, bufLen);
OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
}
if (ReqInfo)
{
- if (gRequestHandler)
+ if (g_requestHandler)
{
- gRequestHandler(endpoint, ReqInfo);
+ g_requestHandler(endpoint, ReqInfo);
}
CADestroyRequestInfoInternal(ReqInfo);
}
else
{
- CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICMalloc(sizeof(CAResponseInfo_t));
+ CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
if (ResInfo == NULL)
{
- OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
+ OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
coap_delete_pdu(pdu);
return;
}
- memset(ResInfo, 0, sizeof(CAResponseInfo_t));
- CAGetResponseInfoFromPdu(pdu, ResInfo, uri);
+
+ CAGetResponseInfoFromPdu(pdu, ResInfo, uri, bufLen);
if (NULL != ResInfo->info.options)
{
if (NULL != endpoint)
{
- endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
+ endpoint->resourceUri = (char *) OICCalloc(bufLen + 1, sizeof(char));
if (endpoint->resourceUri == NULL)
{
- OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed !");
+ OIC_LOG(DEBUG, TAG, "CAReceivedPacketCallback, Memory allocation failed!");
coap_delete_pdu(pdu);
OICFree(ResInfo);
return;
}
- memset(endpoint->resourceUri, 0, strlen(uri) + 1);
- memcpy(endpoint->resourceUri, uri, strlen(uri));
+ memcpy(endpoint->resourceUri, uri, bufLen);
OIC_LOG_V(DEBUG, TAG, "URI : %s", endpoint->resourceUri);
}
- // for retransmission
- void *retransmissionPdu = NULL;
- CARetransmissionReceivedData(&gRetransmissionContext, endpoint, pdu->hdr, pdu->length,
- &retransmissionPdu);
-
- // get token from saved data in retransmission list
- if(retransmissionPdu && CA_EMPTY == code)
- {
- CAGetTokenFromPDU((const coap_hdr_t *)retransmissionPdu, &(ResInfo->info));
- OICFree(retransmissionPdu);
- }
-
if (ResInfo != NULL)
{
- if (gResponseHandler)
+ if (g_responseHandler)
{
- gResponseHandler(endpoint, ResInfo);
+ g_responseHandler(endpoint, ResInfo);
+
+ // for retransmission
+ CARetransmissionReceivedData(&g_retransmissionContext, endpoint, pdu->hdr,
+ pdu->length);
}
CADestroyResponseInfoInternal(ResInfo);
}
void CAHandleRequestResponseCallbacks()
{
CAReadData();
- CARetransmissionBaseRoutine((void *)&gRetransmissionContext);
+ CARetransmissionBaseRoutine((void *)&g_retransmissionContext);
}
CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object,
VERIFY_NON_NULL(object, TAG, "object");
VERIFY_NON_NULL(request, TAG, "request");
+
// If max retransmission queue is reached, then don't handle new request
- if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(gRetransmissionContext.dataList))
+ if (CA_MAX_RT_ARRAY_SIZE == u_arraylist_length(g_retransmissionContext.dataList))
{
- OIC_LOG(DEBUG, TAG, "max RT queue size rchd");
+ OIC_LOG(ERROR, TAG, "max RT queue size reached!");
return CA_SEND_FAILED;
}
- CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
- MEMORY_ALLOC_CHECK(data);
-
- // initialize
- memset(data, 0, sizeof(CAData_t));
-
+ // allocate & initialize
+ CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+ CA_MEMORY_ALLOC_CHECK(data);
// save data
data->type = SEND_TYPE_UNICAST;
{
OIC_LOG(DEBUG, TAG, "IN");
-
if (object == NULL || request == NULL)
{
return CA_STATUS_FAILED;
}
- CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
- MEMORY_ALLOC_CHECK(data);
-
- // initialize
- memset(data, 0, sizeof(CAData_t));
+ // allocate & initialize
+ CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+ CA_MEMORY_ALLOC_CHECK(data);
- CAAddress_t addr;
- memset(&addr, 0, sizeof(CAAddress_t));
+ CAAddress_t addr = {0};
CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(object->resourceUri, addr,
- object->connectivityType);
+ object->connectivityType);
// save data
data->type = SEND_TYPE_MULTICAST;
OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL(object, TAG, "object");
VERIFY_NON_NULL(response, TAG, "response");
- CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
- MEMORY_ALLOC_CHECK(data);
- // initialize
- memset(data, 0, sizeof(CAData_t));
+ // allocate & initialize
+ CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+ CA_MEMORY_ALLOC_CHECK(data);
// save data
data->type = SEND_TYPE_UNICAST;
{
return CA_STATUS_FAILED;
}
+
CARemoteEndpoint_t *remoteEndpoint = NULL;
- CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
- MEMORY_ALLOC_CHECK(data);
- // initialize
- memset(data, 0, sizeof(CAData_t));
+ // allocate & initialize
+ CAData_t *data = (CAData_t *) OICCalloc(1, sizeof(CAData_t));
+ CA_MEMORY_ALLOC_CHECK(data);
- CAAddress_t addr;
- memset(&addr, 0, sizeof(CAAddress_t));
+ CAAddress_t addr = {0};
remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE);
// save data
data->type = SEND_TYPE_MULTICAST;
data->remoteEndpoint = remoteEndpoint;
- CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
- MEMORY_ALLOC_CHECK(ReqInfo);
- memset(ReqInfo, 0, sizeof(CARequestInfo_t));
+ CARequestInfo_t *ReqInfo = (CARequestInfo_t *) OICCalloc(1, sizeof(CARequestInfo_t));
+ CA_MEMORY_ALLOC_CHECK(ReqInfo);
ReqInfo->method = CA_GET;
ReqInfo->info.token = token;
ReqInfo->info.type = CA_MSG_NONCONFIRM;
if (options != NULL && numOptions > 0)
{
// copy data
- temp = (CAHeaderOption_t *) OICMalloc(
- sizeof(CAHeaderOption_t) * numOptions);
-
- MEMORY_ALLOC_CHECK(temp);
-
- memset(temp, 0, sizeof(CAHeaderOption_t) * numOptions);
+ temp = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * numOptions);
+ CA_MEMORY_ALLOC_CHECK(temp);
memcpy(temp, options, sizeof(CAHeaderOption_t) * numOptions);
data->options = temp;
CADestroyRemoteEndpointInternal(remoteEndpoint);
- if (data != NULL)
- {
- OICFree(data);
- }
+ OICFree(data);
OIC_LOG(DEBUG, TAG, "OUT");
return CA_MEMORY_ALLOC_FAILED;
}
-void CASetMessageHandlerCallback(CAMessageHandlerCallback callback)
-{
- OIC_LOG(DEBUG, TAG, "IN");
- gHandlerCallback = callback;
- OIC_LOG(DEBUG, TAG, "OUT");
-}
-
void CASetRequestResponseCallbacks(CARequestCallback ReqHandler,
CAResponseCallback RespHandler)
{
OIC_LOG(DEBUG, TAG, "IN");
- gRequestHandler = ReqHandler;
- gResponseHandler = RespHandler;
+ g_requestHandler = ReqHandler;
+ g_responseHandler = RespHandler;
OIC_LOG(DEBUG, TAG, "OUT");
}
CAResult_t res;
// retransmission initialize
- CARetransmissionInitialize(&gRetransmissionContext, CASendUnicastData, CATimeoutCallback, NULL);
+ CARetransmissionInitialize(&g_retransmissionContext, CASendUnicastData, CATimeoutCallback, NULL);
CAInitializeAdapters();
OIC_LOG(DEBUG, TAG, "OUT");
CATerminateAdapters();
// stop retransmission
- CARetransmissionStop(&gRetransmissionContext);
- CARetransmissionDestroy(&gRetransmissionContext);
+ CARetransmissionStop(&g_retransmissionContext);
+ CARetransmissionDestroy(&g_retransmissionContext);
OIC_LOG(DEBUG, TAG, "OUT");
}
+
#define TAG PCF("CA")
-static u_arraylist_t *gSelectedNetworkList = NULL;
+static u_arraylist_t *g_selectedNetworkList = NULL;
static uint32_t NETWORK_ETHERNET = CA_ETHERNET;
static uint32_t NETWORK_WIFI = CA_WIFI;
static uint32_t NETWORK_EDR = CA_EDR;
static uint32_t NETWORK_LE = CA_LE;
-CAResult_t CAAddNetworkType(uint32_t ConnectivityType)
+CAResult_t CAAddNetworkType(CAConnectivityType_t connectivityType)
{
- if (gSelectedNetworkList == NULL)
+ if (g_selectedNetworkList == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "Create network list");
+ OIC_LOG(DEBUG, TAG, "Create network list");
- gSelectedNetworkList = u_arraylist_create();
+ g_selectedNetworkList = u_arraylist_create();
- if( gSelectedNetworkList == NULL )
+ if( g_selectedNetworkList == NULL )
{
- return CA_STATUS_FAILED;
+ return CA_MEMORY_ALLOC_FAILED;
}
}
- switch (ConnectivityType)
+ CAResult_t res = CA_STATUS_OK;
+ switch (connectivityType)
{
case CA_ETHERNET:
{
#ifndef ETHERNET_ADAPTER
- OIC_LOG_V(DEBUG, TAG, "Add network type(ETHERNET) - Not Supported");
+ OIC_LOG(DEBUG, TAG, "Add network type(ETHERNET) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* ETHERNET_ADAPTER */
- OIC_LOG_V(DEBUG, TAG, "Add network type(ETHERNET)");
- if (!u_arraylist_contains(gSelectedNetworkList, &NETWORK_ETHERNET))
+ OIC_LOG(DEBUG, TAG, "Add network type(ETHERNET)");
+ if (!u_arraylist_contains(g_selectedNetworkList, &NETWORK_ETHERNET))
{
- u_arraylist_add(gSelectedNetworkList, &NETWORK_ETHERNET);
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_ETHERNET);
}
}
- break;
+ break;
case CA_WIFI:
{
#ifndef WIFI_ADAPTER
- OIC_LOG_V(DEBUG, TAG, "Add network type(WIFI) - Not Supported");
+ OIC_LOG(DEBUG, TAG, "Add network type(WIFI) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* WIFI_ADAPTER */
- OIC_LOG_V(DEBUG, TAG, "Add network type(WIFI)");
- if (!u_arraylist_contains(gSelectedNetworkList, &NETWORK_WIFI))
+ OIC_LOG(DEBUG, TAG, "Add network type(WIFI)");
+ if (!u_arraylist_contains(g_selectedNetworkList, &NETWORK_WIFI))
{
- u_arraylist_add(gSelectedNetworkList, &NETWORK_WIFI);
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_WIFI);
}
}
- break;
+ break;
case CA_EDR:
{
#ifndef EDR_ADAPTER
- OIC_LOG_V(DEBUG, TAG, "Add network type(EDR) - Not Supported");
+ OIC_LOG(DEBUG, TAG, "Add network type(EDR) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* EDR_ADAPTER */
- OIC_LOG_V(DEBUG, TAG, "Add network type(EDR)");
- if (!u_arraylist_contains(gSelectedNetworkList, &NETWORK_EDR))
+ OIC_LOG(DEBUG, TAG, "Add network type(EDR)");
+ if (!u_arraylist_contains(g_selectedNetworkList, &NETWORK_EDR))
{
- u_arraylist_add(gSelectedNetworkList, &NETWORK_EDR);
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_EDR);
}
}
- break;
+ break;
case CA_LE:
{
#ifndef LE_ADAPTER
- OIC_LOG_V(DEBUG, TAG, "Add network type(LE) - Not Supported");
+ OIC_LOG(DEBUG, TAG, "Add network type(LE) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* LE_ADAPTER */
- OIC_LOG_V(DEBUG, TAG, "Add network type(LE)");
- if (!u_arraylist_contains(gSelectedNetworkList, &NETWORK_LE))
+ OIC_LOG(DEBUG, TAG, "Add network type(LE)");
+ if (!u_arraylist_contains(g_selectedNetworkList, &NETWORK_LE))
{
- u_arraylist_add(gSelectedNetworkList, &NETWORK_LE);
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_LE);
}
}
- break;
+ break;
}
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG_V(ERROR, TAG, "Add arraylist failed[Err code: %d]", res);
+ return res;
+ }
// start selected interface adapter
- CAStartAdapter((CAConnectivityType_t)ConnectivityType);
+ res = CAStartAdapter((CAConnectivityType_t)connectivityType);
- return CA_STATUS_OK;
+ return res;
}
-CAResult_t CARemoveNetworkType(uint32_t ConnectivityType)
+CAResult_t CARemoveNetworkType(CAConnectivityType_t connectivityType)
{
uint8_t index;
CAConnectivityType_t connType;
- if (gSelectedNetworkList == NULL)
+ if (g_selectedNetworkList == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "Selected network not found");
+ OIC_LOG(DEBUG, TAG, "SelectedNetwork list is NULL");
return CA_STATUS_FAILED;
}
- for (index = 0; index < u_arraylist_length(gSelectedNetworkList); index++)
+ for (index = 0; index < u_arraylist_length(g_selectedNetworkList); index++)
{
- void* ptrType = u_arraylist_get(gSelectedNetworkList, index);
+ void* ptrType = u_arraylist_get(g_selectedNetworkList, index);
if(ptrType == NULL)
{
connType = *(CAConnectivityType_t *) ptrType;
- if (ConnectivityType == connType)
+ if (connectivityType == connType)
{
- switch (ConnectivityType)
+ switch (connectivityType)
{
case CA_ETHERNET:
#ifndef ETHERNET_ADAPTER
- OIC_LOG_V(DEBUG, TAG, "Remove network type(ETHERNET) - Not Supported");
+ OIC_LOG(DEBUG, TAG, "Remove network type(ETHERNET) - Not Supported");
return CA_NOT_SUPPORTED;
#else
- OIC_LOG_V(DEBUG, TAG, "Remove network type(ETHERNET)");
- u_arraylist_remove(gSelectedNetworkList, index);
+ OIC_LOG(DEBUG, TAG, "Remove network type(ETHERNET)");
+ u_arraylist_remove(g_selectedNetworkList, index);
#endif /* ETHERNET_ADAPTER */
break;
case CA_WIFI:
#ifndef WIFI_ADAPTER
- OIC_LOG_V(DEBUG, TAG, "Remove network type(WIFI) - Not Supported");
+ OIC_LOG(DEBUG, TAG, "Remove network type(WIFI) - Not Supported");
return CA_NOT_SUPPORTED;
#else
- OIC_LOG_V(DEBUG, TAG, "Remove network type(WIFI)");
- u_arraylist_remove(gSelectedNetworkList, index);
+ OIC_LOG(DEBUG, TAG, "Remove network type(WIFI)");
+ u_arraylist_remove(g_selectedNetworkList, index);
#endif /* WIFI_ADAPTER */
break;
case CA_EDR:
#ifndef EDR_ADAPTER
- OIC_LOG_V(DEBUG, TAG, "Remove network type(EDR) - Not Supported");
+ OIC_LOG(DEBUG, TAG, "Remove network type(EDR) - Not Supported");
return CA_NOT_SUPPORTED;
#else
- OIC_LOG_V(DEBUG, TAG, "Remove network type(EDR)");
- u_arraylist_remove(gSelectedNetworkList, index);
+ OIC_LOG(DEBUG, TAG, "Remove network type(EDR)");
+ u_arraylist_remove(g_selectedNetworkList, index);
#endif /* EDR_ADAPTER */
break;
case CA_LE:
#ifndef LE_ADAPTER
- OIC_LOG_V(DEBUG, TAG, "Remove network type(LE) - Not Supported");
+ OIC_LOG(DEBUG, TAG, "Remove network type(LE) - Not Supported");
return CA_NOT_SUPPORTED;
#else
- OIC_LOG_V(DEBUG, TAG, "Remove network type(LE)");
- u_arraylist_remove(gSelectedNetworkList, index);
+ OIC_LOG(DEBUG, TAG, "Remove network type(LE)");
+ u_arraylist_remove(g_selectedNetworkList, index);
#endif /* LE_ADAPTER */
break;
u_arraylist_t *CAGetSelectedNetworkList()
{
OIC_LOG(DEBUG, TAG, "CAGetSelectedNetworkList IN");
- if (gSelectedNetworkList == NULL)
+ if (g_selectedNetworkList == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "Selected network not found");
-
+ OIC_LOG(DEBUG, TAG, "SelectedNetwork list is NULL");
return NULL;
}
OIC_LOG(DEBUG, TAG, "CAGetSelectedNetworkList OUT");
- return gSelectedNetworkList;
+ return g_selectedNetworkList;
}
CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size)
{
- OIC_LOG_V(DEBUG, TAG, "get network information.");
+ OIC_LOG(DEBUG, TAG, "get network information.");
if (info == NULL || size == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "Input parameter is invalid value");
+ OIC_LOG(DEBUG, TAG, "Input parameter is invalid value");
return CA_STATUS_INVALID_PARAM;
}
CAResult_t CATerminateNetworkType()
{
- OIC_LOG_V(DEBUG, TAG, "CATerminateNetworkType()");
+ OIC_LOG(DEBUG, TAG, "CATerminateNetworkType()");
- if(gSelectedNetworkList != NULL)
+ if(g_selectedNetworkList != NULL)
{
- u_arraylist_free(&gSelectedNetworkList);
+ u_arraylist_free(&g_selectedNetworkList);
}
return CA_STATUS_OK;
#define TAG "CANW_ST"
-static u_arraylist_t *gSelectedNetworkList = NULL;
+static u_arraylist_t *g_selectedNetworkList = NULL;
static uint32_t NETWORK_ETHERNET = CA_ETHERNET;
static uint32_t NETWORK_WIFI = CA_WIFI;
static uint32_t NETWORK_EDR = CA_EDR;
static uint32_t NETWORK_LE = CA_LE;
-CAResult_t CAAddNetworkType(uint32_t ConnectivityType)
+CAResult_t CAAddNetworkType(CAConnectivityType_t connectivityType)
{
OIC_LOG(DEBUG, TAG, "IN");
- if (gSelectedNetworkList == NULL)
+ if (g_selectedNetworkList == NULL)
{
- gSelectedNetworkList = u_arraylist_create();
+ g_selectedNetworkList = u_arraylist_create();
- if (NULL == gSelectedNetworkList)
+ if (NULL == g_selectedNetworkList)
{
- return CA_STATUS_FAILED;
+ return CA_MEMORY_ALLOC_FAILED;
}
}
-
- switch (ConnectivityType)
+ CAResult_t res = CA_STATUS_OK;
+ switch (connectivityType)
{
case CA_ETHERNET:
+ {
-#ifdef ETHERNET_ADAPTER
- OIC_LOG(DEBUG, TAG, "Add network type(ETHERNET)");
- u_arraylist_add(gSelectedNetworkList, &NETWORK_ETHERNET);
-#else
+#ifndef ETHERNET_ADAPTER
OIC_LOG(DEBUG, TAG, "Add network type(ETHERNET) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* ETHERNET_ADAPTER */
- break;
+ OIC_LOG(DEBUG, TAG, "Add network type(ETHERNET)");
+ if (!u_arraylist_contains(g_selectedNetworkList, &NETWORK_ETHERNET))
+ {
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_ETHERNET);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG_V(ERROR, TAG, "Add arraylist failed[Err code: %d]", res);
+ return res;
+ }
+ }
+ }
+ break;
case CA_WIFI:
+ {
-#ifdef WIFI_ADAPTER
- OIC_LOG(DEBUG, TAG, "Add network type(WIFI)");
- u_arraylist_add(gSelectedNetworkList, &NETWORK_WIFI);
-#else
+#ifndef WIFI_ADAPTER
OIC_LOG(DEBUG, TAG, "Add network type(WIFI) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* WIFI_ADAPTER */
- break;
+ OIC_LOG(DEBUG, TAG, "Add network type(WIFI)");
+ if (!u_arraylist_contains(g_selectedNetworkList, &NETWORK_WIFI))
+ {
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_WIFI);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG_V(ERROR, TAG, "Add arraylist failed[Err code: %d]", res);
+ return res;
+ }
+ }
+ }
+ break;
case CA_EDR:
+ {
-#ifdef EDR_ADAPTER
- OIC_LOG(DEBUG, TAG, "Add network type(EDR)");
- u_arraylist_add(gSelectedNetworkList, &NETWORK_EDR);
-#else
+#ifndef EDR_ADAPTER
OIC_LOG(DEBUG, TAG, "Add network type(EDR) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* EDR_ADAPTER */
- break;
+ OIC_LOG(DEBUG, TAG, "Add network type(EDR)");
+ if (!u_arraylist_contains(g_selectedNetworkList, &NETWORK_EDR))
+ {
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_EDR);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG_V(ERROR, TAG, "Add arraylist failed[Err code: %d]", res);
+ return res;
+ }
+ }
+ }
+ break;
case CA_LE:
+ {
-#ifdef LE_ADAPTER
- OIC_LOG(DEBUG, TAG, "Add network type(LE)");
- u_arraylist_add(gSelectedNetworkList, &NETWORK_LE);
-#else
+#ifndef LE_ADAPTER
OIC_LOG(DEBUG, TAG, "Add network type(LE) - Not Supported");
return CA_NOT_SUPPORTED;
#endif /* LE_ADAPTER */
- break;
+ OIC_LOG(DEBUG, TAG, "Add network type(LE)");
+ if (!u_arraylist_contains(g_selectedNetworkList, &NETWORK_LE))
+ {
+ res = u_arraylist_add(g_selectedNetworkList, &NETWORK_LE);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG_V(ERROR, TAG, "Add arraylist failed[Err code: %d]", res);
+ return res;
+ }
+ }
+ }
+ break;
}
// start selected interface adapter
- CAStartAdapter((CAConnectivityType_t)ConnectivityType);
+ res = CAStartAdapter((CAConnectivityType_t)connectivityType);
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_STATUS_OK;
+ return res;
}
-CAResult_t CARemoveNetworkType(uint32_t ConnectivityType)
+CAResult_t CARemoveNetworkType(CAConnectivityType_t connectivityType)
{
OIC_LOG(DEBUG, TAG, "IN");
- uint8_t index;
- CAConnectivityType_t connType;
- if (gSelectedNetworkList == NULL)
+
+ if (g_selectedNetworkList == NULL)
{
OIC_LOG(DEBUG, TAG, "Selected network not found");
return CA_STATUS_FAILED;
}
- void *ptrType = NULL;
- for (index = 0; index < u_arraylist_length(gSelectedNetworkList); index++)
+ uint8_t index;
+ for (index = 0; index < u_arraylist_length(g_selectedNetworkList); index++)
{
- ptrType = u_arraylist_get(gSelectedNetworkList, index);
+ void* ptrType = u_arraylist_get(g_selectedNetworkList, index);
if (NULL == ptrType)
{
- OIC_LOG(ERROR, TAG, "error");
- return CA_STATUS_FAILED;
+ continue;
}
- connType = *(CAConnectivityType_t *) ptrType;
- if (ConnectivityType == connType)
+ CAConnectivityType_t connType = *(CAConnectivityType_t *) ptrType;
+
+ if (connectivityType == connType)
{
- switch (ConnectivityType)
+ switch (connectivityType)
{
case CA_ETHERNET:
#else
OIC_LOG(DEBUG, TAG, "Remove network type(ETHERNET)");
- u_arraylist_remove(gSelectedNetworkList, index);
+ u_arraylist_remove(g_selectedNetworkList, index);
#endif /* ETHERNET_ADAPTER */
break;
return CA_NOT_SUPPORTED;
#else
OIC_LOG(DEBUG, TAG, "Remove network type(WIFI)");
- u_arraylist_remove(gSelectedNetworkList, index);
+ u_arraylist_remove(g_selectedNetworkList, index);
#endif /* WIFI_ADAPTER */
break;
return CA_NOT_SUPPORTED;
#else
OIC_LOG(DEBUG, TAG, "Remove network type(EDR)");
- u_arraylist_remove(gSelectedNetworkList, index);
+ u_arraylist_remove(g_selectedNetworkList, index);
#endif /* EDR_ADAPTER */
break;
return CA_NOT_SUPPORTED;
#else
OIC_LOG(DEBUG, TAG, "Remove network type(LE)");
- u_arraylist_remove(gSelectedNetworkList, index);
+ u_arraylist_remove(g_selectedNetworkList, index);
#endif /* LE_ADAPTER */
break;
u_arraylist_t *CAGetSelectedNetworkList()
{
- return gSelectedNetworkList;
+ return g_selectedNetworkList;
}
CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size)
{
+ OIC_LOG(DEBUG, TAG, "get network information.");
+
+ if (info == NULL || size == NULL)
+ {
+ OIC_LOG(DEBUG, TAG, "Input parameter is invalid value");
+
+ return CA_STATUS_INVALID_PARAM;
+ }
+
return CAGetNetworkInfo(info, size);
}
CAResult_t CATerminateNetworkType()
{
OIC_LOG(DEBUG, TAG, "CATerminateNetworkType()");
- if(gSelectedNetworkList != NULL)
+ if(g_selectedNetworkList != NULL)
{
- u_arraylist_free(&gSelectedNetworkList);
+ u_arraylist_free(&g_selectedNetworkList);
}
return CA_STATUS_OK;
}
+
#include <stdio.h>
#include <stdlib.h>
-#include <stdbool.h>
#include <string.h>
#include <time.h>
#define TAG "CA"
-#define CA_FLAGS_BLOCK 0x01
#define CA_BUFSIZE 128
-#define CA_COAP_MESSAGE_CON 0
+#define CA_PDU_MIN_SIZE 4
-#define CA_RESPONSE_CLASS(C) (((C) >> 5)*100)
-#define CA_RESPONSE_CODE(C) (CA_RESPONSE_CLASS(C) + (C - COAP_RESPONSE_CODE(CA_RESPONSE_CLASS(C))))
+static const char COAP_HEADER[] = "coap://[::]/";
+static uint32_t SEED = 0;
-static int32_t SEED = 0;
-
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo, char *outUri)
+void CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo, char *outUri,
+ uint32_t buflen)
{
OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu IN");
if (NULL == pdu)
- return 0;
+ {
+ return;
+ }
uint32_t code = CA_NOT_FOUND;
- CAGetRequestPDUInfo(pdu, &code, &(outReqInfo->info), outUri);
+ CAGetInfoFromPDU(pdu, &code, &(outReqInfo->info), outUri, buflen);
outReqInfo->method = code;
OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu OUT");
- return 1;
}
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo, char *outUri)
+void CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo, char *outUri,
+ uint32_t buflen)
{
OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu IN");
if (NULL == pdu)
- return 0;
+ {
+ return;
+ }
uint32_t code = CA_NOT_FOUND;
- CAGetRequestPDUInfo(pdu, &code, &(outResInfo->info), outUri);
+ CAGetInfoFromPDU(pdu, &code, &(outResInfo->info), outUri, buflen);
outResInfo->result = code;
OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu OUT");
- return 1;
}
coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info)
{
OIC_LOG(DEBUG, TAG, "CAGeneratePdu IN");
- coap_pdu_t *pdu;
- char *coapUri = NULL;
- uint32_t coapHeaderLength = 12;
- uint32_t length;
- coap_list_t *optlist = NULL;
-
- if (CA_EMPTY == code)
+ if (NULL == uri)
{
- if (!(pdu = CACreatePDUforRSTandACK((code_t) code, info)))
- {
- return NULL;
- }
+ return NULL;
}
- else
- {
- if (NULL == uri)
- return NULL;
- length = strlen(uri);
- if (CA_MAX_URI_LENGTH < length)
- {
- OIC_LOG(DEBUG, TAG, "check URI length..");
- return NULL;
- }
+ uint32_t length = strlen(uri);
+ if (CA_MAX_URI_LENGTH < length)
+ {
+ OIC_LOG(ERROR, TAG, "check URI length..");
+ return NULL;
+ }
- uint32_t uriLength = length + coapHeaderLength + 1;
- coapUri = (char *) OICMalloc(uriLength);
- if (NULL == coapUri)
- {
- OIC_LOG(DEBUG, TAG, "CAGeneratePdu, Memory allocation failed !");
- return NULL;
- }
- memset(coapUri, 0, uriLength);
+ uint32_t uriLength = length + sizeof(COAP_HEADER);
+ char *coapUri = NULL;
+ coapUri = (char *) OICCalloc(1, uriLength * sizeof(char));
+ if (NULL == coapUri)
+ {
+ OIC_LOG(ERROR, TAG, "CAGeneratePdu, Memory allocation failed !");
+ return NULL;
+ }
- if (NULL != coapUri)
- {
- strcat(coapUri, "coap://[::]/");
- strcat(coapUri, uri);
+ coap_list_t *optlist = NULL;
+ if (NULL != coapUri)
+ {
+ strcat(coapUri, COAP_HEADER);
+ strcat(coapUri, uri);
- // parsing options in URI
- CAParseURI(coapUri, &optlist);
- OICFree(coapUri);
- coapUri = NULL;
+ // parsing options in URI
+ CAParseURI(coapUri, &optlist);
+ OICFree(coapUri);
+ coapUri = NULL;
- // parsing options in HeadOption
- CAParseHeadOption(code, info, &optlist);
- }
+ // parsing options in HeadOption
+ CAParseHeadOption(code, info, &optlist);
+ }
- if (NULL != info.payload) // payload is include in request / response
- {
- if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload, info)))
- return NULL;
- }
- else // payload is not include in request / response
- {
- if (!(pdu = CACreatePDUforRequest((code_t) code, optlist, info)))
- return NULL;
- }
- // free option list
- coap_delete_list(optlist);
+ coap_pdu_t *pdu;
+ if (!(pdu = CAGeneratePduImpl((code_t) code, optlist, info, info.payload)))
+ {
+ return NULL;
}
+ // free option list
+ coap_delete_list(optlist);
+
// pdu print method : coap_show_pdu(pdu);
OIC_LOG(DEBUG, TAG, "CAGeneratePdu OUT");
return pdu;
OIC_LOG(DEBUG, TAG, "CAParsePDU IN");
coap_pdu_t *outpdu = coap_new_pdu();
- coap_pdu_parse((unsigned char *) data, length, outpdu);
- (*outCode) = (uint32_t) CA_RESPONSE_CODE(outpdu->hdr->code);
- OIC_LOG(DEBUG, TAG, "CAParsePDU OUT");
+ if (0 >= coap_pdu_parse((unsigned char *) data, length, outpdu))
+ {
+ OIC_LOG(ERROR, TAG, "coap_pdu_parse failed");
+ coap_delete_pdu(outpdu);
+ return NULL;
+ }
+
+ if (outCode)
+ {
+ (*outCode) = (uint32_t) outpdu->hdr->code;
+ }OIC_LOG(DEBUG, TAG, "CAParsePDU OUT");
return outpdu;
}
-coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options,
- const char *payload, const CAInfo_t info)
+coap_pdu_t *CAGeneratePduImpl(const code_t code, coap_list_t *options, const CAInfo_t info,
+ const char *payload)
{
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload IN");
-
- coap_pdu_t *pdu;
- coap_list_t *opt;
-
- uint32_t CAFlags = 0;
- coap_block_t
- CABlock =
- { .num = 0, .m = 0, .szx = 6};
+ OIC_LOG(DEBUG, TAG, "CAGeneratePduImpl IN");
- if (!(pdu = coap_new_pdu()))
+ coap_pdu_t *pdu = coap_new_pdu();
+ if (!pdu)
+ {
+ OIC_LOG(ERROR, TAG, "Out of memory");
return NULL;
+ }
- unsigned short message_id;
-
- if (info.messageId == 0)
+ OIC_LOG_V(DEBUG, TAG, "messageId is %d", info.messageId);
+ if (CA_MSG_ACKNOWLEDGE == info.type || CA_MSG_RESET == info.type)
{
- /* initialize message id */
- prng((unsigned char *) &message_id, sizeof(unsigned short));
- ++message_id;
-
- OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);
+ pdu->hdr->id = htons(info.messageId);
}
else
{
- /* use saved message id */
- message_id = info.messageId;
- }
-
- pdu->hdr->type = info.type;
- pdu->hdr->id = htons(message_id);
- pdu->hdr->code = COAP_RESPONSE_CODE(code);
-
- if (info.token)
- {
- pdu->hdr->token_length = CA_MAX_TOKEN_LEN;
- if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))
+ uint16_t message_id;
+ if (info.messageId == 0)
{
- OIC_LOG(DEBUG, TAG, "cannot add token to request");
- }
- }
- for (opt = options; opt; opt = opt->next)
- {
- OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
- COAP_OPTION_DATA(*(coap_option *) opt->data));
- coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
- COAP_OPTION_LENGTH(*(coap_option *) opt->data),
- COAP_OPTION_DATA(*(coap_option *) opt->data));
- }
+ /* initialize message id */
+ prng((uint8_t * ) &message_id, sizeof(uint16_t));
- if (NULL != payload)
- {
- uint32_t len = strlen(payload);
- if ((CAFlags & CA_FLAGS_BLOCK) == 0)
- {
- OIC_LOG_V(DEBUG, TAG, "coap_add_data, payload: %s", payload);
- coap_add_data(pdu, len, (const unsigned char *) payload);
+ OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);
}
else
{
- OIC_LOG_V(DEBUG, TAG, "coap_add_block, payload: %s", payload);
- coap_add_block(pdu, len, (const unsigned char *) payload, CABlock.num, CABlock.szx);
+ /* use saved message id */
+ message_id = info.messageId;
}
+ pdu->hdr->id = htons(message_id);
}
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload OUT");
- return pdu;
-}
-
-coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options, const CAInfo_t info)
-{
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest IN");
-
- coap_pdu_t *pdu;
- coap_list_t *opt;
-
- if (!(pdu = coap_new_pdu()))
- {
- OIC_LOG(DEBUG, TAG, "Out of memory");
- return NULL;
- }
-
- unsigned short message_id;
-
- if (info.messageId == 0)
- {
- /* initialize message id */
- prng((unsigned char *) &message_id, sizeof(unsigned short));
- ++message_id;
-
- OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);
- }
- else
- {
- /* use saved message id */
- message_id = info.messageId;
- }
-
pdu->hdr->type = info.type;
- pdu->hdr->id = htons(message_id);
pdu->hdr->code = COAP_RESPONSE_CODE(code);
- OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, strlen(info.token));
- pdu->hdr->token_length = CA_MAX_TOKEN_LEN;
-
- if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))
+ if (info.token)
{
- OIC_LOG(DEBUG, TAG, "cannot add token to request");
- }
+ uint32_t tokenLength = strlen(info.token);
+ OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, tokenLength);
- for (opt = options; opt; opt = opt->next)
- {
- coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
- COAP_OPTION_LENGTH(*(coap_option *) opt->data),
- COAP_OPTION_DATA(*(coap_option *) opt->data));
+ int32_t ret = coap_add_token(pdu, tokenLength, (uint8_t *) info.token);
+ if (0 == ret)
+ {
+ OIC_LOG(DEBUG, TAG, "cannot add token to request");
+ }
}
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest OUT");
- return pdu;
-}
-
-coap_pdu_t *CACreatePDUforRSTandACK(const code_t code, const CAInfo_t info)
-{
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRSTandACK IN");
-
- coap_pdu_t *pdu;
- if (!(pdu = coap_new_pdu()))
+ if (options)
{
- OIC_LOG(DEBUG, TAG, "Out of memory");
- return NULL;
+ coap_list_t *opt;
+ for (opt = options; opt; opt = opt->next)
+ {
+ OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
+ COAP_OPTION_DATA(*(coap_option *) opt->data));
+ coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option * ) opt->data),
+ COAP_OPTION_LENGTH(*(coap_option * ) opt->data),
+ COAP_OPTION_DATA(*(coap_option * ) opt->data));
+ }
}
- unsigned short message_id;
-
- if (info.messageId == 0)
- {
- /* initialize message id */
- prng((unsigned char *) &message_id, sizeof(unsigned short));
- ++message_id;
-
- OIC_LOG_V(DEBUG, TAG, "generate the message id(%d)", message_id);
- }
- else
+ if (NULL != payload)
{
- /* use saved message id */
- message_id = info.messageId;
+ uint32_t len = strlen(payload);
+ OIC_LOG_V(DEBUG, TAG, "coap_add_data, payload: %s", payload);
+ coap_add_data(pdu, len, (const uint8_t *) payload);
}
- pdu->hdr->type = info.type;
- pdu->hdr->id = htons(message_id);
- pdu->hdr->code = COAP_RESPONSE_CODE(code);
-
- OIC_LOG(DEBUG, TAG, "CACreatePDUforRSTandACK OUT");
+ OIC_LOG(DEBUG, TAG, "CAGeneratePduImpl OUT");
return pdu;
}
void CAParseURI(const char *uriInfo, coap_list_t **optlist)
{
- OIC_LOG(DEBUG, TAG, "CAParseURI IN");
-
- unsigned char portbuf[2];
- unsigned char _buf[CA_BUFSIZE];
- unsigned char *buf = _buf;
- coap_uri_t uri;
- size_t buflen;
- uint32_t res;
-
- OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
+ OIC_LOG(DEBUG, TAG, "CAParseURI IN");OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
/* split arg into Uri-* options */
+ coap_uri_t uri;
coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
+ unsigned char portbuf[2];
if (uri.port != COAP_DEFAULT_PORT)
{
- coap_insert(optlist,
+ coap_insert(
+ optlist,
CACreateNewOptionNode(COAP_OPTION_URI_PORT,
- coap_encode_var_bytes(portbuf, uri.port), portbuf), CAOrderOpts);
+ coap_encode_var_bytes(portbuf, uri.port), portbuf),
+ CAOrderOpts);
}
+ unsigned char uriBuffer[CA_BUFSIZE] =
+ { 0 };
+ unsigned char *pBuf = uriBuffer;
+ uint32_t buflen;
+ int32_t res;
+
if (uri.path.length)
{
buflen = CA_BUFSIZE;
- res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
+ res = coap_split_path(uri.path.s, uri.path.length, pBuf, &buflen);
- while (res--)
+ if (res > 0)
{
- coap_insert(optlist,
- CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf),
- COAP_OPT_VALUE(buf)), CAOrderOpts);
- buf += COAP_OPT_SIZE(buf);
+ uint32_t prevIdx = 0;
+ while (res--)
+ {
+ coap_insert(
+ optlist,
+ CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(pBuf),
+ COAP_OPT_VALUE(pBuf)),
+ CAOrderOpts);
+
+ uint32_t optSize = COAP_OPT_SIZE(pBuf);
+ uint32_t nextIdx = prevIdx + optSize;
+ if (nextIdx < buflen)
+ {
+ pBuf += optSize;
+ prevIdx += nextIdx;
+ }
+ }
}
}
if (uri.query.length)
{
buflen = CA_BUFSIZE;
- buf = _buf;
- res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);
+ pBuf = uriBuffer;
+ res = coap_split_query(uri.query.s, uri.query.length, pBuf, &buflen);
- while (res--)
+ if (res > 0)
{
- coap_insert(optlist,
- CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf),
- COAP_OPT_VALUE(buf)), CAOrderOpts);
-
- buf += COAP_OPT_SIZE(buf);
+ uint32_t prevIdx = 0;
+ while (res--)
+ {
+ coap_insert(
+ optlist,
+ CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(pBuf),
+ COAP_OPT_VALUE(pBuf)),
+ CAOrderOpts);
+
+ uint32_t optSize = COAP_OPT_SIZE(pBuf);
+ uint32_t nextIdx = prevIdx + optSize;
+ if (nextIdx < buflen)
+ {
+ pBuf += optSize;
+ prevIdx += nextIdx;
+ }
+ }
}
}
+
OIC_LOG(DEBUG, TAG, "CAParseURI OUT");
}
void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist)
{
OIC_LOG(DEBUG, TAG, "CAParseHeadOption IN");
+
OIC_LOG_V(DEBUG, TAG, "start parse Head Option : %d", info.numOptions);
uint32_t i;
}
else
{
- if (info.options[i].optionData && info.options[i].optionLength > 0)
- {
- OIC_LOG_V(DEBUG, TAG, "Head Option ID: %d", id);
- OIC_LOG_V(DEBUG, TAG, "Head Option data: %s", info.options[i].optionData);
- OIC_LOG_V(DEBUG, TAG, "Head Option length: %d", info.options[i].optionLength);
- coap_insert(optlist,
- CACreateNewOptionNode(id, info.options[i].optionLength,
- info.options[i].optionData), CAOrderOpts);
- }
+ OIC_LOG_V(DEBUG, TAG, "Head Option ID: %d", info.options[i].optionID);
+
+ OIC_LOG_V(DEBUG, TAG, "Head Option data: %s", info.options[i].optionData);
+
+ OIC_LOG_V(DEBUG, TAG, "Head Option length: %d", info.options[i].optionLength);
+
+ coap_insert(
+ optlist,
+ CACreateNewOptionNode(info.options[i].optionID, info.options[i].optionLength,
+ info.options[i].optionData),
+ CAOrderOpts);
}
}
+
OIC_LOG(DEBUG, TAG, "CAParseHeadOption OUT");
}
coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length, const uint8_t *data)
{
OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode IN");
- coap_option *option;
- coap_list_t *node;
-
- option = coap_malloc(sizeof(coap_option) + length + 1);
+ coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
if (!option)
{
OIC_LOG(DEBUG, TAG, "Out of memory");
memcpy(COAP_OPTION_DATA(*option), data, length);
/* we can pass NULL here as delete function since option is released automatically */
- node = coap_new_listnode(option, NULL);
+ coap_list_t *node = coap_new_listnode(option, NULL);
if (!node)
{
return a < b ? -1 : 1;
}
- if (COAP_OPTION_KEY(*(coap_option *) a) < COAP_OPTION_KEY(*(coap_option *) b))
+ if (COAP_OPTION_KEY(*(coap_option *)a) < COAP_OPTION_KEY(*(coap_option * )b))
{
return -1;
}
+
OIC_LOG(DEBUG, TAG, "CAOrderOpts OUT");
- return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option *) b);
+ return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option * )b);
}
uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
while ((option = coap_option_next(&opt_iter)))
{
- if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
- {
-
- }
- else
+ if (COAP_OPTION_URI_PATH != opt_iter.type && COAP_OPTION_URI_QUERY != opt_iter.type)
{
count++;
}
}
+
OIC_LOG(DEBUG, TAG, "CAGetOptionCount OUT");
return count;
}
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo, char *outUri)
+void CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo, char *outUri,
+ uint32_t buflen)
{
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo IN");
- char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */
- uint32_t encode = 0;
- coap_opt_iterator_t opt_iter;
- coap_opt_t *option;
- char optionResult[CA_MAX_URI_LENGTH] =
- { 0, };
- uint32_t count = 0, idx = 0;
- uint32_t optionLength = 0;
- uint32_t isfirstsetflag = 0;
- bool isQueryBeingProcessed = false;
+ OIC_LOG(DEBUG, TAG, "CAGetInfoFromPDU IN");
+ coap_opt_iterator_t opt_iter;
coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL);
- memset(optionResult, 0, sizeof(optionResult));
-
// set code
- (*outCode) = (uint32_t) CA_RESPONSE_CODE(pdu->hdr->code);
+ if (outCode)
+ {
+ (*outCode) = (uint32_t) pdu->hdr->code;
+ }
// init HeaderOption list
- count = CAGetOptionCount(opt_iter);
+ uint32_t count = CAGetOptionCount(opt_iter);
- memset(outInfo, 0, sizeof(CAInfo_t));
+ if (!outInfo)
+ {
+ OIC_LOG(ERROR, TAG, "outInfo is null");
+ return;
+ }
+ memset(outInfo, 0, sizeof(*outInfo));
outInfo->numOptions = count;
// set type
outInfo->type = pdu->hdr->type;
if (count > 0)
{
- outInfo->options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * count);
+ outInfo->options = (CAHeaderOption_t *) OICCalloc(count, sizeof(CAHeaderOption_t));
if (outInfo->options == NULL)
{
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");
+ OIC_LOG(DEBUG, TAG, "CAGetInfoFromPDU, Memory allocation failed !");
return;
}
- memset(outInfo->options, 0, sizeof(CAHeaderOption_t) * count);
}
+ char buf[COAP_MAX_PDU_SIZE] =
+ { 0 };
+ coap_opt_t *option;
+ char optionResult[CA_MAX_URI_LENGTH] =
+ { 0 };
+ uint32_t idx = 0;
+ uint32_t optionLength = 0;
+ bool isfirstsetflag = false;
+ bool isQueryBeingProcessed = false;
+
while ((option = coap_option_next(&opt_iter)))
{
-
if (CAGetOptionData((uint8_t *) (COAP_OPT_VALUE(option)), COAP_OPT_LENGTH(option),
- (uint8_t *) buf, sizeof(buf), encode))
+ (uint8_t *) buf, sizeof(buf)))
{
OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
+ uint32_t bufLength = strlen(buf);
if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
{
- if (0 == isfirstsetflag)
+ if (false == isfirstsetflag)
{
- isfirstsetflag = 1;
- memcpy(optionResult + optionLength, "/", 1);
+ isfirstsetflag = true;
+ optionResult[optionLength] = '/';
optionLength++;
- memcpy(optionResult + optionLength, buf, strlen((const char *) buf));
- optionLength += strlen((const char *) buf);
+ memcpy(optionResult + optionLength, buf, bufLength);
+ optionLength += bufLength;
}
else
{
if (COAP_OPTION_URI_PATH == opt_iter.type)
{
- memcpy(optionResult + optionLength, "/", 1);
+ optionResult[optionLength] = '/';
optionLength++;
}
else if (COAP_OPTION_URI_QUERY == opt_iter.type)
{
- // Delimiter between uri and query is '?'
- if (false == isQueryBeingProcessed)
+ if(false == isQueryBeingProcessed)
{
- memcpy(optionResult + optionLength, "?", 1);
+ optionResult[optionLength] = '?';
+ optionLength++;
isQueryBeingProcessed = true;
}
else
{
- // Delimeter for query params is '&'
- memcpy(optionResult + optionLength, "&", 1);
+ optionResult[optionLength] = '&';
+ optionLength++;
}
- optionLength++;
}
- memcpy(optionResult + optionLength, buf, strlen((const char *) buf));
- optionLength += strlen((const char *) buf);
+ memcpy(optionResult + optionLength, buf, bufLength);
+ optionLength += bufLength;
}
}
else
{
if (idx < count)
{
- uint32_t length = (uint32_t) strlen((const char *) buf);
+ uint32_t length = bufLength;
if (length <= CA_MAX_HEADER_OPTION_DATA_LENGTH)
{
if (pdu->hdr->token_length > 0)
{
OIC_LOG(DEBUG, TAG, "inside pdu->hdr->token_length");
- outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN + 1);
+ outInfo->token = (char *) OICMalloc(pdu->hdr->token_length + 1);
if (outInfo->token == NULL)
{
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");
+ OIC_LOG(DEBUG, TAG, "CAGetInfoFromPDU, Memory allocation failed !");
OICFree(outInfo->options);
return;
}
- memset(outInfo->token, 0, CA_MAX_TOKEN_LEN + 1);
- memcpy(outInfo->token, pdu->hdr->token, CA_MAX_TOKEN_LEN);
+ memcpy(outInfo->token, pdu->hdr->token, pdu->hdr->token_length);
+ outInfo->token[pdu->hdr->token_length] = '\0';
}
// set payload data
if (NULL != pdu->data)
{
+ uint32_t payloadLength = strlen((char*) pdu->data);
OIC_LOG(DEBUG, TAG, "inside pdu->data");
- outInfo->payload = (char *) OICMalloc(strlen((const char *) pdu->data) + 1);
+ outInfo->payload = (char *) OICMalloc(payloadLength + 1);
if (outInfo->payload == NULL)
{
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo, Memory allocation failed !");
+ OIC_LOG(DEBUG, TAG, "CAGetInfoFromPDU, Memory allocation failed !");
OICFree(outInfo->options);
OICFree(outInfo->token);
return;
}
- memcpy(outInfo->payload, pdu->data, strlen((const char *) pdu->data) + 1);
+ memcpy(outInfo->payload, pdu->data, payloadLength);
+ outInfo->payload[payloadLength] = '\0';
}
- memcpy(outUri, optionResult, strlen(optionResult));
- OIC_LOG_V(DEBUG, TAG, "made URL : %s\n", optionResult);
- OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo OUT");
-
-}
-
-CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo)
-{
- OIC_LOG(DEBUG, TAG, "IN - CAGetTokenFromPDU");
- if (NULL == pdu_hdr)
+ uint32_t length = strlen(optionResult);
+ OIC_LOG_V(DEBUG, TAG, "made URL length: %d, %d, %d...\n", length, buflen, strlen(outUri));
+ if (buflen >= length)
{
- OIC_LOG(DEBUG, TAG, "pdu_hdr is null");
- return CA_STATUS_FAILED;
- }
- // set token data
- if (pdu_hdr->token_length > 0)
- {
- OIC_LOG(DEBUG, TAG, "inside pdu_hdr->token_length");
- outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN + 1);
- if (outInfo->token == NULL)
- {
- OIC_LOG(DEBUG, TAG, "CAGetTokenFromPDU, Memory allocation failed !");
- return CA_STATUS_FAILED;
- }
- memset(outInfo->token, 0, CA_MAX_TOKEN_LEN + 1);
- memcpy(outInfo->token, pdu_hdr->token, CA_MAX_TOKEN_LEN);
- }
- OIC_LOG(DEBUG, TAG, "OUT - CAGetTokenFromPDU");
-
- return CA_STATUS_OK;
+ memcpy(outUri, optionResult, length);
+ outUri[length] = '\0';
+ OIC_LOG_V(DEBUG, TAG, "made URL : %s, %s\n", optionResult, outUri);
+ }OIC_LOG(DEBUG, TAG, "CAGetInfoFromPDU OUT");
}
CAResult_t CAGenerateTokenInternal(CAToken_t *token)
}
// memory allocation
- char *temp = (char *) OICMalloc(sizeof(char) * (CA_MAX_TOKEN_LEN + 1));
+ char *temp = (char *) OICCalloc(1, (CA_MAX_TOKEN_LEN + 1) * sizeof(char));
if (temp == NULL)
{
OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal, Memory allocation failed !");
return CA_MEMORY_ALLOC_FAILED;
}
- memset(temp, 0, sizeof(char) * (CA_MAX_TOKEN_LEN + 1));
if (SEED == 0)
{
OICFree(temp);
return CA_STATUS_FAILED;
}
- srand(SEED);
+ srandom(SEED);
}
// set random byte
for (index = 0; index < CA_MAX_TOKEN_LEN; index++)
{
// use valid characters
- temp[index] = (rand() % 94 + 33) & 0xFF;
+ temp[index] = (random() % 94 + 33) & 0xFF;
}
temp[index] = '\0';
*token = temp;
OIC_LOG_V(DEBUG, TAG, "generate the token(%s)!!", *token);
+
OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal OUT");
return CA_STATUS_OK;
}
OIC_LOG_V(DEBUG, TAG, "destroy the token(%s)!!", token);
OICFree(token);
+ token = NULL;
}
+
OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal OUT");
}
-void CADeinitialize(CAInfo_t *info)
+void CADestroyInfo(CAInfo_t *info)
{
- OIC_LOG(DEBUG, TAG, "CADeinitialize IN");
+ OIC_LOG(DEBUG, TAG, "CADestroyInfo IN");
if (NULL != info)
{
OICFree(info->payload);
}
}
- OIC_LOG(DEBUG, TAG, "CADeinitialize OUT");
+
+ OIC_LOG(DEBUG, TAG, "OUT");
}
-uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result, uint32_t buflen,
- uint32_t encode_always)
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *option, uint32_t buflen)
{
- const unsigned char hex[] = "0123456789ABCDEF";
- uint32_t cnt = 0;
- assert(data || len == 0);
+ assert(data || 0 == len);
- if (buflen == 0 || len == 0)
+ if (0 == buflen || 0 == len)
+ {
+ OIC_LOG(ERROR, TAG, "buflen or len is not available");
return 0;
+ }
- if (data == NULL)
+ if (NULL == data)
{
+ OIC_LOG(ERROR, TAG, "data not available");
return 0;
}
+ if (NULL == option)
+ {
+ OIC_LOG(ERROR, TAG, "option pointer is null");
+ return 0;
+ }
+
+ uint32_t cnt = 0;
while (len)
{
- if (!encode_always)
+ if (cnt == buflen - 1)
{
- if (cnt == buflen)
- break;
- *result++ = *data;
- ++cnt;
- }
- else
- {
- if (cnt + 4 < buflen)
- {
- *result++ = '\\';
- *result++ = 'x';
- *result++ = hex[(*data & 0xf0) >> 4];
- *result++ = hex[*data & 0x0f];
- cnt += 4;
- }
- else
- break;
+ break;
}
+ *option++ = *data;
+ ++cnt;
++data;
--len;
}
- *result = '\0';
+ *option = '\0';
return cnt;
}
CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
{
// pdu minimum size is 4 byte.
- if (size < 4)
+ if (size < CA_PDU_MIN_SIZE)
+ {
return CA_MSG_NONCONFIRM;
+ }
coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+ if (NULL == hdr)
+ {
+ return CA_MSG_NONCONFIRM;
+ }
return (CAMessageType_t) hdr->type;
}
uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
{
// pdu minimum size is 4 byte.
- if (size < 4)
+ if (size < CA_PDU_MIN_SIZE)
+ {
return 0;
+ }
coap_hdr_t *hdr = (coap_hdr_t *) pdu;
-
- return ntohs(hdr->id);
-}
-
-CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
-{
- // pdu minimum size is 4 byte.
- if (size < 4)
+ if (NULL == hdr)
+ {
return 0;
+ }
- coap_hdr_t *hdr = (coap_hdr_t *) pdu;
-
- return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->code);
+ return ntohs(hdr->id);
}
#include <stdio.h>
#include <stdlib.h>
-#include <stdbool.h>
#include <string.h>
-
#include "caprotocolmessage_singlethread.h"
#include "logger.h"
#include "oic_malloc.h"
#define TAG "CPM"
-#define CA_FLAGS_BLOCK 0x01
#define CA_BUFSIZE 128
-#define CA_COAP_MESSAGE_CON 0
+#define CA_PDU_MIN_SIZE 4
+static const char COAP_HEADER[] = "coap://[::]/";
-#define CA_RESPONSE_CLASS(C) (((C) >> 5)*100)
-#define CA_RESPONSE_CODE(C) (CA_RESPONSE_CLASS(C) + (C - COAP_RESPONSE_CODE(CA_RESPONSE_CLASS(C))))
+static uint32_t SEED = 0;
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,
- char *outUri)
+void CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo,
+ char *outUri, uint32_t buflen)
{
OIC_LOG(DEBUG, TAG, "IN");
if (NULL == pdu)
- return 0;
+ {
+ OIC_LOG(ERROR, TAG, "pdu NULL");
+ return;
+ }
uint32_t code = CA_NOT_FOUND;
- CAGetRequestPDUInfo(pdu, &code, &(outReqInfo->info), outUri);
+ CAGetInfoFromPDU(pdu, &code, &(outReqInfo->info), outUri, buflen);
outReqInfo->method = code;
OIC_LOG(DEBUG, TAG, "OUT");
- return 1;
}
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
- char *outUri)
+void CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
+ char *outUri, uint32_t buflen)
{
OIC_LOG(DEBUG, TAG, "IN");
if (NULL == pdu)
- return 0;
+ {
+ OIC_LOG(ERROR, TAG, "pdu NULL");
+ return;
+ }
uint32_t code = CA_NOT_FOUND;
- CAGetRequestPDUInfo(pdu, &code, &(outResInfo->info), outUri);
+ CAGetInfoFromPDU(pdu, &code, &(outResInfo->info), outUri, buflen);
outResInfo->result = code;
OIC_LOG(DEBUG, TAG, "OUT");
- return 1;
}
-coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info)
+coap_pdu_t *CAGeneratePdu(const char *uri, uint32_t code, const CAInfo_t info)
{
OIC_LOG(DEBUG, TAG, "IN");
- coap_pdu_t *pdu;
- char *coapUri = NULL;
- uint32_t coapHeaderLength = 12;
- uint32_t length;
- coap_list_t *optlist = NULL;
-
- if(CA_EMPTY == code)
+ if (NULL == uri)
{
- if (!(pdu = CACreatePDUforRSTandACK((code_t) code, info)))
- {
- return NULL;
- }
+ OIC_LOG(ERROR, TAG, "uri NULL");
+ return NULL;
}
- else
+
+ uint32_t length = strlen(uri);
+ if (CA_MAX_URI_LENGTH < length)
{
- if (NULL == uri)
- return NULL;
+ OIC_LOG(ERROR, TAG, "URI len err");
+ return NULL;
+ }
- length = strlen(uri);
- if (CA_MAX_URI_LENGTH < length)
- {
- OIC_LOG(DEBUG, TAG, "URI len err");
- return NULL;
- }
+ uint32_t uriLength = length + sizeof(COAP_HEADER);
+ char *coapUri = (char *) OICCalloc(uriLength, sizeof(char));
+ if (NULL == coapUri)
+ {
+ OIC_LOG(ERROR, TAG, "error");
+ return NULL;
+ }
- uint32_t uriLength = length + coapHeaderLength + 1;
- coapUri = (char *) OICMalloc(uriLength);
- if (NULL == coapUri)
- {
- OIC_LOG(ERROR, TAG, "error");
- return NULL;
- }
- memset(coapUri, 0, uriLength);
+ strcat(coapUri, COAP_HEADER);
+ strcat(coapUri, uri);
- if (NULL != coapUri)
- {
- memcpy(coapUri, "coap://[::]/", coapHeaderLength);
- memcpy(coapUri + coapHeaderLength, uri, length);
+ // parsing options in URI
+ coap_list_t *optlist = NULL;
+ CAParseURI(coapUri, &optlist);
+ OICFree(coapUri);
- // parsing options in URI
- CAParseURI(coapUri, &optlist);
- OICFree(coapUri);
- coapUri = NULL;
+ // parsing options in HeadOption
+ CAParseHeadOption(code, info, &optlist);
- // parsing options in HeadOption
- CAParseHeadOption(code, info, &optlist);
- }
-
- if (NULL != info.payload) // payload is include in request / response
- {
- if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload, info)))
- return NULL;
- }
- else // payload is not include in request / response
- {
- if (!(pdu = CACreatePDUforRequest((code_t) code, optlist, info)))
- return NULL;
- }
- // free option list
- coap_delete_list(optlist);
+ coap_pdu_t *pdu = CAGeneratePduImpl((code_t) code, optlist, info, info.payload);
+ if (NULL == pdu)
+ {
+ OIC_LOG(ERROR, TAG, "pdu NULL");
+ return NULL;
}
+ // free option list
+ coap_delete_list(optlist);
+
// pdu print method : coap_show_pdu(pdu);
OIC_LOG(DEBUG, TAG, "OUT");
return pdu;
OIC_LOG(DEBUG, TAG, "IN");
coap_pdu_t *outpdu = coap_new_pdu();
- coap_pdu_parse((unsigned char *) data, length, outpdu);
- (*outCode) = (uint32_t) CA_RESPONSE_CODE(outpdu->hdr->code);
- OIC_LOG(DEBUG, TAG, "OUT");
- return outpdu;
-}
-
-coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options,
- const char *payload, const CAInfo_t info)
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- coap_pdu_t *pdu;
- coap_list_t *opt;
-
- uint32_t CAFlags = 0;
- coap_block_t CABlock =
- { .num = 0, .m = 0, .szx = 6 };
-
- if (!(pdu = coap_new_pdu()))
- return NULL;
-
- unsigned short message_id;
-
- if (info.messageId == 0)
- {
- /* initialize message id */
- prng((unsigned char * )&message_id, sizeof(unsigned short));
- ++message_id;
-
- OIC_LOG_V(DEBUG, TAG, "gen msg id=%d", message_id);
- }
- else
+ if (0 >= coap_pdu_parse((unsigned char *) data, length, outpdu))
{
- /* use saved message id */
- message_id = info.messageId;
- }
-
- pdu->hdr->type = info.type;
- pdu->hdr->id = htons(message_id);
- pdu->hdr->code = COAP_RESPONSE_CODE(code);
-
- if (info.token)
- {
- pdu->hdr->token_length = CA_MAX_TOKEN_LEN;
- if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))
- {
- OIC_LOG(DEBUG, TAG, "cant add token");
- }
- }
- for (opt = options; opt; opt = opt->next)
- {
- OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.", COAP_OPTION_DATA(*(coap_option * )opt->data));
- coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option * )opt->data),
- COAP_OPTION_LENGTH(*(coap_option * )opt->data),
- COAP_OPTION_DATA(*(coap_option * )opt->data));
+ OIC_LOG(ERROR, TAG, "pdu parse failed");
+ coap_delete_pdu(outpdu);
+ return NULL;
}
- if (NULL != payload)
+ if (outCode)
{
- uint32_t len = strlen(payload);
- if ((CAFlags & CA_FLAGS_BLOCK) == 0)
- {
- OIC_LOG_V(DEBUG, TAG, "add data,payload:%s", payload);
- coap_add_data(pdu, len, (const unsigned char *) payload);
- }
-
-
+ (*outCode) = (uint32_t) outpdu->hdr->code;
}
OIC_LOG(DEBUG, TAG, "OUT");
- return pdu;
+ return outpdu;
}
-coap_pdu_t *CACreatePDUforRequest(const code_t code, coap_list_t *options,
- const CAInfo_t info)
+coap_pdu_t *CAGeneratePduImpl(code_t code, coap_list_t *options,
+ const CAInfo_t info, const char *payload)
{
OIC_LOG(DEBUG, TAG, "IN");
- coap_pdu_t *pdu;
- coap_list_t *opt;
+ coap_pdu_t *pdu = coap_new_pdu();
- if (!(pdu = coap_new_pdu()))
+ if (NULL == pdu)
{
- OIC_LOG(ERROR, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc failed");
return NULL;
}
- unsigned short message_id;
-
- if (info.messageId == 0)
+ OIC_LOG_V(DEBUG, TAG, "msgId: %d", info.messageId);
+ if(CA_MSG_ACKNOWLEDGE == info.type || CA_MSG_RESET == info.type)
{
- /* initialize message id */
- prng((unsigned char * )&message_id, sizeof(unsigned short));
- ++message_id;
-
- OIC_LOG_V(DEBUG, TAG, "gen msg id(%d)", message_id);
+ pdu->hdr->id = htons(info.messageId);
}
else
{
- /* use saved message id */
- message_id = info.messageId;
+ uint16_t message_id;
+ if (info.messageId == 0)
+ {
+ /* initialize message id */
+ prng((unsigned char * )&message_id, sizeof(unsigned short));
+ OIC_LOG_V(DEBUG, TAG, "gen msg id=%d", message_id);
+ }
+ else
+ {
+ /* use saved message id */
+ message_id = info.messageId;
+ }
+ pdu->hdr->id = htons(message_id);
}
-
pdu->hdr->type = info.type;
- pdu->hdr->id = htons(message_id);
pdu->hdr->code = COAP_RESPONSE_CODE(code);
- OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, strlen(info.token));
- pdu->hdr->token_length = CA_MAX_TOKEN_LEN;
-
- if (!coap_add_token(pdu, CA_MAX_TOKEN_LEN, (unsigned char *) info.token))
- {
- OIC_LOG(DEBUG, TAG, "cant add data");
- }
-
- for (opt = options; opt; opt = opt->next)
+ if (info.token)
{
- coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option * )opt->data),
- COAP_OPTION_LENGTH(*(coap_option * )opt->data),
- COAP_OPTION_DATA(*(coap_option * )opt->data));
+ uint32_t tokenLength = strlen(info.token);
+ OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, tokenLength);
+ int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *) info.token);
+ if (0 == ret)
+ {
+ OIC_LOG(DEBUG, TAG, "cant add token");
+ }
}
- OIC_LOG(DEBUG, TAG, "OUT");
- return pdu;
-}
-coap_pdu_t *CACreatePDUforRSTandACK(const code_t code, const CAInfo_t info)
-{
- OIC_LOG(DEBUG, TAG, "IN");
-
- coap_pdu_t *pdu;
-
- if (!(pdu = coap_new_pdu()))
+ if(options)
{
- OIC_LOG(DEBUG, TAG, "error");
- return NULL;
+ coap_list_t *opt;
+ for (opt = options; opt; opt = opt->next)
+ {
+ OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
+ COAP_OPTION_DATA(*(coap_option * )opt->data));
+ coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option * )opt->data),
+ COAP_OPTION_LENGTH(*(coap_option * )opt->data),
+ COAP_OPTION_DATA(*(coap_option * )opt->data));
+ }
}
- unsigned short message_id;
-
- if (info.messageId == 0)
- {
- /* initialize message id */
- prng((unsigned char * )&message_id, sizeof(unsigned short));
- ++message_id;
-
- OIC_LOG_V(DEBUG, TAG, "msg id(%d)", message_id);
- }
- else
+ if (NULL != payload)
{
- /* use saved message id */
- message_id = info.messageId;
+ uint32_t len = strlen(payload);
+ OIC_LOG_V(DEBUG, TAG, "add data,payload:%s", payload);
+ coap_add_data(pdu, len, (const unsigned char *) payload);
}
- pdu->hdr->type = info.type;
- pdu->hdr->id = htons(message_id);
- pdu->hdr->code = COAP_RESPONSE_CODE(code);
-
OIC_LOG(DEBUG, TAG, "OUT");
return pdu;
}
{
OIC_LOG(DEBUG, TAG, "IN");
- unsigned char portbuf[2];
- unsigned char _buf[CA_BUFSIZE];
- unsigned char *buf = _buf;
- coap_uri_t uri;
- size_t buflen;
- uint32_t res;
-
OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo);
/* split arg into Uri-* options */
+ coap_uri_t uri;
coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri);
if (uri.port != COAP_DEFAULT_PORT)
{
+ unsigned char portbuf[2] = {0};
coap_insert(optlist,
CACreateNewOptionNode(COAP_OPTION_URI_PORT,
coap_encode_var_bytes(portbuf, uri.port), portbuf),
- CAOrderOpts);
+ CAOrderOpts);
}
+ unsigned char uriBuffer[CA_BUFSIZE] = {0};
+ unsigned char *tempBuf = uriBuffer;
if (uri.path.length)
{
- buflen = CA_BUFSIZE;
- res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen);
+ uint32_t buflen = CA_BUFSIZE;
+ int32_t res = coap_split_path(uri.path.s, uri.path.length, tempBuf, &buflen);
- while (res--)
+ if (res > 0)
{
- coap_insert(optlist,
- CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf),
- COAP_OPT_VALUE(buf)), CAOrderOpts);
- buf += COAP_OPT_SIZE(buf);
+ uint32_t prevIdx = 0;
+ while (res--)
+ {
+ coap_insert(optlist,
+ CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(tempBuf),
+ COAP_OPT_VALUE(tempBuf)), CAOrderOpts);
+ uint32_t optSize = COAP_OPT_SIZE(tempBuf);
+ uint32_t nextIdx = prevIdx + optSize;
+ if (nextIdx < buflen)
+ {
+ tempBuf += optSize;
+ prevIdx += nextIdx;
+ }
+ }
}
}
if (uri.query.length)
{
- buflen = CA_BUFSIZE;
- buf = _buf;
- res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen);
-
- while (res--)
+ size_t buflen = CA_BUFSIZE;
+ tempBuf = uriBuffer;
+ int32_t res = coap_split_query(uri.query.s, uri.query.length, tempBuf, &buflen);
+ if (res > 0)
{
- coap_insert(optlist,
- CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf),
- COAP_OPT_VALUE(buf)), CAOrderOpts);
+ uint32_t prevIdx = 0;
+ while (res--)
+ {
+ coap_insert(optlist,
+ CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(tempBuf),
+ COAP_OPT_VALUE(tempBuf)), CAOrderOpts);
- buf += COAP_OPT_SIZE(buf);
+ uint32_t optSize = COAP_OPT_SIZE(tempBuf);
+ uint32_t nextIdx = prevIdx + optSize;
+ if (nextIdx < buflen)
+ {
+ tempBuf += optSize;
+ prevIdx += nextIdx;
+ }
+ }
}
}
+
OIC_LOG(DEBUG, TAG, "OUT");
}
-void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist)
+void CAParseHeadOption(uint32_t code, const CAInfo_t info, coap_list_t **optlist)
{
OIC_LOG(DEBUG, TAG, "IN");
OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info.numOptions);
info.options[i].optionData), CAOrderOpts);
}
}
+
OIC_LOG(DEBUG, TAG, "OUT");
}
-coap_list_t *CACreateNewOptionNode(const uint16_t key, const uint32_t length,
+coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length,
const uint8_t *data)
{
OIC_LOG(DEBUG, TAG, "IN");
- coap_option *option;
- coap_list_t *node;
- option = coap_malloc(sizeof(coap_option) + length);
+ coap_option *option = coap_malloc(sizeof(coap_option) + length + 1);
if (!option)
{
- OIC_LOG(ERROR, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc failed");
return NULL;
}
- memset(option, 0, sizeof(coap_option) + length);
+ memset(option, 0, sizeof(coap_option) + length + 1);
COAP_OPTION_KEY(*option) = key;
COAP_OPTION_LENGTH(*option) = length;
memcpy(COAP_OPTION_DATA(*option), data, length);
/* we can pass NULL here as delete function since option is released automatically */
- node = coap_new_listnode(option, NULL);
+ coap_list_t *node = coap_new_listnode(option, NULL);
if (!node)
{
{
return -1;
}
+
OIC_LOG(DEBUG, TAG, "OUT");
return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option * )b);
}
while ((option = coap_option_next(&opt_iter)))
{
- if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
- {
-
- }
- else
+ if (COAP_OPTION_URI_PATH != opt_iter.type && COAP_OPTION_URI_QUERY != opt_iter.type)
{
count++;
}
}
+
OIC_LOG(DEBUG, TAG, "OUT");
return count;
}
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
- char *outUri)
+void CAGetInfoFromPDU(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo,
+ char *outUri, uint32_t buflen)
{
OIC_LOG(DEBUG, TAG, "IN");
- char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */
- uint32_t encode = 0;
- coap_opt_iterator_t opt_iter;
- coap_opt_t *option;
- char optionResult[CA_MAX_URI_LENGTH] =
- { 0, };
- uint32_t count = 0, idx = 0;
- uint32_t optionLength = 0;
- uint32_t isfirstsetflag = 0;
- bool isQueryBeingProcessed = false;
+ coap_opt_iterator_t opt_iter;
coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL);
- memset(optionResult, 0, sizeof(optionResult));
-
// set code
- (*outCode) = (uint32_t) CA_RESPONSE_CODE(pdu->hdr->code);
+ if (outCode)
+ {
+ (*outCode) = (uint32_t) pdu->hdr->code;
+ }
// init HeaderOption list
- count = CAGetOptionCount(opt_iter);
+ uint32_t count = CAGetOptionCount(opt_iter);
- memset(outInfo, 0, sizeof(CAInfo_t));
+ if (!outInfo)
+ {
+ OIC_LOG(ERROR, TAG, "outInfo is NULL");
+ return;
+ }
+ memset(outInfo, 0, sizeof(*outInfo));
outInfo->numOptions = count;
+
// set type
outInfo->type = pdu->hdr->type;
if (count > 0)
{
- outInfo->options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * count);
+ outInfo->options = (CAHeaderOption_t *) OICCalloc(count, sizeof(CAHeaderOption_t));
if (outInfo->options == NULL)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc failed");
return;
}
- memset(outInfo->options, 0, sizeof(CAHeaderOption_t) * count);
}
+ coap_opt_t *option;
+ char optionResult[CA_MAX_URI_LENGTH] = {0,};
+ uint32_t idx = 0;
+ uint32_t optionLength = 0;
+ bool isfirstsetflag = false;
+ bool isQueryBeingProcessed = false;
+
while ((option = coap_option_next(&opt_iter)))
{
+ char buf[COAP_MAX_PDU_SIZE] = {0}; /* need some space for output creation */
if (CAGetOptionData((uint8_t *)(COAP_OPT_VALUE(option)),
- COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf),
- encode))
+ COAP_OPT_LENGTH(option), (uint8_t *)buf, sizeof(buf)))
{
OIC_LOG_V(DEBUG, TAG, "COAP URI element : %s", buf);
+ uint32_t bufLength = strlen((const char *) buf);
if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
{
- if (0 == isfirstsetflag)
+ if (false == isfirstsetflag)
{
- isfirstsetflag = 1;
- memcpy(optionResult + optionLength, "/", 1);
+ isfirstsetflag = true;
+ optionResult[optionLength] = '/';
optionLength++;
- memcpy(optionResult + optionLength, buf, strlen((const char *) buf));
- optionLength += strlen((const char *) buf);
+ memcpy(optionResult + optionLength, buf, bufLength);
+ optionLength += bufLength;
}
else
{
if (COAP_OPTION_URI_PATH == opt_iter.type)
{
- memcpy(optionResult + optionLength, "/", 1);
+ optionResult[optionLength] = '/';
optionLength++;
}
else if (COAP_OPTION_URI_QUERY == opt_iter.type)
{
- // Delimiter between uri and query is '?'
- if (false == isQueryBeingProcessed)
+ if(false == isQueryBeingProcessed)
{
- memcpy(optionResult + optionLength, "?", 1);
+ optionResult[optionLength] = '?';
+ optionLength++;
isQueryBeingProcessed = true;
}
else
{
- // Delimeter for query params is '&'
- memcpy(optionResult + optionLength, "&", 1);
+ optionResult[optionLength] = '&';
+ optionLength++;
}
- optionLength++;
}
- memcpy(optionResult + optionLength, buf, strlen((const char *) buf));
- optionLength += strlen((const char *) buf);
+ memcpy(optionResult + optionLength, buf, bufLength);
+ optionLength += bufLength;
}
}
else
{
if (idx < count)
{
- uint32_t length = (uint32_t) strlen((const char *) buf);
+ uint32_t length = bufLength;
if (length <= CA_MAX_HEADER_OPTION_DATA_LENGTH)
{
if (pdu->hdr->token_length > 0)
{
OIC_LOG(DEBUG, TAG, "pdu->hdr->token_length>0");
- outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN + 1);
+ outInfo->token = (char *) OICMalloc(pdu->hdr->token_length + 1);
if (outInfo->token == NULL)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc failed");
OICFree(outInfo->options);
return;
}
- memset(outInfo->token, 0, CA_MAX_TOKEN_LEN + 1);
- memcpy(outInfo->token, pdu->hdr->token, CA_MAX_TOKEN_LEN);
+ memcpy(outInfo->token, pdu->hdr->token, pdu->hdr->token_length);
+ outInfo->token[pdu->hdr->token_length] = '\0';
}
// set payload data
if (NULL != pdu->data)
{
+ uint32_t payloadLength = strlen((const char *) pdu->data) + 1;
OIC_LOG(DEBUG, TAG, "inside pdu->data");
- outInfo->payload = (char *) OICMalloc(strlen((const char *) pdu->data) + 1);
+ outInfo->payload = (char *) OICMalloc(payloadLength + 1);
if (outInfo->payload == NULL)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc failed");
OICFree(outInfo->options);
OICFree(outInfo->token);
return;
}
- memcpy(outInfo->payload, pdu->data, strlen((const char *) pdu->data) + 1);
+ memcpy(outInfo->payload, pdu->data, payloadLength);
+ outInfo->payload[payloadLength] = '\0';
}
-
-
- memcpy(outUri, optionResult, strlen(optionResult));
- OIC_LOG_V(DEBUG, TAG, "made URL:%s\n", optionResult);
- OIC_LOG(DEBUG, TAG, "OUT");
-
-}
-
-CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo)
-{
- OIC_LOG(DEBUG, TAG, "IN");
- if(NULL == pdu_hdr)
+ uint32_t length = strlen(optionResult);
+ OIC_LOG_V(DEBUG, TAG, "made URL length: %d, %d, %d...\n", length, buflen, strlen(outUri));
+ if (buflen >= length)
{
- OIC_LOG(DEBUG, TAG, "error");
- return CA_STATUS_FAILED;
+ memcpy(outUri, optionResult, length);
+ outUri[length] = '\0';
+ OIC_LOG_V(DEBUG, TAG, "made URL:%s\n", optionResult);
}
- // set token data
- if (pdu_hdr->token_length > 0)
- {
- OIC_LOG(DEBUG, TAG, "toklen > 0");
- outInfo->token = (char *) OICMalloc(CA_MAX_TOKEN_LEN + 1);
- if (outInfo->token == NULL)
- {
- OIC_LOG(DEBUG, TAG, "error");
- return CA_STATUS_FAILED;
- }
- memset(outInfo->token, 0, CA_MAX_TOKEN_LEN + 1);
- memcpy(outInfo->token, pdu_hdr->token, CA_MAX_TOKEN_LEN);
- }
- OIC_LOG(DEBUG, TAG, "OUT - CAGetTokenFromPDU");
- return CA_STATUS_OK;
+ OIC_LOG(DEBUG, TAG, "OUT");
}
CAResult_t CAGenerateTokenInternal(CAToken_t *token)
OIC_LOG(DEBUG, TAG, "IN");
if (token == NULL)
{
+ OIC_LOG(ERROR, TAG, "tok null");
return CA_STATUS_FAILED;
}
// memory allocation
- char *temp = (char *) OICMalloc(sizeof(char) * (CA_MAX_TOKEN_LEN + 1));
+ char *temp = (char *) OICCalloc(CA_MAX_TOKEN_LEN + 1, sizeof(char));
if (temp == NULL)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "malloc failed");
return CA_MEMORY_ALLOC_FAILED;
}
- memset(temp, 0, sizeof(char) * (CA_MAX_TOKEN_LEN + 1));
+
+ if (SEED == 0)
+ {
+ SEED = now();
+ if (SEED == -1)
+ {
+ OIC_LOG(DEBUG, TAG, "Failed to Create Seed!");
+ SEED = 0;
+ OICFree(temp);
+ return CA_STATUS_FAILED;
+ }
+ srandom(SEED);
+ }
// set random byte
uint32_t index;
for (index = 0; index < CA_MAX_TOKEN_LEN; index++)
{
- // use valid characters
+ // To create random value 33~126(ASCII code) for valid character
temp[index] = (rand() % 94 + 33) & 0xFF;
}
if (token != NULL)
{
OIC_LOG_V(DEBUG, TAG, "destroy token(%s)!!", token);
-
OICFree(token);
}
+
OIC_LOG(DEBUG, TAG, "OUT");
}
-void CADeinitialize(CAInfo_t *info)
+void CADestroyInfo(CAInfo_t *info)
{
OIC_LOG(DEBUG, TAG, "IN");
OICFree(info->payload);
}
}
+
OIC_LOG(DEBUG, TAG, "OUT");
}
-uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result,
- uint32_t buflen, uint32_t encode_always)
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *option, uint32_t buflen)
{
- const unsigned char hex[] = "0123456789ABCDEF";
- uint32_t cnt = 0;
assert(data || len == 0);
- if (buflen == 0 || len == 0)
+ if (0 == buflen|| 0 == len)
+ {
+ OIC_LOG(ERROR, TAG, "len 0");
+ return 0;
+ }
+
+ if (NULL == data || NULL == option)
+ {
+ OIC_LOG(ERROR, TAG, "data/option NULL");
return 0;
+ }
+ uint32_t cnt = 0;
while (len)
{
- if (!encode_always)
- {
- if (cnt == buflen)
- break;
- *result++ = *data;
- ++cnt;
- }
- else
+ if (cnt == buflen)
{
- if (cnt + 4 < buflen)
- {
- *result++ = '\\';
- *result++ = 'x';
- *result++ = hex[(*data & 0xf0) >> 4];
- *result++ = hex[*data & 0x0f];
- cnt += 4;
- }
- else
- break;
+ break;
}
-
+ *option++ = *data;
+ ++cnt;
++data;
--len;
}
- *result = '\0';
+ *option = '\0';
return cnt;
}
CAMessageType_t CAGetMessageTypeFromPduBinaryData(const void *pdu, uint32_t size)
{
// pdu minimum size is 4 byte.
- if (size < 4)
+ if (size < CA_PDU_MIN_SIZE)
+ {
+ OIC_LOG(DEBUG, TAG, "min size");
return CA_MSG_NONCONFIRM;
+ }
coap_hdr_t *hdr = (coap_hdr_t *) pdu;
+ if(NULL == hdr)
+ {
+ return CA_MSG_NONCONFIRM;
+ }
+
return (CAMessageType_t) hdr->type;
}
uint16_t CAGetMessageIdFromPduBinaryData(const void *pdu, uint32_t size)
{
// pdu minimum size is 4 byte.
- if (size < 4)
+ if (size < CA_PDU_MIN_SIZE)
+ {
+ OIC_LOG(DEBUG, TAG, "min size");
return 0;
+ }
coap_hdr_t *hdr = (coap_hdr_t *) pdu;
- return ntohs(hdr->id);
-}
-
-CAResponseResult_t CAGetCodeFromPduBinaryData(const void *pdu, uint32_t size)
-{
- // pdu minimum size is 4 byte.
- if (size < 4)
+ if(NULL == hdr)
+ {
return 0;
+ }
- coap_hdr_t *hdr = (coap_hdr_t *) pdu;
-
- return (CAResponseResult_t) CA_RESPONSE_CODE(hdr->code);
+ return ntohs(hdr->id);
}
if (thread == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "thread data passing error!!");
+ OIC_LOG_V(ERROR, TAG, "thread data passing error!!");
return;
}
// check stop flag
if (thread->isStop)
+ {
continue;
+ }
// get data
u_queue_message_t *message = u_queue_get_element(thread->dataQueue);
continue;
}
- void *data = message->msg;
-
// process data
- thread->threadTask(data);
+ thread->threadTask(message->msg);
// free
if (thread->destroy != NULL)
OIC_LOG_V(DEBUG, TAG, "thread initialize..");
- memset(thread, 0, sizeof(CAQueueingThread_t));
-
- // mutex init
- u_mutex_init();
-
// set send thread data
thread->threadPool = handle;
thread->dataQueue = u_queue_create();
thread->threadMutex = u_mutex_new();
thread->threadCond = u_cond_new();
- thread->isStop = CA_TRUE;
+ thread->isStop = true;
thread->threadTask = task;
thread->destroy = destroy;
return CA_STATUS_FAILED;
}
- if (CA_FALSE == thread->isStop) //Queueing thread already running
+ if (false == thread->isStop) //Queueing thread already running
{
OIC_LOG_V(DEBUG, TAG, "queueing thread already running..");
return CA_STATUS_OK;
}
- thread->isStop = CA_FALSE;
+ // mutex lock
+ u_mutex_lock(thread->threadMutex);
+ thread->isStop = false;
+ // mutex unlock
+ u_mutex_unlock(thread->threadMutex);
+
CAResult_t res = u_thread_pool_add_task(thread->threadPool, CAQueueingThreadBaseRoutine,
thread);
if (res != CA_STATUS_OK)
{
OIC_LOG_V(DEBUG, TAG, "thread pool add task error(send thread).");
- thread->isStop = CA_TRUE;
- return res;
}
return res;
{
if (thread == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "thread instance is empty..");
+ OIC_LOG_V(ERROR, TAG, "thread instance is empty..");
return CA_STATUS_FAILED;
}
if (data == NULL || size == 0)
{
- OIC_LOG_V(DEBUG, TAG, "data is empty..");
+ OIC_LOG_V(ERROR, TAG, "data is empty..");
return CA_STATUS_FAILED;
}
if (message == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "memory error!!");
+ OIC_LOG_V(ERROR, TAG, "memory error!!");
return CA_MEMORY_ALLOC_FAILED;
}
- memset(message, 0, sizeof(u_queue_message_t));
message->msg = data;
- message->size = sizeof(size);
+ message->size = size;
// mutex lock
u_mutex_lock(thread->threadMutex);
u_mutex_lock(thread->threadMutex);
// set stop flag
- thread->isStop = CA_TRUE;
+ thread->isStop = true;
- // notity the thread
+ // notify the thread
u_cond_signal(thread->threadCond);
u_cond_wait(thread->threadCond, thread->threadMutex);
return CA_STATUS_OK;
}
-
*
******************************************************************/
+#include <string.h>
+
#include "oic_malloc.h"
#include "caremotehandler.h"
#include "logger.h"
CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *rep)
{
char *temp = NULL;
- uint32_t len = 0;
+ size_t len = 0;
if (rep == NULL)
return NULL;
OIC_LOG(DEBUG, TAG, "CACloneRemoteEndpoint Out of memory");
return NULL;
}
- memset(clone, 0, sizeof(CARemoteEndpoint_t));
memcpy(clone, rep, sizeof(CARemoteEndpoint_t));
if (rep->resourceUri != NULL)
// allocate reference uri field
len = strlen(rep->resourceUri);
- temp = (char *) OICMalloc(sizeof(char) * (len + 1));
+ temp = (char *) OICCalloc(len + 1, sizeof(char));
if (temp == NULL)
{
OIC_LOG(DEBUG, TAG, "CACloneRemoteEndpoint Out of memory");
return NULL;
}
- memset(temp, 0, sizeof(char) * (len + 1));
+
strncpy(temp, rep->resourceUri, len);
// save the uri
// parse uri
// #1. check prefix
int startIndex = 0;
- CABool_t secured = CA_FALSE;
+ bool secured = false;
if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0)
{
OIC_LOG_V(DEBUG, TAG, "uri has '%s' prefix.", COAP_PREFIX);
{
OIC_LOG_V(DEBUG, TAG, "uri has '%s' prefix.", COAPS_PREFIX);
startIndex = COAPS_PREFIX_LEN;
- secured = CA_TRUE;
+ secured = true;
}
// #2. copy uri for parse
return NULL;
}
- cloneUri = (char *) OICMalloc(sizeof(char) * (len + 1));
+ cloneUri = (char *) OICCalloc(len + 1, sizeof(char));
if (cloneUri == NULL)
{
OIC_LOG(DEBUG, TAG, "CACreateRemoteEndpointUriInternal Out of memory");
return NULL;
}
- memset(cloneUri, 0, sizeof(char) * (len + 1));
+
memcpy(cloneUri, &uri[startIndex], sizeof(char) * len);
// #3. parse address
OIC_LOG_V(DEBUG, TAG, "pResourceUri : %s", pResourceUri == NULL ? "" : pResourceUri);
// address
- CAAddress_t address;
- memset(&address, 0, sizeof(CAAddress_t));
+ CAAddress_t address = {};
int resType = getCAAddress(pAddress, &address);
if (resType == -1)
// resource uri
CAURI_t resourceUri = pResourceUri;
- CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address, connectivityType);
+ CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address,
+ connectivityType);
if (remoteEndpoint == NULL)
{
OIC_LOG(DEBUG, TAG, "create remote endpoint fail");
}
// allocate the remote end point structure.
- CARemoteEndpoint_t *rep = (CARemoteEndpoint_t *) OICMalloc(sizeof(CARemoteEndpoint_t));
+ CARemoteEndpoint_t *rep = (CARemoteEndpoint_t *) OICCalloc(1, sizeof(CARemoteEndpoint_t));
if (rep == NULL)
{
OIC_LOG(DEBUG, TAG, "CACreateRemoteEndpointInternal of memory");
return NULL;
}
- memset(rep, 0, sizeof(CARemoteEndpoint_t));
// allocate reference uri field
len = strlen(resourceUri);
return NULL;
}
- memset(temp, 0, sizeof(char) * (len + 1));
strncpy(temp, resourceUri, len);
+ temp[len] = '\0';
// save the uri
rep->resourceUri = temp;
OIC_LOG(DEBUG, TAG, "CACloneRequestInfo Out of memory");
return NULL;
}
- memset(clone, 0, sizeof(CARequestInfo_t));
+
memcpy(clone, rep, sizeof(CARequestInfo_t));
if (rep->info.token != NULL)
{
// allocate token field
- len = CA_MAX_TOKEN_LEN;
+ len = strlen(rep->info.token);
- temp = (char *) OICMalloc(sizeof(char) * (len + 1));
+ temp = (char *) OICCalloc(len + 1, sizeof(char));
if (temp == NULL)
{
OIC_LOG(DEBUG, TAG, "CACloneRequestInfo Out of memory");
return NULL;
}
- memset(temp, 0, sizeof(char) * (len + 1));
- memcpy(temp, rep->info.token, len);
+ strncpy(temp, rep->info.token, len);
// save the token
clone->info.token = temp;
{
// save the options
clone->info.options =
- (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * clone->info.numOptions);
+ (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * rep->info.numOptions);
if (clone->info.options == NULL)
{
OIC_LOG(DEBUG, TAG, "CACloneRequestInfo Out of memory");
}
memcpy(clone->info.options,
rep->info.options,
- sizeof(CAHeaderOption_t) * clone->info.numOptions);
+ sizeof(CAHeaderOption_t) * rep->info.numOptions);
}
if (rep->info.payload != NULL)
return NULL;
}
- memset(temp, 0, sizeof(char) * (len + 1));
strncpy(temp, rep->info.payload, len);
+ temp[len] = '\0';
// save the payload
clone->info.payload = temp;
return NULL;
// allocate the response info structure.
- CAResponseInfo_t *clone = (CAResponseInfo_t *) OICMalloc(sizeof(CAResponseInfo_t));
+ CAResponseInfo_t *clone = (CAResponseInfo_t *) OICCalloc(1, sizeof(CAResponseInfo_t));
if (clone == NULL)
{
OIC_LOG(DEBUG, TAG, "CACloneResponseInfo Out of memory");
return NULL;
}
- memset(clone, 0, sizeof(CAResponseInfo_t));
memcpy(clone, rep, sizeof(CAResponseInfo_t));
if (rep->info.token != NULL)
{
// allocate token field
- len = CA_MAX_TOKEN_LEN;
+ len = strlen(rep->info.token);
- temp = (char *) OICMalloc(sizeof(char) * (len + 1));
+ temp = (char *) OICCalloc(len + 1, sizeof(char));
if (temp == NULL)
{
OIC_LOG(DEBUG, TAG, "CACloneResponseInfo Out of memory");
return NULL;
}
- memset(temp, 0, sizeof(char) * (len + 1));
- memcpy(temp, rep->info.token, len);
+ strncpy(temp, rep->info.token, len);
// save the token
clone->info.token = temp;
if (rep->info.options != NULL && rep->info.numOptions)
{
// save the options
- clone->info.options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t));
+ clone->info.options = (CAHeaderOption_t *) OICMalloc(
+ sizeof(CAHeaderOption_t) * rep->info.numOptions);
+
if (clone->info.options == NULL)
{
OIC_LOG(DEBUG, TAG, "CACloneResponseInfo Out of memory");
OICFree(clone);
return NULL;
}
- memset(clone->info.options, 0, sizeof(CAHeaderOption_t));
- memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t));
+ memcpy(clone->info.options, rep->info.options,
+ sizeof(CAHeaderOption_t) * rep->info.numOptions);
}
if (rep->info.payload != NULL)
// allocate payload field
len = strlen(rep->info.payload);
- temp = (char *) OICMalloc(sizeof(char) * (len + 1));
+ temp = (char *) OICCalloc(len + 1, sizeof(char));
if (temp == NULL)
{
OIC_LOG(DEBUG, TAG, "CACloneResponseInfo Out of memory");
return NULL;
}
- memset(temp, 0, sizeof(char) * (len + 1));
strncpy(temp, rep->info.payload, len);
// save the payload
return;
// free uri field
- if (rep->resourceUri != NULL)
- {
- OICFree((char *) rep->resourceUri);
- }
+ OICFree((char *) rep->resourceUri);
// free remote end point structure.
OICFree(rep);
return;
// free token field
- if (rep->info.token != NULL)
- {
- OICFree((char *) rep->info.token);
- }
+ OICFree((char *) rep->info.token);
// free options field
- if (rep->info.options != NULL && rep->info.numOptions)
- {
- OICFree((CAHeaderOption_t *) rep->info.options);
- }
+ OICFree((CAHeaderOption_t *) rep->info.options);
// free payload field
- if (rep->info.payload != NULL)
- {
- OICFree((char *) rep->info.payload);
- }
+ OICFree((char *) rep->info.payload);
OICFree(rep);
}
return;
// free token field
- if (rep->info.token != NULL)
- {
- OICFree((char *) rep->info.token);
- }
+ OICFree((char *) rep->info.token);
// free options field
if (rep->info.options != NULL && rep->info.numOptions)
}
// free payload field
- if (rep->info.payload != NULL)
- {
- OICFree((char *) rep->info.payload);
- }
+ OICFree((char *) rep->info.payload);
OICFree(rep);
}
+
#ifdef __ANDROID__
#include <linux/time.h>
#endif
-#include "coap.h"
+
#include "caretransmission.h"
#include "caremotehandler.h"
#include "caprotocolmessage.h"
#include "oic_malloc.h"
#include "logger.h"
-#define TAG PCF("CA")
+#define TAG PCF("RET")
typedef struct
{
- /** last sent time. microseconds **/
- uint64_t timeStamp;
- /** timeout value. milliseconds **/
- uint32_t timeout;
- /** retransmission count **/
- uint8_t triedCount;
- /** coap PDU message id **/
- uint16_t messageId;
- /** remote endpoint **/
- CARemoteEndpoint_t *endpoint;
- /** coap PDU **/
- void *pdu;
- /** coap PDU size**/
- uint32_t size;
+ uint64_t timeStamp; /**< last sent time. microseconds */
+ uint64_t timeout; /**< timeout value. microseconds */
+ uint8_t triedCount; /**< retransmission count */
+ uint16_t messageId; /**< coap PDU message id */
+ CARemoteEndpoint_t *endpoint; /**< remote endpoint */
+ void *pdu; /**< coap PDU */
+ uint32_t size; /**< coap PDU size */
} CARetransmissionData_t;
/**
- * getCurrent monotonic time
- *
- * microseconds
+ * @brief getCurrent monotonic time
+ * @return current time in microseconds
*/
uint64_t getCurrentTimeInMicroSeconds();
* @brief check timeout routine
* @param currentTime [IN]microseconds
* @param timeStamp [IN]microseconds
- * @param timeoutValue [IN]milliseconds
+ * @param timeoutValue [IN]microseconds
* @param triedCount [IN]
- * @return CA_TRUE(timeout) or CA_FALSE
- *
- * microseconds
+ * @return true if the timeout period has elapsed, false otherwise
*/
-static CABool_t CACheckTimeout(uint64_t currentTime, uint64_t timeStamp, uint32_t timeoutValue,
+static bool CACheckTimeout(uint64_t currentTime, uint64_t timeStamp, uint64_t timeoutValue,
uint8_t triedCount)
{
// #1. calculate timeout
- uint64_t timeout = (timeoutValue << triedCount) * (uint64_t) 1000;
+ uint32_t milliTimeoutValue = timeoutValue * 0.001;
+ uint64_t timeout = (milliTimeoutValue << triedCount) * (uint64_t) 1000;
if (currentTime >= timeStamp + timeout)
{
- OIC_LOG_V(DEBUG, TAG, "%d milliseconds time out!!, tried count(%d)",
- (timeoutValue << triedCount), triedCount);
- return CA_TRUE;
+ OIC_LOG_V(DEBUG, TAG, "%d microseconds time out!!, tried count(%d)", timeout, triedCount);
+ return true;
}
- return CA_FALSE;
+ return false;
}
/**
* @brief timeout value is
- * between DEFAULT_ACK_TIMEOUT and (DEFAULT_ACK_TIMEOUT * DEFAULT_RANDOM_FACTOR) second.
+ * between DEFAULT_ACK_TIMEOUT_SEC and
+ * (DEFAULT_ACK_TIMEOUT_SEC * DEFAULT_RANDOM_FACTOR) second.
* DEFAULT_RANDOM_FACTOR 1.5 (CoAP)
- * @return milliseconds.
+ * @return microseconds.
*/
-static uint32_t CAGetTimeoutValue()
+static uint64_t CAGetTimeoutValue()
{
- return (DEFAULT_ACK_TIMEOUT * 1000) + ((1000 * (rand() & 0xFF)) >> 8);
+ return ((DEFAULT_ACK_TIMEOUT_SEC * 1000) + ((1000 * (random() & 0xFF)) >> 8)) *
+ (uint64_t) 1000;
}
static void CACheckRetransmissionList(CARetransmission_t *context)
{
// mutex lock
u_mutex_lock(context->threadMutex);
- uint64_t currentTime = 0;
- uint32_t i = 0;
+ int32_t i = 0;
uint32_t len = u_arraylist_length(context->dataList);
for (i = 0; i < len; i++)
CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
if (retData == NULL)
+ {
continue;
+ }
- currentTime = getCurrentTimeInMicroSeconds();
+ uint64_t currentTime = getCurrentTimeInMicroSeconds();
if (CACheckTimeout(currentTime, retData->timeStamp, retData->timeout, retData->triedCount))
{
// modify loop value.
len = u_arraylist_length(context->dataList);
+
--i;
}
else
{
- OIC_LOG_V(DEBUG, TAG, "arraylist remove error");
+ OIC_LOG_V(ERROR, TAG, "arraylist remove error");
}
}
if (context == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "thread data passing error!!");
+ OIC_LOG_V(ERROR, TAG, "thread data passing error!!");
return;
}
}
else
{
- // check each RETRANSMISSION_CHECK_PERIOD time.
- OIC_LOG_V(DEBUG, TAG, "wait..(%d)microseconds", RETRANSMISSION_CHECK_PERIOD);
+ // check each RETRANSMISSION_CHECK_PERIOD_SEC time.
+ OIC_LOG_V(DEBUG, TAG, "wait..(%d)microseconds",
+ RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) 1000000);
// wait
- u_cond_timed_wait(context->threadCond, context->threadMutex,
- RETRANSMISSION_CHECK_PERIOD);
+ u_cond_wait_until(context->threadCond, context->threadMutex,
+ RETRANSMISSION_CHECK_PERIOD_SEC * (uint64_t) 1000000);
}
// mutex unlock
// check stop flag
if (context->isStop)
+ {
continue;
+ }
CACheckRetransmissionList(context);
}
memset(context, 0, sizeof(CARetransmission_t));
- CARetransmissionConfig_t cfg;
- memset(&cfg, 0, sizeof(CARetransmissionConfig_t));
+ CARetransmissionConfig_t cfg = { 0 };
if (config == NULL)
{
cfg = *config;
}
- // mutex init
- u_mutex_init();
-
// set send thread data
context->threadPool = handle;
context->threadMutex = u_mutex_new();
context->dataSendMethod = retransmissionSendMethod;
context->timeoutCallback = timeoutCallback;
context->config = cfg;
- context->isStop = CA_FALSE;
+ context->isStop = false;
context->dataList = u_arraylist_create();
return CA_STATUS_OK;
if (res != CA_STATUS_OK)
{
- OIC_LOG_V(DEBUG, TAG, "thread pool add task error(send thread).");
+ OIC_LOG_V(ERROR, TAG, "thread pool add task error(send thread).");
return res;
}
}
// create retransmission data
- CARetransmissionData_t *retData = (CARetransmissionData_t *) OICMalloc(
- sizeof(CARetransmissionData_t));
+ CARetransmissionData_t *retData = (CARetransmissionData_t *) OICCalloc(
+ 1, sizeof(CARetransmissionData_t));
if (retData == NULL)
{
- OIC_LOG_V(DEBUG, TAG, "memory error!!");
+ OIC_LOG_V(ERROR, TAG, "memory error!!");
return CA_MEMORY_ALLOC_FAILED;
}
- memset(retData, 0, sizeof(CARetransmissionData_t));
// copy PDU data
void *pduData = (void *) OICMalloc(sizeof(int8_t) * size);
if (pduData == NULL)
{
OICFree(retData);
- OIC_LOG_V(DEBUG, TAG, "memory error!!");
+ OIC_LOG_V(ERROR, TAG, "memory error!!");
return CA_MEMORY_ALLOC_FAILED;
}
- memset(pduData, 0, sizeof(int8_t) * size);
memcpy(pduData, pdu, sizeof(int8_t) * size);
// clone remote endpoint
{
OICFree(retData);
OICFree(pduData);
- OIC_LOG_V(DEBUG, TAG, "memory error!!");
+ OIC_LOG_V(ERROR, TAG, "memory error!!");
return CA_MEMORY_ALLOC_FAILED;
}
// mutex lock
u_mutex_lock(context->threadMutex);
+ uint32_t i = 0;
+ uint32_t len = u_arraylist_length(context->dataList);
+
// #3. add data into list
+ for (i = 0; i < len; i++)
+ {
+ CARetransmissionData_t *currData = u_arraylist_get(context->dataList, i);
+
+ if (currData == NULL)
+ {
+ continue;
+ }
+
+ // found index
+ if (retData != NULL && (currData->endpoint->connectivityType == endpoint->connectivityType)
+ && currData->messageId == messageId)
+ {
+ OIC_LOG_V(ERROR, TAG, "Duplicate message ID");
+
+ // mutex unlock
+ u_mutex_unlock(context->threadMutex);
+
+ OICFree(retData);
+ OICFree(pduData);
+ OICFree(remoteEndpoint);
+ return CA_STATUS_FAILED;
+ }
+ }
+
u_arraylist_add(context->dataList, (void *) retData);
// notity the thread
}
CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
- const CARemoteEndpoint_t *endpoint,
- const void *pdu, uint32_t size,
- void **retransmissionPdu)
+ const CARemoteEndpoint_t *endpoint, const void *pdu,
+ uint32_t size)
{
- OIC_LOG_V(DEBUG, TAG, "IN - CARetransmissionReceivedData");
if (context == NULL || endpoint == NULL || pdu == NULL)
{
OIC_LOG_V(DEBUG, TAG, "invalid parameter..");
{
CARetransmissionData_t *retData = u_arraylist_get(context->dataList, i);
- if (retData == NULL)
- continue;
-
// found index
- if ((retData->endpoint->connectivityType == endpoint->connectivityType)
+ if (retData != NULL && (retData->endpoint->connectivityType == endpoint->connectivityType)
&& retData->messageId == messageId)
{
- // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
- // if retransmission was finish..token will be unavailable.
- if(CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
+ // #2. remove data from list
+ CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
+
+ if (removedData != NULL)
{
- OIC_LOG_V(DEBUG, TAG, "code is CA_EMPTY..");
+ OIC_LOG_V(DEBUG, TAG, "remove retransmission CON data!!, message id(%d)",
+ messageId);
- if(NULL == retData->pdu)
- {
- OIC_LOG_V(DEBUG, TAG, "retData->pdu is null");
- }
+ CADestroyRemoteEndpointInternal(removedData->endpoint);
+ OICFree(removedData->pdu);
- // copy PDU data
- (*retransmissionPdu) = (void *) OICMalloc(sizeof(int8_t) * retData->size);
- if ((*retransmissionPdu) == NULL)
- {
- OICFree(retData);
- OIC_LOG_V(DEBUG, TAG, "memory error!!");
- return CA_MEMORY_ALLOC_FAILED;
- }
- memset((*retransmissionPdu), 0, sizeof(int8_t) * retData->size);
- memcpy((*retransmissionPdu), retData->pdu, sizeof(int8_t) * retData->size);
+ OICFree(removedData);
}
-
break;
}
}
- // #2. remove data from list
- if (i < len)
- {
- CARetransmissionData_t *removedData = u_arraylist_remove(context->dataList, i);
-
- if (removedData != NULL)
- {
- OIC_LOG_V(DEBUG, TAG, "remove retransmission CON data!!, message id(%d)", messageId);
-
- CADestroyRemoteEndpointInternal(removedData->endpoint);
- OICFree(removedData->pdu);
-
- OICFree(removedData);
- }
- }
-
// mutex unlock
u_mutex_unlock(context->threadMutex);
- OIC_LOG_V(DEBUG, TAG, "OUT - CARetransmissionReceivedData");
return CA_STATUS_OK;
}
u_mutex_lock(context->threadMutex);
// set stop flag
- context->isStop = CA_TRUE;
+ context->isStop = true;
// notity the thread
u_cond_signal(context->threadCond);
#ifdef __ANDROID__
struct timespec getTs;
- memset(&getTs, 0, sizeof(getTs));
clock_gettime(CLOCK_MONOTONIC, &getTs);
currentTime = (getTs.tv_sec * (uint64_t)1000000000 + getTs.tv_nsec)/1000;
#endif
return currentTime;
}
+
*
******************************************************************/
#include "caretransmission_singlethread.h"
-#include "coap.h"
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
{
/** last sent time. microseconds **/
uint64_t timeStamp;
+
/** retransmission count **/
uint8_t triedCount;
+
/** coap PDU message id **/
uint16_t messageId;
+
/** remote endpoint **/
CARemoteEndpoint_t *endpoint;
+
/** coap PDU **/
void *pdu;
+
/** coap PDU size**/
uint32_t size;
+
} CARetransmissionData_t;
-static CARetransmission_t *gRetransmissionPtr = NULL;
+static CARetransmission_t *g_retransmissionPtr = NULL;
/**
- * getCurrent monotonic time
+ * getCurrent monotonic time.
*
- * microseconds
+ * @return current time in microseconds.
*/
uint64_t getCurrentTimeInMicroSeconds();
/**
- * timeout routine
- * 2sec -> 4sec -> 8sec -> 16sec
- *
- * microseconds
+ * @brief check timeout routine
+ * @param currentTime [IN]microseconds
+ * @param timeStamp [IN]microseconds
+ * @param triedCount [IN]Number of retransmission tried.
+ * @return true if the timeout period has elapsed, false otherwise.
*/
-static CABool_t CACheckTimeout(uint64_t currentTime, uint64_t timeStamp, uint8_t triedCount)
+static bool CACheckTimeout(uint64_t currentTime, uint64_t timeStamp, uint8_t triedCount)
{
OIC_LOG(DEBUG, TAG, "IN");
// #1. calculate timeout
if (currentTime >= timeStamp + timeOut)
{
OIC_LOG_V(DEBUG, TAG, "timeout=%d, tried cnt=%d", (2 << triedCount), triedCount);
- return CA_TRUE;
+ return true;
}
OIC_LOG(DEBUG, TAG, "OUT");
- return CA_FALSE;
+ return false;
}
void CACheckRetransmissionList()
uint64_t currentTime = 0;
uint32_t i = 0;
- uint32_t len = u_arraylist_length(gRetransmissionPtr->dataList);
+ uint32_t len = u_arraylist_length(g_retransmissionPtr->dataList);
OIC_LOG_V(DEBUG, TAG, "len=%d", len);
for (i = 0; i < len; i++)
{
CARetransmissionData_t *retData =
- (CARetransmissionData_t *)u_arraylist_get(gRetransmissionPtr->dataList, i);
+ (CARetransmissionData_t *)u_arraylist_get(g_retransmissionPtr->dataList, i);
if (retData == NULL)
continue;
OIC_LOG(DEBUG, TAG, "RTdata-Success");
// #2. if time's up, send the data.
- if (gRetransmissionPtr->dataSendMethod != NULL)
+ if (g_retransmissionPtr->dataSendMethod != NULL)
{
OIC_LOG_V(DEBUG, TAG, "retry CON data-msgid=%d", retData->messageId);
- gRetransmissionPtr->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
+ g_retransmissionPtr->dataSendMethod(retData->endpoint, retData->pdu, retData->size);
}
// #3. increase the retransmission count and update timestamp.
}
// #4. if tried count is max, remove the retransmission data from list.
- if (retData->triedCount >= gRetransmissionPtr->config.tryingCount)
+ if (retData->triedCount >= g_retransmissionPtr->config.tryingCount)
{
CARetransmissionData_t *removedData =
- (CARetransmissionData_t *)u_arraylist_remove(gRetransmissionPtr->dataList, i);
+ (CARetransmissionData_t *)u_arraylist_remove(g_retransmissionPtr->dataList, i);
if (NULL == removedData)
{
OIC_LOG(DEBUG, TAG, "Removed data is NULL");
removedData->messageId);
// callback for retransmit timeout
- if (gRetransmissionPtr->timeoutCallback != NULL)
+ if (g_retransmissionPtr->timeoutCallback != NULL)
{
- gRetransmissionPtr->timeoutCallback(removedData->endpoint, removedData->pdu,
+ g_retransmissionPtr->timeoutCallback(removedData->endpoint, removedData->pdu,
removedData->size);
}
OICFree(removedData);
// modify loop value.
- len = u_arraylist_length(gRetransmissionPtr->dataList);
+ len = u_arraylist_length(g_retransmissionPtr->dataList);
--i;
}
}
if (context == NULL)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "cnxt null");
return;
}
- if (CA_TRUE == context->isStop)
+ if (true == context->isStop)
{
- OIC_LOG(DEBUG, TAG, "Not reqd");
+ OIC_LOG(DEBUG, TAG, "thread stopped");
return;
}
- gRetransmissionPtr = context;
+ g_retransmissionPtr = context;
CACheckRetransmissionList();
}
OIC_LOG(DEBUG, TAG, "IN");
if (context == NULL)
{
- OIC_LOG(DEBUG, TAG, "error");
+ OIC_LOG(ERROR, TAG, "cnxt null");
return CA_STATUS_FAILED;
}
context->dataSendMethod = retransmissionSendMethod;
context->timeoutCallback = timeoutCallback;
context->config = cfg;
- context->isStop = CA_FALSE;
+ context->isStop = false;
context->dataList = u_arraylist_create();
// Enable TimedAction for CACheckRetransmissionList API
- gRetransmissionPtr = context;
+ g_retransmissionPtr = context;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
OIC_LOG(DEBUG, TAG, "error");
return CA_MEMORY_ALLOC_FAILED;
}
- memset(pduData, 0, sizeof(int8_t) * size);
memcpy(pduData, pdu, sizeof(int8_t) * size);
// clone remote endpoint
u_arraylist_add(context->dataList, (void *) retData);
// #4. Initiate Re-transmission for added entry
- gRetransmissionPtr = context;
+ g_retransmissionPtr = context;
CACheckRetransmissionList();
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CARetransmissionReceivedData(CARetransmission_t *context,
- const CARemoteEndpoint_t *endpoint,
- const void *pdu, uint32_t size,
- void **retransmissionPdu)
+ const CARemoteEndpoint_t *endpoint, const void *pdu, uint32_t size)
{
OIC_LOG(DEBUG, TAG, "IN");
if (context == NULL || endpoint == NULL || pdu == NULL)
// found index
if ((retData->endpoint->connectivityType == endpoint->connectivityType)
&& retData->messageId == messageId)
- {
- // get pdu data for getting token when CA_EMPTY(RST/ACK) is received from remote device
- // if retransmission was finish..token will be unavailable.
- if(CA_EMPTY == CAGetCodeFromPduBinaryData(pdu, size))
- {
- OIC_LOG(DEBUG, TAG, "CA_EMPTY");
-
- if(NULL == retData->pdu)
- {
- OIC_LOG(DEBUG, TAG, "retData->pdu is null");
- }
-
- // copy PDU data
- (*retransmissionPdu) = (void *) OICMalloc(sizeof(int8_t) * retData->size);
- if (NULL == (*retransmissionPdu))
- {
- OICFree(retData);
- OIC_LOG(DEBUG, TAG, "error");
- return CA_MEMORY_ALLOC_FAILED;
- }
- memset((*retransmissionPdu), 0, sizeof(int8_t) * retData->size);
- memcpy((*retransmissionPdu), retData->pdu, sizeof(int8_t) * retData->size);
- }
-
break;
- }
}
// #2. remove data from list
}
// set stop flag
- context->isStop = CA_TRUE;
+ context->isStop = true;
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
OIC_LOG(DEBUG, TAG, "IN");
uint64_t currentTime = 0;
- /*
- #ifdef __ANDROID__
- struct timespec getTs;
-
- memset(&getTs, 0, sizeof(getTs));
- clock_gettime(CLOCK_MONOTONIC, &getTs);
-
- currentTime = (getTs.tv_sec * 1000000000 + getTs.tv_nsec)/1000;
- OIC_LOG_V(DEBUG, TAG, "current time = %d", currentTime);
- #else if __ARDUINO__
- currentTime = micros();
- #else
- currentTime = g_get_monotonic_time();
- */
#ifdef __ARDUINO__
- currentTime = micros();
+ currentTime = millis() * 1000;
OIC_LOG_V(DEBUG, TAG, "currtime=%lu", currentTime);
#else
OIC_LOG(DEBUG, TAG, "OUT");
return currentTime;
}
+
src_dir+'arduino/caethernetclient.cpp',
src_dir+'arduino/caethernetserver.cpp',
src_dir+'arduino/caethernetnwmonitor.cpp',
- ])
\ No newline at end of file
+ ])
#define MOD_NAME "EU"
-CAResult_t CAArduinoInitUdpSocket(int16_t *port, int32_t *socketID)
+CAResult_t CAArduinoGetAvailableSocket(int *sockID)
{
- OIC_LOG(DEBUG, MOD_NAME, "IN");
- VERIFY_NON_NULL(port, MOD_NAME, "port");
- VERIFY_NON_NULL(socketID, MOD_NAME, "socketID");
-
+ VERIFY_NON_NULL(sockID, MOD_NAME, "sockID");
uint8_t state;
//Is any socket available to work with ?
- int32_t sockID = 0;
+ *sockID = 0;
for (int i = 1; i < MAX_SOCK_NUM; i++)
{
state = W5100.readSnSR(i);
if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT)
{
- sockID = i;
+ *sockID = i;
break;
}
}
- if (sockID == 0)
+ if (*sockID == 0)
{
- OIC_LOG(ERROR, MOD_NAME, "failed");
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, MOD_NAME, "sockID 0");
+ return CA_SOCKET_OPERATION_FAILED;
+ }
+
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAArduinoInitUdpSocket(uint16_t *port, int *socketID)
+{
+ OIC_LOG(DEBUG, MOD_NAME, "IN");
+ VERIFY_NON_NULL(port, MOD_NAME, "port");
+ VERIFY_NON_NULL(socketID, MOD_NAME, "socketID");
+
+ CAResult_t ret = CAArduinoGetAvailableSocket(socketID);
+ if (ret != CA_STATUS_OK)
+ {
+ OIC_LOG(ERROR, MOD_NAME, "get sock fail");
+ return ret;
}
//Create a datagram socket on which to recv/send.
- if (!socket(sockID, SnMR::UDP, *port, 0))
+ if (!socket(*socketID, SnMR::UDP, *port, 0))
{
- OIC_LOG(ERROR, MOD_NAME, "failed");
+ OIC_LOG(ERROR, MOD_NAME, "sock fail");
return CA_STATUS_FAILED;
}
- *socketID = sockID;
- OIC_LOG_V(DEBUG, MOD_NAME, "socketId:%d", sockID);
+ OIC_LOG_V(DEBUG, MOD_NAME, "socketId:%d", *socketID);
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
}
-CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, const int16_t *mport,
- const int16_t *lport, int32_t *socketID)
+CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress,
+ uint16_t mport,
+ uint16_t lport, int *socketID)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
VERIFY_NON_NULL(mcastAddress, MOD_NAME, "address");
VERIFY_NON_NULL(socketID, MOD_NAME, "socket");
- VERIFY_NON_NULL(lport, MOD_NAME, "port");
- VERIFY_NON_NULL(mport, MOD_NAME, "port");
- uint8_t state;
+
uint8_t mcastMacAddr[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00};
uint8_t ipAddr[4] = { 0 };
uint16_t parsedPort = 0;
- if (!CAParseIPv4AddressLocal((unsigned char *) mcastAddress, ipAddr, &parsedPort))
+ if (CAParseIPv4AddressInternal(mcastAddress, ipAddr, sizeof(ipAddr),
+ &parsedPort) != CA_STATUS_OK)
{
- OIC_LOG(ERROR, MOD_NAME, "failed");
+ OIC_LOG(ERROR, MOD_NAME, "parse fail");
return CA_STATUS_FAILED;
}
- int32_t sockID = 0;
- //Is any socket available to work with ?
- for (int i = 1; i < MAX_SOCK_NUM; i++)
+ *socketID = 0;
+ CAResult_t ret = CAArduinoGetAvailableSocket(socketID);
+ if (ret != CA_STATUS_OK)
{
- state = W5100.readSnSR(i);
- if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT)
- {
- sockID = i;
- break;
- }
+ OIC_LOG(ERROR, MOD_NAME, "sock fail");
+ return ret;
}
- if (sockID == 0)
- {
- OIC_LOG(ERROR, MOD_NAME, "failed");
- return CA_STATUS_FAILED;
- }
-
-
//Calculate Multicast MAC address
mcastMacAddr[3] = ipAddr[1] & 0x7F;
mcastMacAddr[4] = ipAddr[2];
mcastMacAddr[5] = ipAddr[3];
- W5100.writeSnDIPR(sockID, (uint8_t *)ipAddr);
- W5100.writeSnDHAR(sockID, mcastMacAddr);
- W5100.writeSnDPORT(sockID, *mport);
+ W5100.writeSnDIPR(*socketID, (uint8_t *)ipAddr);
+ W5100.writeSnDHAR(*socketID, mcastMacAddr);
+ W5100.writeSnDPORT(*socketID, mport);
//Create a datagram socket on which to recv/send.
- if (!socket(sockID, SnMR::UDP, *lport, SnMR::MULTI))
+ if (!socket(*socketID, SnMR::UDP, lport, SnMR::MULTI))
{
- OIC_LOG(ERROR, MOD_NAME, "failed");
- return CA_STATUS_FAILED;
+ OIC_LOG(ERROR, MOD_NAME, "sock fail");
+ return CA_SOCKET_OPERATION_FAILED;
}
- *socketID = sockID;
- OIC_LOG_V(DEBUG, MOD_NAME, "socketId:%d", sockID);
+ OIC_LOG_V(DEBUG, MOD_NAME, "socketId:%d", *socketID);
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
}
-int16_t CAParseIPv4AddressLocal(unsigned char *ipAddrStr, uint8_t *ipAddr, uint16_t *port)
-{
- size_t index = 0;
- unsigned char *itr;
- uint8_t dotCount = 0;
-
- ipAddr[index] = 0;
- *port = 0;
- itr = ipAddrStr;
- if (!isdigit((unsigned char) *ipAddrStr))
- {
- return -1;
- }
- ipAddrStr = itr;
-
- while (*ipAddrStr)
- {
- if (isdigit((unsigned char) *ipAddrStr))
- {
- ipAddr[index] *= 10;
- ipAddr[index] += *ipAddrStr - '0';
- }
- else if ((unsigned char) *ipAddrStr == '.')
- {
- index++;
- dotCount++;
- ipAddr[index] = 0;
- }
- else
- {
- break;
- }
- ipAddrStr++;
- }
- if (*ipAddrStr == ':')
- {
- ipAddrStr++;
- while (*ipAddrStr)
- {
- if (isdigit((unsigned char) *ipAddrStr))
- {
- *port *= 10;
- *port += *ipAddrStr - '0';
- }
- else
- {
- break;
- }
- ipAddrStr++;
- }
- }
- if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255
- && dotCount == 3)
- {
- return 1;
- }
- return 0;
-}
-
-
#endif
/**
- * @brief Initialize Unicast UDP socket
- * @param port [IN] Port to start the unicast server
- * @param socketID [IN] Unicast socket ID
+ * @brief Get available UDP socket
+ * @param sockID [OUT] Available UDP socket ID
* @return #CA_STATUS_OK or Appropriate error code
*/
-CAResult_t CAArduinoInitUdpSocket(int16_t *port, int32_t *socketID);
+CAResult_t CAArduinoGetAvailableSocket(int *sockID);
/**
- * @brief Initialize Multicast UDP socket
- * @param mcastAddress [IN] Port to start the unicast server
- * @param mport [IN] Multicast port
- * @param lport [IN] Local port on which the server is started
- * @param socketID [IN] Multicast socket ID
+ * @brief Initialize Unicast UDP socket
+ * @param port [INOUT] Port to start the unicast server
+ * @param socketID [OUT Unicast socket ID
* @return #CA_STATUS_OK or Appropriate error code
*/
-CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, const int16_t *mport,
- const int16_t *lport, int32_t *socketID);
+CAResult_t CAArduinoInitUdpSocket(uint16_t *port, int *socketID);
/**
- * @brief To parse the IP address
- * @param ipAddrStr [IN] IP address to be parsed
- * @param ipAddr [OUT] Parsed IP address
- * @param port [OUT] Parsed Port number
- * @return 1 on Success otherwise failed to parse the address
+ * @brief Initialize Multicast UDP socket
+ * @param mcastAddress [IN] Port to start the unicast server
+ * @param mport [IN] Multicast port
+ * @param lport [IN] Local port on which the server is started
+ * @param socketID [OUT] Multicast socket ID
+ * @return #CA_STATUS_OK or Appropriate error code
*/
-int16_t CAParseIPv4AddressLocal(unsigned char *ipAddrStr, uint8_t *ipAddr, uint16_t *port);
+CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress,
+ uint16_t mport, uint16_t lport,
+ int *socketID);
#ifdef __cplusplus
}
#endif //_CA_ETHERNET_ADAPTER_UTILS_
+
#include "caadapterutils.h"
#include "oic_malloc.h"
-/// This is the max buffer size between Arduino and WiFi Shield
-#define ARDUINO_ETHERNET_SPI_RECV_BUFFERSIZE (64)
-
#define MOD_NAME "EC"
-static int32_t gSockID = 0;
+static int g_sockID = 0;
/**
- * @var gUnicastPort
+ * @var g_unicastPort
* @brief Unicast Port
*/
-static int16_t gUnicastPort = 0;
+static uint16_t g_unicastPort = 0;
-void CAEthernetSetUnicastSocket(const int32_t socketID)
+void CAEthernetSetUnicastSocket(int socketID)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
if (0 < socketID)
{
- gSockID = socketID;
- return;
+ g_sockID = socketID;
+ }
+ else
+ {
+ OIC_LOG(ERROR, MOD_NAME, "sock err");
}
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return;
}
-void CAEthernetSetUnicastPort(const int16_t port)
+void CAEthernetSetUnicastPort(uint16_t port)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
- if (0 < port)
- {
- gUnicastPort = port;
- return;
- }
-
+ g_unicastPort = port;
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return;
}
-uint32_t CAEthernetSendData(const char *remoteAddress, const int16_t port,
- const char *buf, const uint32_t bufLen, bool isMulticast)
+uint32_t CAEthernetSendData(const char *remoteAddress, uint16_t port,
+ const char *buf, uint32_t bufLen, bool isMulticast)
{
- if (!isMulticast && 0 == gUnicastPort)
+ if (!isMulticast && 0 == g_unicastPort)
{
- OIC_LOG(ERROR, MOD_NAME, "Failed");
+ OIC_LOG(ERROR, MOD_NAME, "port 0");
return 0;
}
- int32_t socketID = 0;
+ VERIFY_NON_NULL(buf, MOD_NAME, "buf");
+ VERIFY_NON_NULL(remoteAddress, MOD_NAME, "address");
+
+ int socketID = 0;
if (isMulticast)
{
- if (CAArduinoInitMulticastUdpSocket(remoteAddress, &port, &gUnicastPort, &socketID) != CA_STATUS_OK)
+ if (CAArduinoInitMulticastUdpSocket(remoteAddress, port, g_unicastPort, &socketID)
+ != CA_STATUS_OK)
{
- OIC_LOG(ERROR, MOD_NAME, "multicast");
+ OIC_LOG(ERROR, MOD_NAME, "init mcast err");
return 0;
}
OIC_LOG_V(DEBUG, MOD_NAME, "MPORT:%d", port);
- OIC_LOG_V(DEBUG, MOD_NAME, "LPORT:%d", gUnicastPort);
+ OIC_LOG_V(DEBUG, MOD_NAME, "LPORT:%d", g_unicastPort);
OIC_LOG_V(DEBUG, MOD_NAME, "SOCKET ID:%d", socketID);
}
else
{
- if (0 == gSockID)
+ if (0 == g_sockID)
{
- if (CAArduinoInitUdpSocket((int16_t *)&port, &socketID) != CA_STATUS_OK)
+ if (CAArduinoInitUdpSocket(&port, &socketID) != CA_STATUS_OK)
{
- OIC_LOG(ERROR, MOD_NAME, "unicast");
+ OIC_LOG(ERROR, MOD_NAME, "init ucast err");
return 0;
}
}
else
{
- socketID = gSockID;
+ socketID = g_sockID;
}
}
uint32_t ret;
- VERIFY_NON_NULL(buf, MOD_NAME, "buf");
- VERIFY_NON_NULL(remoteAddress, MOD_NAME, "address");
-
uint8_t ipAddr[4] = { 0 };
uint16_t parsedPort = 0;
- if (!CAParseIPv4AddressLocal((unsigned char *) remoteAddress, ipAddr, &parsedPort))
+ if (CAParseIPv4AddressInternal(remoteAddress, ipAddr, sizeof(ipAddr),
+ &parsedPort) != CA_STATUS_OK)
{
- OIC_LOG(ERROR, MOD_NAME, "failed");
+ OIC_LOG(ERROR, MOD_NAME, "parse fail");
return 0;
}
- ret = sendto(socketID, (const uint8_t *)buf, (uint16_t)bufLen, (uint8_t *)ipAddr, port);
- delay(10);
- if (gSockID != socketID)
+ if (bufLen > 65535) // Max value for uint16_t
+ {
+ // This will never happen as max buffer size we are dealing with is COAP_MAX_PDU_SIZE
+ OIC_LOG(ERROR, MOD_NAME, "Size exceeded");
+ return 0;
+ }
+
+ ret = sendto(socketID, (const uint8_t *)buf, (uint16_t)bufLen, ipAddr, port);
+ if (g_sockID != socketID)
{
close(socketID);
}
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return ret;
}
+
bool CAEthernetIsConnected(void)
{
- return CA_TRUE;
+ return true;
}
-void CAEthernetSetConnectionStateChangeCallback(CAEthernetConnectionStateChangeCallback callback)
+void CAEthernetSetConnectionStateChangeCallback
+ (CAEthernetConnectionStateChangeCallback callback)
{
return;
}
void CAEthernetTerminateNetworkMonitor(void)
{
return;
-}
\ No newline at end of file
+}
#include "caadapterutils.h"
#include "oic_malloc.h"
-#define COAP_MAX_PDU_SIZE 320
#define MOD_NAME "ES"
// Length of the IP address decimal notation string
#define IPNAMESIZE (16)
-CAResult_t CAEthernetStartUnicastServer(const char *localAddress, int16_t *port,
+CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port,
const bool forceStart, int32_t *serverFD);
-static int32_t CAArduinoRecvData(int32_t sockFd, uint8_t **buf, uint32_t bufLen,
- uint8_t *senderAddr, uint16_t *senderPort);
+static CAResult_t CAArduinoRecvData(int32_t sockFd);
static CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen);
static void CAArduinoCheckData();
static void CAPacketReceivedCallback(const char *ipAddress, const uint32_t port,
const void *data, const uint32_t dataLength);
-static CAEthernetPacketReceivedCallback gPacketReceivedCallback = NULL;
-static int32_t gUnicastSocket = 0;
-static int32_t gMulticastSocket = 0;
+static CAEthernetPacketReceivedCallback g_packetReceivedCallback = NULL;
+static int g_unicastSocket = 0;
+static int g_multicastSocket = 0;
/**
- * @var gUnicastPort
+ * @var g_unicastPort
* @brief Unicast Port
*/
-int16_t gUnicastPort = 0;
+static uint16_t g_unicastPort = 0;
CAResult_t CAEthernetInitializeServer(void)
{
return;
}
-CAResult_t CAEthernetGetUnicastServerInfo(char **ipAddress, int *port, int32_t *serverID)
+CAResult_t CAEthernetGetUnicastServerInfo(char **ipAddress, uint16_t *port,
+ int *serverID)
{
return CA_STATUS_OK;
}
-CAResult_t CAEthernetStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, int32_t *serverFD)
+CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port,
+ const bool forceStart, int *serverFD)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
VERIFY_NON_NULL(port, MOD_NAME, "port");
- // Note: ****Update the MAC address here with your shield's MAC address****
- uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
- uint8_t error = Ethernet.begin(ETHERNET_MAC);
- if (error == 0)
- {
- OIC_LOG_V(ERROR, MOD_NAME, "FAILED:%d", error);
- return CA_STATUS_FAILED;
- }
- OIC_LOG(DEBUG, MOD_NAME, "success");
-
uint8_t rawIPAddr[4];
char address[16];
W5100.getIPAddress(rawIPAddr);
sprintf(address, "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2], rawIPAddr[3]);
OIC_LOG_V(DEBUG, MOD_NAME, "address:%s", address);
- //if (CAArduinoInitUdpSocket(port, serverFD) != CA_STATUS_OK)
if (CAArduinoInitUdpSocket(port, serverFD) != CA_STATUS_OK)
{
OIC_LOG(DEBUG, MOD_NAME, "failed");
return CA_STATUS_FAILED;
}
- gUnicastPort = *port;
- gUnicastSocket = *serverFD;
- OIC_LOG_V(DEBUG, MOD_NAME, "gUnicastPort: %d", gUnicastPort);
- OIC_LOG_V(DEBUG, MOD_NAME, "gUnicastSocket: %d", gUnicastSocket);
+ g_unicastPort = *port;
+ g_unicastSocket = *serverFD;
+ OIC_LOG_V(DEBUG, MOD_NAME, "g_unicastPort: %d", g_unicastPort);
+ OIC_LOG_V(DEBUG, MOD_NAME, "g_unicastSocket: %d", g_unicastSocket);
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAEthernetStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD)
+ uint16_t multicastPort, int *serverFD)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
- if (CAArduinoInitMulticastUdpSocket(multicastAddress, &multicastPort, &multicastPort,
+ if (CAArduinoInitMulticastUdpSocket(multicastAddress, multicastPort, multicastPort,
serverFD) != CA_STATUS_OK)
{
OIC_LOG(DEBUG, MOD_NAME, "failed");
return CA_STATUS_FAILED;
}
- gMulticastSocket = *serverFD;
+ g_multicastSocket = *serverFD;
OIC_LOG_V(DEBUG, MOD_NAME, "gMulticastPort: %d", multicastPort);
- OIC_LOG_V(DEBUG, MOD_NAME, "gMulticastSocket: %d", gMulticastSocket);
+ OIC_LOG_V(DEBUG, MOD_NAME, "g_multicastSocket: %d", g_multicastSocket);
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAEthernetStopUnicastServer()
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
- close(gUnicastSocket);
- gUnicastSocket = 0;
+ close(g_unicastSocket);
+ g_unicastSocket = 0;
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAEthernetStopMulticastServer()
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
- close(gMulticastSocket);
- gMulticastSocket = 0;
+ close(g_multicastSocket);
+ g_multicastSocket = 0;
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
}
const void *data, const uint32_t dataLength)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
- if (gPacketReceivedCallback)
+ if (g_packetReceivedCallback)
{
- gPacketReceivedCallback(ipAddress, port, data, dataLength);
+ g_packetReceivedCallback(ipAddress, port, data, dataLength);
}
OIC_LOG(DEBUG, MOD_NAME, "OUT");
}
void CAArduinoCheckData()
{
- void *data = NULL;
- int32_t dataLen = 0;
- uint8_t senderAddr[4] = { 0 };
- char addr[IPNAMESIZE] = {0};
- uint16_t senderPort = 0;
-
- if (gUnicastSocket)
+ if (g_unicastSocket)
{
- dataLen = CAArduinoRecvData(gUnicastSocket, (uint8_t **)&data, COAP_MAX_PDU_SIZE, senderAddr,
- &senderPort);
- if (dataLen < 0)
+ if (CAArduinoRecvData(g_unicastSocket) != CA_STATUS_OK)
{
- OIC_LOG(ERROR, MOD_NAME, "FAILED");
+ OIC_LOG(ERROR, MOD_NAME, "rcv fail");
CAEthernetStopUnicastServer();
}
- else if (dataLen > 0)
- {
- OIC_LOG(DEBUG, MOD_NAME, "unicast data recvd");
- sprintf(addr, "%d.%d.%d.%d", senderAddr[0], senderAddr[1], senderAddr[2], senderAddr[3]);
- CAPacketReceivedCallback(addr, senderPort, data, dataLen);
- }
-
- if(data)
- {
- OICFree(data);
- data = NULL;
- }
}
- if (gMulticastSocket)
+ if (g_multicastSocket)
{
- dataLen = CAArduinoRecvData(gMulticastSocket, (uint8_t **)&data, COAP_MAX_PDU_SIZE,
- senderAddr, &senderPort);
- if (dataLen < 0)
+ if (CAArduinoRecvData(g_multicastSocket) != CA_STATUS_OK)
{
+ OIC_LOG(ERROR, MOD_NAME, "rcv fail");
CAEthernetStopMulticastServer();
}
- else if (dataLen > 0)
- {
- OIC_LOG(DEBUG, MOD_NAME, "multicast data recvd");
- sprintf(addr, "%d.%d.%d.%d", senderAddr[0], senderAddr[1], senderAddr[2], senderAddr[3]);
- CAPacketReceivedCallback(addr, senderPort, data, dataLen);
- }
-
- if(data)
- {
- OICFree(data);
- data = NULL;
- }
}
}
-/// Retrieve any available data from UDP socket. This is a non-blocking call.
-int32_t CAArduinoRecvData(int32_t sockFd, uint8_t **buf, uint32_t bufLen,
- uint8_t *senderAddr, uint16_t *senderPort)
+/** Retrieve any available data from UDP socket and call callback.
+ * This is a non-blocking call.
+ */
+CAResult_t CAArduinoRecvData(int32_t sockFd)
{
- //OIC_LOG(DEBUG, MOD_NAME, "IN");
/**Bug : When there are multiple UDP packets in Wiznet buffer, W5100.getRXReceivedSize
* will not return correct length of the first packet.
* Fix : Use the patch provided for arduino/libraries/Ethernet/utility/socket.cpp
*/
- VERIFY_NON_NULL(buf, MOD_NAME, "buf");
- VERIFY_NON_NULL(senderAddr, MOD_NAME, "senderAddr");
- VERIFY_NON_NULL(senderPort, MOD_NAME, "senderPort");
- int32_t ret = 0;
+ void *data = NULL;
+ uint8_t senderAddr[4] = { 0 };
+ char addr[IPNAMESIZE] = {0};
+ uint16_t senderPort = 0;
+
uint16_t recvLen = W5100.getRXReceivedSize(sockFd);
if (recvLen == 0)
{
- return recvLen;
+ // No data available on socket
+ return CA_STATUS_OK;
}
OIC_LOG_V(DEBUG, MOD_NAME, "rcvd %d", recvLen);
recvLen = recvLen > COAP_MAX_PDU_SIZE ? COAP_MAX_PDU_SIZE:recvLen;
- *buf = (uint8_t *)OICMalloc(recvLen + 1);
- if (NULL == *buf)
+ data = OICCalloc(recvLen + 1, 1);
+ if (NULL == data)
{
OIC_LOG(DEBUG, MOD_NAME, "Out of memory!");
- return 0;
+ return CA_MEMORY_ALLOC_FAILED;
}
- memset(*buf, 0, recvLen + 1);
+
// Read available data.
- ret = recvfrom(sockFd, *buf, bufLen, senderAddr, senderPort);
+ int32_t ret = recvfrom(sockFd, (uint8_t *)data, recvLen + 1, senderAddr, &senderPort);
+ if (ret < 0)
+ {
+ OIC_LOG(ERROR, MOD_NAME, "rcv fail");
+ OICFree(data);
+ return CA_STATUS_FAILED;
+ }
+ else if (ret > 0)
+ {
+ OIC_LOG(DEBUG, MOD_NAME, "data recvd");
+ snprintf(addr, sizeof(addr), "%d.%d.%d.%d", senderAddr[0], senderAddr[1], senderAddr[2],
+ senderAddr[3]);
+ CAPacketReceivedCallback(addr, senderPort, data, ret);
+ }
+
+ OICFree(data);
+
OIC_LOG(DEBUG, MOD_NAME, "OUT");
- return ret;
+ return CA_STATUS_OK;
}
void CAEthernetSetPacketReceiveCallback(CAEthernetPacketReceivedCallback callback)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
- gPacketReceivedCallback = callback;
+ g_packetReceivedCallback = callback;
OIC_LOG(DEBUG, MOD_NAME, "OUT");
}
}
W5100.getIPAddress(rawIPAddr);
- sprintf(address, "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2], rawIPAddr[3]);
+ snprintf(address, sizeof(address), "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2],
+ rawIPAddr[3]);
OIC_LOG_V(DEBUG, MOD_NAME, "address:%s", address);
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
}
+
* @def CA_PORT
* @brief Port to listen for incoming data
*/
-#define CA_PORT 5298
+#define CA_PORT 6298
/**
* @def CA_SECURE_PORT
} CAEthernetData;
/**
- * @var gNetworkPacketCallback
+ * @var g_networkPacketCallback
* @brief Network Packet Received Callback to CA
*/
-static CANetworkPacketReceivedCallback gNetworkPacketCallback = NULL;
+static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
/**
- * @var gNetworkChangeCb
+ * @var g_networkChangeCallback
* @brief Network Changed Callback to CA
*/
-static CANetworkChangeCallback gNetworkChangeCallback = NULL;
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
/**
- * @var gIsMulticastServerStarted
+ * @var g_isMulticastServerStarted
* @brief Flag to check if multicast server is started
*/
-static bool gIsMulticastServerStarted = false;
+static bool g_isMulticastServerStarted = false;
/**
* @var gIsStartServerCalled
* @brief Flag to check if server start requested by CA.
*/
-static bool gStartUnicastServerRequested = false;
+static bool g_startUnicastServerRequested = false;
/**
- * @var gUnicastServerport
+ * @var g_unicastServerport
* @brief port number on which unicast server is running.
*/
-static int16_t gUnicastServerport = 0;
+static uint16_t g_unicastServerport = 0;
#ifdef __WITH_DTLS__
/**
- * @var gSecureUnicastServerport
+ * @var g_secureUnicastServerport
* @brief port number on which secure unicast server is running.
*/
-static int16_t gSecureUnicastServerport = 0;
+static uint16_t g_secureUnicastServerport = 0;
#endif
/**
- * @var gIsStartServerCalled
+ * @var g_startMulticastServerRequested
* @brief Flag to check if server start requested by CA.
*/
-static bool gStartMulticastServerRequested = false;
+static bool g_startMulticastServerRequested = false;
/**
- * @var gSendQueueHandle
+ * @var g_sendQueueHandle
* @brief Queue handle for Send Data
*/
-static CAQueueingThread_t *gSendQueueHandle = NULL;
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from CA
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
static CAResult_t CAEthernetInitializeQueueHandles();
static void CAEthernetDeinitializeQueueHandles();
-static void CAEthernetNotifyNetworkChange(const char *address, const int16_t port,
+static void CAEthernetNotifyNetworkChange(const char *address, const uint16_t port,
const CANetworkStatus_t status);
static void CAEthernetConnectionStateCB(const char *ipAddress,
const CANetworkStatus_t status);
-static void CAEthernetPacketReceivedCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, const CABool_t isSecured);
+static void CAEthernetPacketReceivedCB(const char *ipAddress, const uint16_t port,
+ const void *data, const uint32_t dataLength, const bool isSecured);
#ifdef __WITH_DTLS__
-static uint32_t CAEthernetPacketSendCB(const char *ipAddress, const uint32_t port,
+static uint32_t CAEthernetPacketSendCB(const char *ipAddress, const uint16_t port,
const void *data, const uint32_t dataLength);
#endif
static CAResult_t CAEthernetStopServers();
static void CAEthernetSendDataThread(void *threadData);
-static CAEthernetData *CACreateEthernetData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+static CAEthernetData *CACreateEthernetData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
void CAFreeEthernetData(CAEthernetData *EthernetData);
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
// Check if the message queue is already initialized
- if (gSendQueueHandle)
+ if (g_sendQueueHandle)
{
- OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "Already queue is initialized!");
+ OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "send queue handle is already initialized!");
return CA_STATUS_OK;
}
// Create send message queue
- gSendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
- if (!gSendQueueHandle)
+ g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_sendQueueHandle)
{
OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Memory allocation failed!");
return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(gSendQueueHandle, gThreadPool,
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_threadPool,
CAEthernetSendDataThread, CADataDestroyer))
{
OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(gSendQueueHandle);
- gSendQueueHandle = NULL;
+ OICFree(g_sendQueueHandle);
+ g_sendQueueHandle = NULL;
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
- CAQueueingThreadDestroy(gSendQueueHandle);
- OICFree(gSendQueueHandle);
- gSendQueueHandle = NULL;
+ CAQueueingThreadDestroy(g_sendQueueHandle);
+ OICFree(g_sendQueueHandle);
+ g_sendQueueHandle = NULL;
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
}
-void CAEthernetNotifyNetworkChange(const char *address, const int16_t port,
+void CAEthernetNotifyNetworkChange(const char *address, const uint16_t port,
const CANetworkStatus_t status)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
return;
}
- if (NULL != gNetworkChangeCallback)
+ if (NULL != g_networkChangeCallback)
{
- gNetworkChangeCallback(localEndpoint, status);
+ g_networkChangeCallback(localEndpoint, status);
}
CAAdapterFreeLocalEndpoint(localEndpoint);
*/
if (CA_INTERFACE_UP == status)
{
- int16_t port = CA_PORT;
+ uint16_t port = CA_PORT;
int32_t serverFd = -1;
// Start Unicast server if requested earlier
- if (gStartUnicastServerRequested)
+ if (g_startUnicastServerRequested)
{
ret = CAEthernetStartUnicastServer("0.0.0.0", &port, false, false, &serverFd);
if (CA_STATUS_OK == ret)
{
OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Unicast server started on %d port", port);
CAEthernetSetUnicastSocket(serverFd);
- gUnicastServerport = port;
+ g_unicastServerport = port;
}
else
{
{
OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Secure Unicast server started on %d", port);
CAEthernetSetSecureUnicastSocket(serverFd);
- gSecureUnicastServerport = port;
+ g_secureUnicastServerport = port;
}
else
{
}
// Start Multicast server if requested earlier
- if (gStartMulticastServerRequested)
+ if (g_startMulticastServerRequested)
{
- int16_t multicastPort = CA_MCAST_PORT;
+ uint16_t multicastPort = CA_MCAST_PORT;
int32_t multicastFd = 0;
ret = CAEthernetStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort,
&multicastFd);
{
OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Multicast server started on %d port",
multicastPort);
- gIsMulticastServerStarted = true;
+ g_isMulticastServerStarted = true;
}
else
{
}
#ifdef __WITH_DTLS__
-uint32_t CAEthernetPacketSendCB(const char *ipAddress, const uint32_t port,
+uint32_t CAEthernetPacketSendCB(const char *ipAddress, const uint16_t port,
const void *data, const uint32_t dataLength)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
- uint32_t sentLength = CAEthernetSendData(ipAddress, port, data, dataLength, CA_FALSE, CA_TRUE);
+ uint32_t sentLength = CAEthernetSendData(ipAddress, port, data, dataLength, false, true);
- OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Successfully sent %d of encripted data!", sentLength);
+ OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Successfully sent %d of encrypted data!", sentLength);
return sentLength;
}
#endif
-void CAEthernetPacketReceivedCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, const CABool_t isSecured)
+void CAEthernetPacketReceivedCB(const char *ipAddress, const uint16_t port,
+ const void *data, const uint32_t dataLength, const bool isSecured)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Address: %s, port:%d, data:%s", ipAddress, port, data);
}
memcpy(buf, data, dataLength);
memset(buf + dataLength, 0, 1);
- if (gNetworkPacketCallback)
+ if (g_networkPacketCallback)
{
- gNetworkPacketCallback(endPoint, buf, dataLength);
+ g_networkPacketCallback(endPoint, buf, dataLength);
}
else
{
VERIFY_NON_NULL(netCallback, ETHERNET_ADAPTER_TAG, "netCallback");
VERIFY_NON_NULL(handle, ETHERNET_ADAPTER_TAG, "thread pool handle");
- gThreadPool = handle;
- gNetworkChangeCallback = netCallback;
- gNetworkPacketCallback = networkPacketCallback;
+ g_threadPool = handle;
+ g_networkChangeCallback = netCallback;
+ g_networkPacketCallback = networkPacketCallback;
- CAResult_t ret = CAEthernetInitializeNetworkMonitor(gThreadPool);
+ CAResult_t ret = CAEthernetInitializeNetworkMonitor(g_threadPool);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "Failed to initialize n/w monitor![%d]", ret);
}
CAEthernetSetConnectionStateChangeCallback(CAEthernetConnectionStateCB);
- ret = CAEthernetInitializeServer(gThreadPool);
+ ret = CAEthernetInitializeServer(g_threadPool);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "Failed to initialize server![%d]", ret);
CAConnectivityHandler_t ethernetHandler;
ethernetHandler.startAdapter = CAStartEthernet;
ethernetHandler.startListenServer = CAStartEthernetListeningServer;
- ethernetHandler.startDiscoverServer = CAStartEthernetDiscoveryServer;
+ ethernetHandler.startDiscoveryServer = CAStartEthernetDiscoveryServer;
ethernetHandler.sendData = CASendEthernetUnicastData;
ethernetHandler.sendDataToAll = CASendEthernetMulticastData;
ethernetHandler.GetnetInfo = CAGetEthernetInterfaceInformation;
}
// Start send queue thread
- if (CA_STATUS_OK != CAQueueingThreadStart(gSendQueueHandle))
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
{
OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Failed to Start Send Data Thread");
CAStopEthernet();
return CA_STATUS_FAILED;
}
- // Start send queue thread
- if (CA_STATUS_OK != CAQueueingThreadStart(gSendQueueHandle))
- {
- OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Failed to Start Send Data Thread");
- return CA_STATUS_FAILED;
- }
-
- gStartUnicastServerRequested = true;
+ g_startUnicastServerRequested = true;
bool retVal = CAEthernetIsConnected();
if (false == retVal)
{
return CA_STATUS_OK;
}
- char *ifcName;
- char *ifcAdrs;
+ char *ifcName = NULL;
+ char *ifcAdrs = NULL;
ret = CAEthernetGetInterfaceInfo(&ifcName, &ifcAdrs);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Failed to get ethernet interface info [%d]", ret);
return ret;
}
- int16_t unicastPort = CA_PORT;
+ uint16_t unicastPort = CA_PORT;
int32_t serverFd = 0;
// Address is hardcoded as we are using Single Interface
ret = CAEthernetStartUnicastServer(ifcAdrs, &unicastPort, false, false, &serverFd);
{
OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Unicast server started on %d port", unicastPort);
CAEthernetSetUnicastSocket(serverFd);
- gUnicastServerport = unicastPort;
+ g_unicastServerport = unicastPort;
}
#ifdef __WITH_DTLS__
{
OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "Secure Unicast server started on %d port", unicastPort);
CAEthernetSetSecureUnicastSocket(serverFd);
- gSecureUnicastServerport = unicastPort;
+ g_secureUnicastServerport = unicastPort;
}
#endif
OICFree(ifcAdrs);
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
- return ret;;
+ return ret;
}
CAResult_t CAStartEthernetListeningServer()
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
CAResult_t ret = CA_STATUS_OK;
- int16_t multicastPort = CA_MCAST_PORT;
+ uint16_t multicastPort = CA_MCAST_PORT;
- if (gIsMulticastServerStarted == true)
+ if (g_isMulticastServerStarted == true)
{
OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG,
"Failed to Start Multicast Server, Already Started!");
return CA_SERVER_STARTED_ALREADY;
}
- gStartMulticastServerRequested = true;
+ g_startMulticastServerRequested = true;
bool retVal = CAEthernetIsConnected();
if (false == retVal)
{
return CA_STATUS_OK;
}
- char *ifcName;
- char *ifcAdrs;
+ char *ifcName = NULL;
+ char *ifcAdrs = NULL;
ret = CAEthernetGetInterfaceInfo(&ifcName, &ifcAdrs);
if (CA_STATUS_OK != ret)
{
if (CA_STATUS_OK == ret)
{
OIC_LOG(INFO, ETHERNET_ADAPTER_TAG, "Multicast Server is Started Successfully");
- gIsMulticastServerStarted = true;
+ g_isMulticastServerStarted = true;
}
OICFree(ifcName);
OICFree(ifcAdrs);
+
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
return ret;
}
return CAStartEthernetListeningServer();
}
-uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+int32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
- uint32_t dataSize = 0;
- VERIFY_NON_NULL_RET(remoteEndpoint, ETHERNET_ADAPTER_TAG, "remoteEndpoint", dataSize);
- VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", dataSize);
- VERIFY_NON_NULL_RET(gSendQueueHandle, ETHERNET_ADAPTER_TAG, "sendQueueHandle", dataSize);
+ VERIFY_NON_NULL_RET(remoteEndpoint, ETHERNET_ADAPTER_TAG, "remoteEndpoint", -1);
+ VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", -1);
+ VERIFY_NON_NULL_RET(g_sendQueueHandle, ETHERNET_ADAPTER_TAG, "sendQueueHandle", -1);
if (0 == dataLength)
{
OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "Invalid Data Length");
- return dataSize;
+ return -1;
}
// Create EthernetData to add to queue
if (!ethernetData)
{
OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "Failed to create ethernetData!");
- return CA_MEMORY_ALLOC_FAILED;
+ return -1;
}
+ else
+ {
+ // Add message to send queue
+ CAQueueingThreadAddData(g_sendQueueHandle, ethernetData, sizeof(CAEthernetData));
- // Add message to send queue
- CAQueueingThreadAddData(gSendQueueHandle, ethernetData, sizeof(CAEthernetData));
-
- OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
- return dataLength;
+ OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+ return dataLength;
+ }
}
-uint32_t CASendEthernetMulticastData(void *data, uint32_t dataLength)
+int32_t CASendEthernetMulticastData(const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
- uint32_t dataSize = 0;
- VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", dataSize);
- VERIFY_NON_NULL_RET(gSendQueueHandle, ETHERNET_ADAPTER_TAG, "sendQueueHandle", dataSize);
+ VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", -1);
+ VERIFY_NON_NULL_RET(g_sendQueueHandle, ETHERNET_ADAPTER_TAG, "sendQueueHandle", -1);
if (0 == dataLength)
{
OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "Invalid Data Length");
- return dataSize;
+ return -1;
}
// Create EthernetData to add to queue
if (!EthernetData)
{
OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "Failed to create ethernetData!");
- return CA_MEMORY_ALLOC_FAILED;
+ return -1;
}
+ else
+ {
+ // Add message to send queue
+ CAQueueingThreadAddData(g_sendQueueHandle, EthernetData, sizeof(CAEthernetData));
- // Add message to send queue
- CAQueueingThreadAddData(gSendQueueHandle, EthernetData, sizeof(CAEthernetData));
-
- OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
- return dataLength;
+ OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+ return dataLength;
+ }
}
CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+
VERIFY_NON_NULL(info, ETHERNET_ADAPTER_TAG, "info");
VERIFY_NON_NULL(size, ETHERNET_ADAPTER_TAG, "size");
+ if (info == NULL || size == NULL)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
+
CALocalConnectivity_t *netInfo = NULL;
bool retVal = CAEthernetIsConnected();
if (false == retVal)
{
OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG,
- "Failed to get interface address, Ethernet not Connected", CA_ADAPTER_NOT_ENABLED);
+ "Failed to get interface address, Ethernet not Connected",
+ CA_ADAPTER_NOT_ENABLED);
return CA_ADAPTER_NOT_ENABLED;
}
int32_t netInfoSize = 1;
#ifdef __WITH_DTLS__
- if (gSecureUnicastServerport)
+ if (g_secureUnicastServerport)
{
- netInfoSize = 2;
+ netInfoSize++;
}
#endif
- netInfo = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t) * netInfoSize);
+ netInfo = (CALocalConnectivity_t *) OICCalloc(netInfoSize, sizeof(CALocalConnectivity_t));
VERIFY_NON_NULL_RET(netInfo, ETHERNET_ADAPTER_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
- memset(netInfo, 0, sizeof(CALocalConnectivity_t) * netInfoSize);
char *ipAddress = NULL;
char *ifcName = NULL;
return CA_MEMORY_ALLOC_FAILED;
}
- // copy unciast server information
- endpoint->isSecured = CA_FALSE;
- endpoint->addressInfo.IP.port = gUnicastServerport;
+ // copy unicast server information
+ endpoint->isSecured = false;
+ endpoint->addressInfo.IP.port = g_unicastServerport;
memcpy(&netInfo[0], endpoint, sizeof(CALocalConnectivity_t));
*size = 1;
#ifdef __WITH_DTLS__
- // copy sevure unicast server information
- if (gSecureUnicastServerport)
+ // copy secure unicast server information
+ if (g_secureUnicastServerport)
{
- endpoint->isSecured = CA_TRUE;
- endpoint->addressInfo.IP.port = gSecureUnicastServerport;
+ endpoint->isSecured = true;
+ endpoint->addressInfo.IP.port = g_secureUnicastServerport;
memcpy(&netInfo[1], endpoint, sizeof(CALocalConnectivity_t));
- *size = 2;
+ (*size)++;
}
#endif
*info = netInfo;
CAResult_t CAReadEthernetData()
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+ OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
return CA_STATUS_OK;
}
if (CA_STATUS_OK == CAEthernetStopUnicastServer())
{
CAEthernetSetUnicastSocket(-1);
- gUnicastServerport = -1;
+ g_unicastServerport = -1;
}
#ifdef __WITH_DTLS__
if (CA_STATUS_OK == CAEthernetStopSecureUnicastServer())
{
CAEthernetSetSecureUnicastSocket(-1);
- gSecureUnicastServerport = -1;
+ g_secureUnicastServerport = -1;
}
#endif
//Stop multicast server and set the state accordingly
if (CA_STATUS_OK == CAEthernetStopMulticastServer())
{
- gIsMulticastServerStarted = false;
+ g_isMulticastServerStarted = false;
}
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
- gStartUnicastServerRequested = false;
- gStartMulticastServerRequested = false;
+ g_startUnicastServerRequested = false;
+ g_startMulticastServerRequested = false;
// Stop ethernet network monitor
CAEthernetStopNetworkMonitor();
// Stop send queue thread
- if (gSendQueueHandle && CA_FALSE == gSendQueueHandle->isStop)
+ if (g_sendQueueHandle && false == g_sendQueueHandle->isStop)
{
- CAQueueingThreadStop(gSendQueueHandle);
+ CAQueueingThreadStop(g_sendQueueHandle);
}
// Stop Unicast, Secured unicast and Multicast servers running
if (NULL != ethernetData->remoteEndpoint)
{
char *address = ethernetData->remoteEndpoint->addressInfo.IP.ipAddress;
- uint32_t port = ethernetData->remoteEndpoint->addressInfo.IP.port;
+ uint16_t port = ethernetData->remoteEndpoint->addressInfo.IP.port;
#ifdef __WITH_DTLS__
if (!ethernetData->remoteEndpoint->isSecured)
}
else
{
- OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!");
- uint8_t cacheFalg = 0;
+ OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!");
+ uint8_t cacheFlag = 0;
CAResult_t result = CAAdapterNetDtlsEncrypt(address, port, ethernetData->data,
- ethernetData->dataLen, &cacheFalg, DTLS_ETHERNET);
+ ethernetData->dataLen, &cacheFlag, DTLS_ETHERNET);
if (CA_STATUS_OK != result)
{
OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt failed!");
}
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt returned with cache[%d]",
- cacheFalg);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG,
+ "CAAdapterNetDtlsEncrypt returned with cache[%d]",cacheFlag);
}
#else
CAEthernetSendData(address, port, ethernetData->data, ethernetData->dataLen, false,
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
}
-CAEthernetData *CACreateEthernetData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+CAEthernetData *CACreateEthernetData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength)
{
CAEthernetData *ethernetData = (CAEthernetData *) OICMalloc(sizeof(CAEthernetData));
CAFreeEthernetData(etdata);
}
+
* @brief Unicast port number (to listen for incoming data on unicast server).
* Note :- Actual port number may differ based on result of bind() operation.
*/
-#define CA_PORT 5298
+#define CA_PORT 6298
/**
* @def CA_SECURE_PORT
* @var gIsMulticastServerStarted
* @brief Flag to check if multicast server is started
*/
-static int gIsMulticastServerStarted = 0;
+static bool gIsMulticastServerStarted = false;
/**
* @var gIsStartServerCalled
* @var gUnicastServerport
* @brief port number on which unicast server is running.
*/
-static int16_t gUnicastServerport = 0;
+static uint16_t gUnicastServerport = 0;
/**
* @var gIsStartServerCalled
static bool gStartMulticastServerRequested = false;
-static void CAEthernetNotifyNetworkChange(const char *address, const int16_t port,
- const CANetworkStatus_t status);
+static void CAEthernetNotifyNetworkChange(const char *address, int16_t port,
+ CANetworkStatus_t status);
static void CAEthernetConnectionStateCB(const char *ipAddress,
- const CANetworkStatus_t status);
-static void CAEthernetPacketReceivedCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength);
+ CANetworkStatus_t status);
+static void CAEthernetPacketReceivedCB(const char *ipAddress, uint32_t port,
+ const void *data, uint32_t dataLength);
static CAResult_t CAEthernetStopServers();
-void CAEthernetNotifyNetworkChange(const char *address, const int16_t port,
- const CANetworkStatus_t status)
+void CAEthernetNotifyNetworkChange(const char *address, int16_t port,
+ CANetworkStatus_t status)
{
CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_ETHERNET, address);
if (!localEndpoint)
}
void CAEthernetConnectionStateCB(const char *ipAddr,
- const CANetworkStatus_t status)
+ CANetworkStatus_t status)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
* and start unicast and multicast servers if requested earlier */
if (CA_INTERFACE_UP == status)
{
- char *ipAddress = NULL;
- int16_t port = CA_PORT;
+ uint16_t port = CA_PORT;
int32_t serverFd = -1;
/* Start Unicast server if requested earlier */
if (gStartUnicastServerRequested)
}
else
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", ret);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "strt mcast srv fail:%d", ret);
}
}
+ char *ipAddress = NULL;
+ char *ifcName = NULL;
+ CAResult_t ret = CAEthernetGetInterfaceInfo(&ifcName, &ipAddress);
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "get interface info fail:%d", ret);
+ OICFree(ipAddress);
+ OICFree(ifcName);
+ return;
+ }
/* Notify network change to CA */
CAEthernetNotifyNetworkChange(ipAddress, port, status);
OICFree(ipAddress);
+ OICFree(ifcName);
}
else
{
ret = CAEthernetStopServers();
if (CA_STATUS_OK != ret)
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", ret);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "stop srv fail:%d", ret);
return;
}
}
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
}
-void CAEthernetPacketReceivedCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength)
+void CAEthernetPacketReceivedCB(const char *ipAddress, uint32_t port,
+ const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
OIC_LOG_V(DEBUG, ETHERNET_ADAPTER_TAG, "sddress:%s", ipAddress);
{
gNetworkPacketCallback(endPoint, data, dataLength);
}
- CADestroyRemoteEndpoint(endPoint);
+ CAAdapterFreeRemoteEndpoint(endPoint);
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
}
CAResult_t ret = CAEthernetInitializeNetworkMonitor();
if (CA_STATUS_OK != ret)
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", ret);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "init n/w fail:%d", ret);
return ret;
}
CAEthernetSetConnectionStateChangeCallback(CAEthernetConnectionStateCB);
ret = CAEthernetInitializeServer();
if (CA_STATUS_OK != ret)
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", ret);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "init fail:%d", ret);
CATerminateEthernet();
return ret;
}
CAConnectivityHandler_t EthernetHandler;
EthernetHandler.startAdapter = CAStartEthernet;
EthernetHandler.startListenServer = CAStartEthernetListeningServer;
- EthernetHandler.startDiscoverServer = CAStartEthernetDiscoveryServer;
+ EthernetHandler.startDiscoveryServer = CAStartEthernetDiscoveryServer;
EthernetHandler.sendData = CASendEthernetUnicastData;
EthernetHandler.sendDataToAll = CASendEthernetMulticastData;
EthernetHandler.GetnetInfo = CAGetEthernetInterfaceInformation;
CAResult_t ret = CAEthernetStartNetworkMonitor();
if (CA_STATUS_OK != ret)
{
- OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Failed");
+ OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "strt n/w monitor fail");
}
gStartUnicastServerRequested = true;
bool retVal = CAEthernetIsConnected();
if (false == retVal)
{
- OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Failed");
+ OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "not connected");
return ret;
}
- int16_t unicastPort = CA_PORT;
+ uint16_t unicastPort = CA_PORT;
int32_t serverFd = 0;
// Address is hardcoded as we are using Single Interface
ret = CAEthernetStartUnicastServer("0.0.0.0", &unicastPort, false, &serverFd);
bool retVal = CAEthernetIsConnected();
if (false == retVal)
{
- OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG,
- "No ethernet");
+ OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG,"Not connected");
return CA_ADAPTER_NOT_ENABLED;
}
return CAStartEthernetListeningServer();
}
-uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
- uint32_t dataLength)
+int32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+ uint32_t dataLength)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
- uint32_t dataSize = 0;
- VERIFY_NON_NULL_RET(remoteEndpoint, ETHERNET_ADAPTER_TAG, "remoteEndpoint", dataSize);
- VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", dataSize);
+ VERIFY_NON_NULL_RET(remoteEndpoint, ETHERNET_ADAPTER_TAG, "remoteEndpoint", -1);
+ VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", -1);
if (dataLength == 0)
{
OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Invalid length");
- return dataSize;
+ return -1;
}
CAEthernetSendData(remoteEndpoint->addressInfo.IP.ipAddress,
return dataLength;
}
-uint32_t CASendEthernetMulticastData(void *data, uint32_t dataLength)
+int32_t CASendEthernetMulticastData(const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
- uint32_t dataSize = 0;
- VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", dataSize);
+ VERIFY_NON_NULL_RET(data, ETHERNET_ADAPTER_TAG, "data", -1);
if (dataLength == 0)
{
OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Invalid length");
- return dataSize;
+ return -1;
}
CAEthernetSendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, true);
bool retVal = CAEthernetIsConnected();
if (false == retVal)
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "No ethernet", CA_ADAPTER_NOT_ENABLED);
+ OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Not connected");
return CA_ADAPTER_NOT_ENABLED;
}
char *ipAddress = NULL;
char *ifcName = NULL;
- CAResult_t ret = CAEthernetGetInterfaceInfo(&ipAddress, &ifcName);
+ CAResult_t ret = CAEthernetGetInterfaceInfo(&ifcName, &ipAddress);
if (CA_STATUS_OK != ret)
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", ret);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "get interface info fail:%d", ret);
+ OICFree(ipAddress);
+ OICFree(ifcName);
return ret;
}
(*info) = CAAdapterCreateLocalEndpoint(CA_ETHERNET, ipAddress);
if (NULL == (*info))
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "Failed",
- CA_MEMORY_ALLOC_FAILED);
+ OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "malloc fail");
OICFree(ipAddress);
OICFree(ifcName);
return CA_MEMORY_ALLOC_FAILED;
CAResult_t result = CAEthernetStopUnicastServer();
if (CA_STATUS_OK != result)
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", result);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "stop ucast srv fail:%d", result);
return result;
}
CAEthernetSetUnicastSocket(-1);
- CAEthernetSetUnicastPort(-1);
- gUnicastServerport = -1;
+ CAEthernetSetUnicastPort(0);
+ gUnicastServerport = 0;
result = CAEthernetStopMulticastServer();
if (CA_STATUS_OK != result)
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", result);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "stop mcast srv fail:%d", result);
return result;
}
gIsMulticastServerStarted = false;
CAResult_t result = CAEthernetStopServers();
if (CA_STATUS_OK != result)
{
- OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "FAILED:%d", result);
+ OIC_LOG_V(ERROR, ETHERNET_ADAPTER_TAG, "stop srv fail:%d", result);
}
OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
return;
}
+
#define ETHERNET_CLIENT_TAG "ETHERNET_CLIENT"
/**
- * @var gUnicastServerSocketDescClient
+ * @var g_unicastServerSocketDescClient
* @brief socket descriptor for unicast server
*/
-static int32_t gUnicastServerSocketDescClient = -1;
+static int32_t g_unicastServerSocketDescClient = -1;
#ifdef __WITH_DTLS__
/**
- * @var gUnicastServerSocketDescClient
+ * @var g_unicastServerSecureSocketDescClient
* @brief socket descriptor for secure unicast server
*/
-static int32_t gUnicastServerSecureSocketDescClient = -1;
+static int32_t g_unicastServerSecureSocketDescClient = -1;
#endif
-static uint32_t CASendData(const char *remoteAddress, const uint32_t port,
+static uint32_t CASendData(const char *remoteAddress, const uint16_t port,
const void *data, const uint32_t dataLength, int32_t sockfd)
{
OIC_LOG(DEBUG, ETHERNET_CLIENT_TAG, "IN");
(struct sockaddr *)&destAddr, sizeof(destAddr));
if (-1 == sendDataLength)
{
- OIC_LOG_V(ERROR, ETHERNET_CLIENT_TAG, "Failed to Send Data, Error code: %s", strerror(errno));
+ OIC_LOG_V(ERROR, ETHERNET_CLIENT_TAG, "Failed to Send Data, Error code: %s",
+ strerror(errno));
return 0;
}
- OIC_LOG_V(INFO, ETHERNET_CLIENT_TAG, "Sending data is successful, sent bytes[%d]", sendDataLength);
+ OIC_LOG_V(INFO, ETHERNET_CLIENT_TAG, "Sending data is successful, sent bytes[%d]",
+ sendDataLength);
return sendDataLength;
}
{
OIC_LOG(DEBUG, ETHERNET_CLIENT_TAG, "IN");
- gUnicastServerSocketDescClient = socketFD;
+ g_unicastServerSocketDescClient = socketFD;
}
#ifdef __WITH_DTLS__
{
OIC_LOG(DEBUG, ETHERNET_CLIENT_TAG, "IN");
- gUnicastServerSecureSocketDescClient = socketFD;
+ g_unicastServerSecureSocketDescClient = socketFD;
}
#endif
-uint32_t CAEthernetSendData(const char *remoteAddress, const uint32_t port,
+uint32_t CAEthernetSendData(const char *remoteAddress, const uint16_t port,
const void *data, const uint32_t dataLength,
- CABool_t isMulticast, CABool_t isSecured)
+ bool isMulticast, bool isSecured)
{
uint32_t len = 0;
#ifdef __WITH_DTLS__
- if (CA_TRUE == isSecured)
+ if (true == isSecured)
{
len = CASendData(remoteAddress, port,
- data, dataLength, gUnicastServerSecureSocketDescClient);
+ data, dataLength, g_unicastServerSecureSocketDescClient);
}
else
- {
#endif
+ {
len = CASendData(remoteAddress, port,
- data, dataLength, gUnicastServerSocketDescClient);
-#ifdef __WITH_DTLS__
+ data, dataLength, g_unicastServerSocketDescClient);
}
-#endif
+
return len;
}
+
#include "umutex.h"
#include "logger.h"
#include "oic_malloc.h"
+#include "oic_string.h"
#define ETHERNET_MONITOR_TAG "ETHERNET_MONITOR"
static CANetworkStatus_t nwConnectivityStatus;
/**
- * @var gEthernetNetInfoMutex
+ * @var g_ethernetNetInfoMutex
* @brief Mutex for synchronizing access to cached interface and IP address information.
*/
-static u_mutex gEthernetNetInfoMutex = NULL;
+static u_mutex g_ethernetNetInfoMutex = NULL;
/**
- * @var gEthernetInterfaceName
+ * @var g_ethernetInterfaceName
* @brief Maintains interface name.
*/
-static char *gEthernetInterfaceName = NULL;
+static char *g_ethernetInterfaceName = NULL;
/**
- * @var gEthernetIPAddress
+ * @var g_ethernetIPAddress
* @brief Maintains interface IP address.
*/
-static char *gEthernetIPAddress = NULL;
+static char *g_ethernetIPAddress = NULL;
/**
- * @var gEthernetSubnetMask
+ * @var g_ethernetSubnetMask
* @brief Maintains interface subnetmask.
*/
-static char *gEthernetSubnetMask = NULL;
+static char *g_ethernetSubnetMask = NULL;
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from adapter
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
/**
- * @var gStopNetworkMonitor
+ * @var g_stopNetworkMonitor
* @brief Flag to control the Network Monitor Thread
*/
-static bool gStopNetworkMonitor = false;
+static bool g_stopNetworkMonitor = false;
/**
- * @var gNetworkChangeCb
+ * @var g_networkChangeCb
* @brief Maintains network connection state change callback.
*/
-static CAEthernetConnectionStateChangeCallback gNetworkChangeCb = NULL;
+static CAEthernetConnectionStateChangeCallback g_networkChangeCb = NULL;
/**
* @fn CAEthernetGetInterfaceInformation
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "IN");
- gThreadPool = threadPool;
+ g_threadPool = threadPool;
- if (!gEthernetNetInfoMutex)
+ if (!g_ethernetNetInfoMutex)
{
- gEthernetNetInfoMutex = u_mutex_new();
+ g_ethernetNetInfoMutex = u_mutex_new();
}
- u_mutex_lock(gEthernetNetInfoMutex);
- CAEthernetGetInterfaceInformation(&gEthernetInterfaceName, &gEthernetIPAddress,
- &gEthernetSubnetMask);
- u_mutex_unlock(gEthernetNetInfoMutex);
+ u_mutex_lock(g_ethernetNetInfoMutex);
+ CAEthernetGetInterfaceInformation(&g_ethernetInterfaceName, &g_ethernetIPAddress,
+ &g_ethernetSubnetMask);
+ u_mutex_unlock(g_ethernetNetInfoMutex);
- nwConnectivityStatus = (gEthernetIPAddress) ? CA_INTERFACE_UP : CA_INTERFACE_DOWN;
+ nwConnectivityStatus = (g_ethernetIPAddress) ? CA_INTERFACE_UP : CA_INTERFACE_DOWN;
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "IN");
- gThreadPool = NULL;
+ g_threadPool = NULL;
- if (gEthernetInterfaceName)
+ if (g_ethernetInterfaceName)
{
- OICFree(gEthernetInterfaceName);
- gEthernetInterfaceName = NULL;
+ OICFree(g_ethernetInterfaceName);
+ g_ethernetInterfaceName = NULL;
}
- if (gEthernetIPAddress)
+ if (g_ethernetIPAddress)
{
- OICFree(gEthernetIPAddress);
- gEthernetIPAddress = NULL;
+ OICFree(g_ethernetIPAddress);
+ g_ethernetIPAddress = NULL;
}
- if (gEthernetSubnetMask)
+ if (g_ethernetSubnetMask)
{
- OICFree(gEthernetSubnetMask);
- gEthernetSubnetMask = NULL;
+ OICFree(g_ethernetSubnetMask);
+ g_ethernetSubnetMask = NULL;
}
- if (gEthernetNetInfoMutex)
+ if (g_ethernetNetInfoMutex)
{
- u_mutex_free(gEthernetNetInfoMutex);
- gEthernetNetInfoMutex = NULL;
+ u_mutex_free(g_ethernetNetInfoMutex);
+ g_ethernetNetInfoMutex = NULL;
}
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "IN");
- u_mutex_lock(gEthernetNetInfoMutex);
- gStopNetworkMonitor = false;
- u_mutex_unlock(gEthernetNetInfoMutex);
+ g_stopNetworkMonitor = false;
- if (gStopNetworkMonitor)
+ if (g_stopNetworkMonitor)
{
OIC_LOG_V(ERROR, ETHERNET_MONITOR_TAG, "Stop network monitor requested");
return CA_STATUS_FAILED;
}
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, (void *) CANetworkMonitorThread,
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, (void *) CANetworkMonitorThread,
(void *)NULL))
{
OIC_LOG(ERROR, ETHERNET_MONITOR_TAG, "[ThreadPool] thread_pool_add_task failed!");
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "IN");
- if (gStopNetworkMonitor)
+ if (g_stopNetworkMonitor)
{
OIC_LOG(DEBUG, ETHERNET_MONITOR_TAG, "CAEthernetStopNetworkMonitor, already stopped!");
return CA_STATUS_OK;
}
- u_mutex_lock(gEthernetNetInfoMutex);
- gStopNetworkMonitor = true;
- u_mutex_unlock(gEthernetNetInfoMutex);
+ g_stopNetworkMonitor = true;
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(ipAddress, ETHERNET_MONITOR_TAG, "ip address");
// Get the interface and ipaddress information from cache
- u_mutex_lock(gEthernetNetInfoMutex);
- if (gEthernetInterfaceName == NULL || gEthernetIPAddress == NULL)
+ u_mutex_lock(g_ethernetNetInfoMutex);
+ if (g_ethernetInterfaceName == NULL || g_ethernetIPAddress == NULL)
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "Network not enabled");
+
+ u_mutex_unlock(g_ethernetNetInfoMutex);
return CA_ADAPTER_NOT_ENABLED;
}
- *interfaceName = (gEthernetInterfaceName) ? strndup(gEthernetInterfaceName,
- strlen(gEthernetInterfaceName)) : NULL;
- *ipAddress = (gEthernetIPAddress) ? strndup(gEthernetIPAddress, strlen(gEthernetIPAddress))
+ *interfaceName = (g_ethernetInterfaceName) ? strndup(g_ethernetInterfaceName,
+ strlen(g_ethernetInterfaceName)) : NULL;
+ *ipAddress = (g_ethernetIPAddress) ? OICStrdup((const char *)g_ethernetIPAddress)
: NULL;
- u_mutex_unlock(gEthernetNetInfoMutex);
+ u_mutex_unlock(g_ethernetNetInfoMutex);
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(subnetMask, ETHERNET_MONITOR_TAG, "subnet mask");
- u_mutex_lock(gEthernetNetInfoMutex);
- if (NULL == gEthernetSubnetMask)
+ u_mutex_lock(g_ethernetNetInfoMutex);
+ if (NULL == g_ethernetSubnetMask)
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "There is no subnet mask information!");
+
+ u_mutex_unlock(g_ethernetNetInfoMutex);
return CA_STATUS_FAILED;
}
- *subnetMask = (gEthernetSubnetMask) ? strndup(gEthernetSubnetMask, strlen(gEthernetSubnetMask))
+ *subnetMask = (g_ethernetSubnetMask) ?
+ strndup(g_ethernetSubnetMask, strlen(g_ethernetSubnetMask))
: NULL;
- u_mutex_unlock(gEthernetNetInfoMutex);
+ u_mutex_unlock(g_ethernetNetInfoMutex);
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "IN");
- if (CA_INTERFACE_DOWN == nwConnectivityStatus)
+ if (CA_INTERFACE_DOWN == nwConnectivityStatus) {
+ OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
+
return false;
+ }
+
+ OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
return true;
}
-void CAEthernetSetConnectionStateChangeCallback(CAEthernetConnectionStateChangeCallback callback)
+void CAEthernetSetConnectionStateChangeCallback
+ (CAEthernetConnectionStateChangeCallback callback)
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "IN");
- gNetworkChangeCb = callback;
+ g_networkChangeCb = callback;
+
+ OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
}
-void CAEthernetGetInterfaceInformation(char **interfaceName, char **ipAddress, char **subnetMask)
+void CAEthernetGetInterfaceInformation(char **interfaceName,
+ char **ipAddress, char **subnetMask)
{
- struct ifaddrs *ifa = NULL;
- struct ifaddrs *ifp = NULL;
- const char *matchName = "eth";
-
if (!interfaceName || !ipAddress || !subnetMask)
{
- OIC_LOG(ERROR, ETHERNET_MONITOR_TAG, "Invalid input: interface/ipaddress holder is NULL!");
+ OIC_LOG(ERROR, ETHERNET_MONITOR_TAG, "Invalid input: interface/ipaddress/subnet mask holder is NULL!");
return;
}
+ struct ifaddrs *ifp = NULL;
if (-1 == getifaddrs(&ifp))
{
OIC_LOG_V(ERROR, ETHERNET_MONITOR_TAG, "Failed to get interface list!, Error code: %s",
return;
}
+ struct ifaddrs *ifa = NULL;
for (ifa = ifp; ifa; ifa = ifa->ifa_next)
{
char interfaceAddress[CA_IPADDR_SIZE];
continue;
}
- if (!strncasecmp(ifa->ifa_name, matchName, strlen(matchName)))
+ const char matchName[] = "eth";
+ int matchNameLen = strlen(matchName);
+ if (!strncasecmp(ifa->ifa_name, matchName, matchNameLen))
{
// get the interface ip address
if (0 != getnameinfo(ifa->ifa_addr, len, interfaceAddress,
{
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "IN");
- while (!gStopNetworkMonitor)
+ while (!g_stopNetworkMonitor)
{
// Get network information
- CANetworkStatus_t currNetworkStatus;
char *interfaceName = NULL;
char *ipAddress = NULL;
char *subnetMask = NULL;
CAEthernetGetInterfaceInformation(&interfaceName, &ipAddress, &subnetMask);
// check current network status
+ CANetworkStatus_t currNetworkStatus;
currNetworkStatus = (ipAddress) ? CA_INTERFACE_UP : CA_INTERFACE_DOWN;
// if network status is changed
if (currNetworkStatus != nwConnectivityStatus)
{
// set current network information
- u_mutex_lock(gEthernetNetInfoMutex);
+ u_mutex_lock(g_ethernetNetInfoMutex);
nwConnectivityStatus = currNetworkStatus;
- OICFree(gEthernetInterfaceName);
- OICFree(gEthernetIPAddress);
- OICFree(gEthernetSubnetMask);
- gEthernetInterfaceName = (interfaceName) ? strndup(interfaceName, strlen(interfaceName)) : NULL;
- gEthernetIPAddress = (ipAddress) ? strndup(ipAddress, strlen(ipAddress)) : NULL;
- gEthernetSubnetMask = (subnetMask) ? strndup(subnetMask, strlen(subnetMask)) : NULL;
+ OICFree(g_ethernetInterfaceName);
+ OICFree(g_ethernetIPAddress);
+ OICFree(g_ethernetSubnetMask);
+ g_ethernetInterfaceName =
+ (interfaceName) ? strndup(interfaceName, strlen(interfaceName)) : NULL;
+ g_ethernetIPAddress = (ipAddress) ? strndup(ipAddress, strlen(ipAddress)) : NULL;
+ g_ethernetSubnetMask = (subnetMask) ? strndup(subnetMask, strlen(subnetMask)) : NULL;
- u_mutex_unlock(gEthernetNetInfoMutex);
+ u_mutex_unlock(g_ethernetNetInfoMutex);
- if (gNetworkChangeCb)
+ if (g_networkChangeCb)
{
- gNetworkChangeCb(gEthernetIPAddress, nwConnectivityStatus);
+ g_networkChangeCb(g_ethernetIPAddress, nwConnectivityStatus);
}
}
OICFree(interfaceName);
OIC_LOG_V(DEBUG, ETHERNET_MONITOR_TAG, "OUT");
}
+
#include "caadapternetdtls.h"
#endif
#include "umutex.h"
+#include "oic_malloc.h"
/**
* @def ETHERNET_SERVER_TAG
#define IPNAMESIZE 16
/**
- * @var gUnicastServerSocketFD
+ * @var g_unicastServerSocketFD
* @brief Unicast server socket descriptor
*/
-static int32_t gUnicastServerSocketFD = -1;
+static int32_t g_unicastServerSocketFD = -1;
/**
- * @var gMutexUnicastServer
+ * @var g_mutexUnicastServer
* @brief Mutex to synchronize unicast server
*/
-static u_mutex gMutexUnicastServer = NULL;
+static u_mutex g_mutexUnicastServer = NULL;
/**
- * @var gStopUnicast
+ * @var g_stopUnicast
* @brief Flag to control the Receive Unicast Data Thread
*/
-static bool gStopUnicast = false;
+static bool g_stopUnicast = false;
/**
- * @var gMulticastServerSocketFD
+ * @var g_multicastServerSocketFD
* @brief socket descriptor for multicast server
*/
-static int32_t gMulticastServerSocketFD = -1;
+static int32_t g_multicastServerSocketFD = -1;
/**
- * @var gMutexMulticastServer
+ * @var g_mutexMulticastServer
* @brief Mutex to synchronize secure multicast server
*/
-static u_mutex gMutexMulticastServer = NULL;
+static u_mutex g_mutexMulticastServer = NULL;
/**
- * @var gStopMulticast
+ * @var g_stopMulticast
* @brief Flag to control the Receive Multicast Data Thread
*/
-static bool gStopMulticast = false;
+static bool g_stopMulticast = false;
#ifdef __WITH_DTLS__
/**
- * @var gSecureUnicastServerSocketFD
+ * @var g_secureUnicastServerSocketFD
* @brief Secure unicast server socket descriptor
*/
-static int32_t gSecureUnicastServerSocketFD = -1;
+static int32_t g_secureUnicastServerSocketFD = -1;
/**
- * @var gMutexSecureUnicastServer
+ * @var g_mutexSecureUnicastServer
* @brief Mutex to synchronize secure unicast server
*/
-static u_mutex gMutexSecureUnicastServer = NULL;
+static u_mutex g_mutexSecureUnicastServer = NULL;
/**
- * @var gStopSecureUnicast
+ * @var g_stopSecureUnicast
* @brief Flag to control the unicast secure data receive thread
*/
-static bool gStopSecureUnicast = false;
+static bool g_stopSecureUnicast = false;
#endif
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from adapter
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
/**
- * @var gMulticastServerInterface
+ * @var g_multicastServerInterface
* @brief Local interface on which multicast server is running
*/
-static char gMulticastServerInterface[IPNAMESIZE];
+static char g_multicastServerInterface[IPNAMESIZE];
/**
- * @var gMulticastMemberReq
+ * @var g_multicastMemberReq
* @brief ip_mreq structure passed to join a multicast group
*/
-static struct ip_mreq gMulticastMemberReq;
+static struct ip_mreq g_multicastMemberReq;
/**
- * @var gPacketReceivedCallback
+ * @var g_packetReceivedCallback
* @brief Callback for notifying the upper layer on receival data from remote OIC device
*/
-static CAEthernetPacketReceivedCallback gPacketReceivedCallback = NULL;
+static CAEthernetPacketReceivedCallback g_packetReceivedCallback = NULL;
/**
- * @var gExceptionCallback
+ * @var g_exceptionCallback
* @brief Callback for notifying the upper layer when unicast/multicast server encounters exception
*/
-static CAEthernetExceptionCallback gExceptionCallback = NULL;
+static CAEthernetExceptionCallback g_exceptionCallback = NULL;
/**
@brief Thread context information for unicast, multicast and secured unicast server
int32_t ret = select(ctx->socket_fd + 1, &reads, NULL, NULL, &timeout);
if (*(ctx->stopFlag) == true)
{
- OIC_LOG_V(DEBUG, ETHERNET_SERVER_TAG, "Stop request received for [%d] server", ctx->type);
+ OIC_LOG_V(DEBUG, ETHERNET_SERVER_TAG,
+ "Stop request received for [%d] server", ctx->type);
break;
}
struct sockaddr_in srcSockAddress;
int32_t recvLen;
socklen_t srcAddressLen = sizeof(srcSockAddress);
- if (-1 == (recvLen = recvfrom(ctx->socket_fd, recvBuffer,
+
+ recvLen = recvfrom(ctx->socket_fd, recvBuffer,
sizeof(recvBuffer), 0, (struct sockaddr *) &srcSockAddress,
- &srcAddressLen)))
+ &srcAddressLen);
+
+ if (-1 == recvLen)
{
OIC_LOG_V(DEBUG, ETHERNET_SERVER_TAG, "%s", strerror(errno));
continue;
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Server socket shutdown [%d]!", ctx->type);
// Notify upper layer this exception
- if (gExceptionCallback)
+ if (g_exceptionCallback)
{
- gExceptionCallback(ctx->type);
+ g_exceptionCallback(ctx->type);
}
OICFree(ctx);
ctx = NULL;
return;
}
- const char *srcIPAddress = NULL;
- int32_t srcPort = -1;
-
- srcIPAddress = inet_ntoa(srcSockAddress.sin_addr);
+ char srcIPAddress[CA_IPADDR_SIZE] = {0};
+ inet_ntop(AF_INET, &srcSockAddress.sin_addr.s_addr, srcIPAddress, sizeof(srcIPAddress));
+ uint16_t srcPort = 0;
srcPort = ntohs(srcSockAddress.sin_port);
OIC_LOG_V(DEBUG, ETHERNET_SERVER_TAG, "Received packet from %s:%d\n",
continue;
}
- if (!CAAdapterIsSameSubnet(gMulticastServerInterface, srcIPAddress, netMask))
+ if (!CAAdapterIsSameSubnet(g_multicastServerInterface, srcIPAddress, netMask))
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "Packet received from different subnet, Ignore!");
if (NULL != netMask)
case CA_UNICAST_SERVER:
case CA_MULTICAST_SERVER:
// Notify data to upper layer
- if (gPacketReceivedCallback)
+ if (g_packetReceivedCallback)
{
- gPacketReceivedCallback(srcIPAddress, srcPort, recvBuffer, recvLen, false);
+ g_packetReceivedCallback(srcIPAddress, srcPort, recvBuffer, recvLen, false);
}
break;
#ifdef __WITH_DTLS__
srcPort,
(uint8_t *)recvBuffer,
recvLen, DTLS_ETHERNET);
- OIC_LOG_V(DEBUG, ETHERNET_SERVER_TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
+ OIC_LOG_V(DEBUG, ETHERNET_SERVER_TAG,
+ "CAAdapterNetDtlsDecrypt returns [%d]", ret);
}
break;
#endif //__WITH_DTLS__
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
}
-static CAResult_t CACreateSocket(int32_t *socketFD, const char *localIp, int16_t *port,
- const bool forceStart)
+static CAResult_t CACreateSocket(int32_t *socketFD, const char *localIp, uint16_t *port,
+ bool forceStart)
{
int32_t sock = -1;
// Create a UDP socket
- if (-1 == (sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)))
+ sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
+ if (-1 == sock)
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Failed to create Socket, Error code: %s",
strerror(errno));
struct sockaddr_in sockAddr;
bool isBound = false;
- int16_t serverPort = *port;
+ uint16_t serverPort = *port;
- memset((char *) &sockAddr, 0, sizeof(sockAddr));
+ memset(&sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(serverPort);
if (localIp)
static CAResult_t CACloseSocket(int32_t *socketFD)
{
+ if (socketFD == NULL)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
+
if (-1 == *socketFD)
{
OIC_LOG(INFO, ETHERNET_SERVER_TAG, "Server not running");
return CA_STATUS_OK;
}
-static CAResult_t CAStartUnicastServer(const char *localAddress, int16_t *port,
+static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port,
const bool forceStart, bool isSecured, int32_t *serverFD)
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
+ if (serverFD == NULL)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
+
CAResult_t ret = CACreateSocket(serverFD, localAddress, port, forceStart);
if (CA_STATUS_OK != ret)
{
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopUnicast;
+ ctx->stopFlag = &g_stopUnicast;
ctx->socket_fd = *serverFD;
ctx->type = isSecured ? CA_SECURED_UNICAST_SERVER : CA_UNICAST_SERVER;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CAReceiveHandler, (void *)ctx))
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CAReceiveHandler, (void *)ctx))
{
OIC_LOG(ERROR, ETHERNET_SERVER_TAG, "Failed to create read thread!");
- OICFree((void *)ctx);
+ OICFree(ctx);
close(*serverFD);
+ *serverFD = -1;
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
- if (gMutexUnicastServer)
+ if (g_mutexUnicastServer)
{
- u_mutex_free(gMutexUnicastServer);
- gMutexUnicastServer = NULL;
+ u_mutex_free(g_mutexUnicastServer);
+ g_mutexUnicastServer = NULL;
}
#ifdef __WITH_DTLS__
- if (gMutexSecureUnicastServer)
+ if (g_mutexSecureUnicastServer)
{
- u_mutex_free(gMutexSecureUnicastServer);
- gMutexSecureUnicastServer = NULL;
+ u_mutex_free(g_mutexSecureUnicastServer);
+ g_mutexSecureUnicastServer = NULL;
}
#endif
- if (gMutexMulticastServer)
+ if (g_mutexMulticastServer)
{
- u_mutex_free(gMutexMulticastServer);
- gMutexMulticastServer = NULL;
+ u_mutex_free(g_mutexMulticastServer);
+ g_mutexMulticastServer = NULL;
}
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
- gMutexUnicastServer = u_mutex_new();
- if (!gMutexUnicastServer)
+ if(g_mutexUnicastServer) {
+ OIC_LOG(ERROR, ETHERNET_SERVER_TAG, "mutex is already created!");
+
+ OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
+ return CA_STATUS_FAILED;
+ }
+
+ g_mutexUnicastServer = u_mutex_new();
+ if (!g_mutexUnicastServer)
{
OIC_LOG(ERROR, ETHERNET_SERVER_TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
#ifdef __WITH_DTLS__
- gMutexSecureUnicastServer = u_mutex_new();
- if (!gMutexSecureUnicastServer)
+ g_mutexSecureUnicastServer = u_mutex_new();
+ if (!g_mutexSecureUnicastServer)
{
OIC_LOG(ERROR, ETHERNET_SERVER_TAG, "Failed to created mutex!");
}
#endif
- gMutexMulticastServer = u_mutex_new();
- if (!gMutexMulticastServer)
+ g_mutexMulticastServer = u_mutex_new();
+ if (!g_mutexMulticastServer)
{
OIC_LOG(ERROR, ETHERNET_SERVER_TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
- gThreadPool = threadPool;
+ g_threadPool = threadPool;
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
- gThreadPool = NULL;
+ g_threadPool = NULL;
// Destroy mutex
CAEthernetServerDestroyMutex();
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
}
-CAResult_t CAEthernetStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, const bool isSecured,
- int32_t *serverFD)
+CAResult_t CAEthernetStartUnicastServer(const char *localAddress, uint16_t *port,
+ bool forceStart, bool isSecured, int32_t *serverFD)
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
}
*serverFD = -1;
- if (CA_FALSE == isSecured)
+ if (false == isSecured)
{
- u_mutex_lock(gMutexUnicastServer);
- if (-1 != gUnicastServerSocketFD)
+ u_mutex_lock(g_mutexUnicastServer);
+ if (-1 != g_unicastServerSocketFD)
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Unicast Server is Started Already!",
CA_SERVER_STARTED_ALREADY);
- *serverFD = gUnicastServerSocketFD;
- u_mutex_unlock(gMutexUnicastServer);
+ *serverFD = g_unicastServerSocketFD;
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_SERVER_STARTED_ALREADY;
}
- gStopUnicast = false;
+ g_stopUnicast = false;
if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
- &gUnicastServerSocketFD))
+ &g_unicastServerSocketFD))
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Failed to start unicast server!");
- gUnicastServerSocketFD = -1;
- u_mutex_unlock(gMutexUnicastServer);
+ g_unicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gUnicastServerSocketFD;
- u_mutex_unlock(gMutexUnicastServer);
+ *serverFD = g_unicastServerSocketFD;
+ u_mutex_unlock(g_mutexUnicastServer);
}
#ifdef __WITH_DTLS__
else // Start unicast server for secured communication
{
- u_mutex_lock(gMutexSecureUnicastServer);
- if (-1 != gSecureUnicastServerSocketFD)
+ u_mutex_lock(g_mutexSecureUnicastServer);
+ if (-1 != g_secureUnicastServerSocketFD)
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Unicast Server is Started Already!",
CA_SERVER_STARTED_ALREADY);
- *serverFD = gSecureUnicastServerSocketFD;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ *serverFD = g_secureUnicastServerSocketFD;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
return CA_SERVER_STARTED_ALREADY;
}
- gStopSecureUnicast = false;
+ g_stopSecureUnicast = false;
if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
- &gSecureUnicastServerSocketFD))
+ &g_secureUnicastServerSocketFD))
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Failed to start unicast server!");
- gSecureUnicastServerSocketFD = -1;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ g_secureUnicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gSecureUnicastServerSocketFD;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ *serverFD = g_secureUnicastServerSocketFD;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
}
#endif
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
return CA_STATUS_OK;
}
-CAResult_t CAEthernetStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD)
+CAResult_t CAEthernetStartMulticastServer(const char *localAddress,
+ const char *multicastAddress, const uint16_t multicastPort, int32_t *serverFD)
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
VERIFY_NON_NULL(multicastAddress, ETHERNET_SERVER_TAG, "port");
VERIFY_NON_NULL(serverFD, ETHERNET_SERVER_TAG, "server socket FD");
- int16_t port = multicastPort;
+ uint16_t port = multicastPort;
if (0 >= port)
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Invalid input: Multicast port is invalid!");
return CA_STATUS_INVALID_PARAM;
}
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
- if (gMulticastServerSocketFD != -1)
+ if (g_multicastServerSocketFD != -1)
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Multicast Server is already running!");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_SERVER_STARTED_ALREADY;
}
- CAResult_t ret = CACreateSocket(&gMulticastServerSocketFD, multicastAddress, &port, true);
+ CAResult_t ret = CACreateSocket(&g_multicastServerSocketFD, multicastAddress, &port, true);
if (ret != CA_STATUS_OK)
{
OIC_LOG(ERROR, ETHERNET_SERVER_TAG, "Failed to create multicast socket");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return ret;
}
// Add membership to receiving socket (join group)
- memset(&gMulticastMemberReq, 0, sizeof(struct ip_mreq));
- gMulticastMemberReq.imr_interface.s_addr = inet_addr(localAddress);
- inet_aton(multicastAddress, &gMulticastMemberReq.imr_multiaddr);
+ memset(&g_multicastMemberReq, 0, sizeof(struct ip_mreq));
+ g_multicastMemberReq.imr_interface.s_addr = inet_addr(localAddress);
+ inet_aton(multicastAddress, &g_multicastMemberReq.imr_multiaddr);
- if (-1 == setsockopt(gMulticastServerSocketFD, IPPROTO_IP, IP_ADD_MEMBERSHIP,
- (char *) &gMulticastMemberReq,
+ if (-1 == setsockopt(g_multicastServerSocketFD, IPPROTO_IP, IP_ADD_MEMBERSHIP,
+ (char *) &g_multicastMemberReq,
sizeof(struct ip_mreq)))
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Failed to add to multicast group, Error code: %s\n",
strerror(errno));
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
- u_mutex_unlock(gMutexMulticastServer);
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_STATUS_FAILED;
}
if (!ctx)
{
OIC_LOG(ERROR, ETHERNET_SERVER_TAG, "Out of memory!");
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopMulticast;
- ctx->socket_fd = gMulticastServerSocketFD;
+ ctx->stopFlag = &g_stopMulticast;
+ ctx->socket_fd = g_multicastServerSocketFD;
ctx->type = CA_MULTICAST_SERVER;
- gStopMulticast = false;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CAReceiveHandler, (void *)ctx))
+ g_stopMulticast = false;
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CAReceiveHandler, (void *)ctx))
{
OIC_LOG(ERROR, ETHERNET_SERVER_TAG, "thread_pool_add_task failed!");
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
- gStopMulticast = true;
- u_mutex_unlock(gMutexMulticastServer);
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
+ g_stopMulticast = true;
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gMulticastServerSocketFD;
- strncpy(gMulticastServerInterface, localAddress, IPNAMESIZE);
- u_mutex_unlock(gMutexMulticastServer);
+ *serverFD = g_multicastServerSocketFD;
+ strncpy(g_multicastServerInterface, localAddress, IPNAMESIZE);
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
- u_mutex_lock(gMutexUnicastServer);
- gStopUnicast = true;
- CAResult_t ret = CACloseSocket(&gUnicastServerSocketFD);
- u_mutex_unlock(gMutexUnicastServer);
+ u_mutex_lock(g_mutexUnicastServer);
+ g_stopUnicast = true;
+ CAResult_t ret = CACloseSocket(&g_unicastServerSocketFD);
+ u_mutex_unlock(g_mutexUnicastServer);
OIC_LOG_V(INFO, ETHERNET_SERVER_TAG, "Unicast server stopped [%d]", ret);
return ret;
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
- u_mutex_lock(gMutexSecureUnicastServer);
- gStopSecureUnicast = true;
- CAResult_t ret = CACloseSocket(&gSecureUnicastServerSocketFD);
- u_mutex_unlock(gMutexSecureUnicastServer);
+ u_mutex_lock(g_mutexSecureUnicastServer);
+ g_stopSecureUnicast = true;
+ CAResult_t ret = CACloseSocket(&g_secureUnicastServerSocketFD);
+ u_mutex_unlock(g_mutexSecureUnicastServer);
OIC_LOG_V(INFO, ETHERNET_SERVER_TAG, "Secured unicast server stopped [%d]", ret);
return ret;
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
- if (gMulticastServerSocketFD == -1)
+ if (g_multicastServerSocketFD == -1)
{
OIC_LOG(INFO, ETHERNET_SERVER_TAG, "Multicast server is not yet started");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_SERVER_NOT_STARTED;
}
- gStopMulticast = true;
+ g_stopMulticast = true;
// leave the group after you are done
- if (-1 == setsockopt(gMulticastServerSocketFD, IPPROTO_IP, IP_DROP_MEMBERSHIP,
- (char *)&gMulticastMemberReq,
+ if (-1 == setsockopt(g_multicastServerSocketFD, IPPROTO_IP, IP_DROP_MEMBERSHIP,
+ (char *)&g_multicastMemberReq,
sizeof(struct ip_mreq)))
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Failed to leave multicast group, Error code: %s\n",
strerror(errno));
}
- CAResult_t ret = CACloseSocket(&gMulticastServerSocketFD);
- u_mutex_unlock(gMutexMulticastServer);
+ CAResult_t ret = CACloseSocket(&g_multicastServerSocketFD);
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG_V(INFO, ETHERNET_SERVER_TAG, "Multicast server stopped [%d]", ret);
return ret;
}
-CAResult_t CAEthernetGetUnicastServerInfo(const bool isSecured, char **ipAddress, int16_t *port,
- int32_t *serverFD)
+CAResult_t CAEthernetGetUnicastServerInfo(bool isSecured,
+ char **ipAddress, uint16_t *port, int32_t *serverFD)
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
struct sockaddr_in sockAddr;
socklen_t len = sizeof(struct sockaddr_in);
- if (-1 == getsockname(gUnicastServerSocketFD, (struct sockaddr *)&sockAddr, &len))
+ if (-1 == getsockname(g_unicastServerSocketFD, (struct sockaddr *)&sockAddr, &len))
{
OIC_LOG_V(ERROR, ETHERNET_SERVER_TAG, "Failed in getsockname [%s]!", strerror(errno));
return CA_STATUS_FAILED;
*ipAddress = (serverAddress) ? strndup(serverAddress, strlen(serverAddress)) : NULL;
*port = ntohs(sockAddr.sin_port);
#ifdef __WITH_DTLS__
- *serverFD = (CA_TRUE == isSecured) ? gSecureUnicastServerSocketFD : gUnicastServerSocketFD;
+ *serverFD = (true == isSecured) ? g_secureUnicastServerSocketFD : g_unicastServerSocketFD;
#else
- *serverFD = gUnicastServerSocketFD;
+ *serverFD = g_unicastServerSocketFD;
#endif
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
void CAEthernetSetPacketReceiveCallback(CAEthernetPacketReceivedCallback callback)
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
- gPacketReceivedCallback = callback;
+ g_packetReceivedCallback = callback;
+ OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
}
void CAEthernetSetExceptionCallback(CAEthernetExceptionCallback callback)
{
OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "IN");
- gExceptionCallback = callback;
+ g_exceptionCallback = callback;
+ OIC_LOG(DEBUG, ETHERNET_SERVER_TAG, "OUT");
}
+
#define WIFI_CLIENT_TAG "WIFI_CLIENT"
/**
- * @var gUnicastServerSocketDescClient
+ * @var g_unicastServerSocket
* @brief socket descriptor for unicast server
*/
-static int32_t gUnicastServerSocketDescClient = -1;
+static int32_t g_unicastServerSocket = -1;
#ifdef __WITH_DTLS__
/**
- * @var gUnicastServerSocketDescClient
+ * @var g_unicastServerSecureSocket
* @brief socket descriptor for secure unicast server
*/
-static int32_t gUnicastServerSecureSocketDescClient = -1;
+static int32_t g_unicastServerSecureSocket = -1;
#endif
-static uint32_t CASendData(const char *remoteAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, int32_t sockfd)
+static uint32_t CASendData(const char *remoteAddress, uint16_t port,
+ const void *data, uint32_t dataLength, int sockfd)
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
return 0;
}
- struct sockaddr_in destAddr;
- memset((char *)&destAddr, 0, sizeof(destAddr));
+ struct sockaddr_in destAddr = {};
destAddr.sin_family = AF_INET;
destAddr.sin_port = htons(port);
return sendDataLength;
}
-void CAWiFiSetUnicastSocket(const int32_t socketFD)
+void CAWiFiSetUnicastSocket(int socketFD)
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
- gUnicastServerSocketDescClient = socketFD;
+ g_unicastServerSocket = socketFD;
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT");
}
#ifdef __WITH_DTLS__
-void CAWiFiSetSecureUnicastSocket(const int32_t socketFD)
+void CAWiFiSetSecureUnicastSocket(int socketFD)
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
- gUnicastServerSecureSocketDescClient = socketFD;
+ g_unicastServerSecureSocket = socketFD;
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT");
}
#endif
-uint32_t CAWiFiSendData(const char *remoteAddress, const uint32_t port,
- const void *data, const uint32_t dataLength,
- CABool_t isMulticast, CABool_t isSecured)
+uint32_t CAWiFiSendData(const char *remoteAddress, uint16_t port,
+ const void *data, uint32_t dataLength,
+ bool isMulticast, bool isSecured)
{
uint32_t len = 0;
#ifdef __WITH_DTLS__
- if (CA_TRUE == isSecured)
+ if (true == isSecured)
{
len = CASendData(remoteAddress, port,
- data, dataLength, gUnicastServerSecureSocketDescClient);
+ data, dataLength, g_unicastServerSecureSocket);
}
else
{
#endif
len = CASendData(remoteAddress, port,
- data, dataLength, gUnicastServerSocketDescClient);
+ data, dataLength, g_unicastServerSocket);
#ifdef __WITH_DTLS__
}
#endif
}
+
#include "cawifiinterface.h"
#include <string.h>
-//#include <ifaddrs.h>
+#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <linux/if.h>
#include <netdb.h>
#include <errno.h>
+#include <unistd.h>
+
#include "caadapterutils.h"
#include "umutex.h"
#include "logger.h"
#include "oic_malloc.h"
-#include "com_iotivity_jar_CAWiFiInterface.h"
+#include "oic_string.h"
+#include "com_iotivity_jar_cawifiinterface.h"
#define WIFI_MONITOR_TAG "WIFI_MONITOR"
/**
- * @var nwConnectivityStatus
+ * @var g_nwConnectivityStatus
* @brief Maintains network status.
*/
-static CANetworkStatus_t nwConnectivityStatus;
+static CANetworkStatus_t g_nwConnectivityStatus;
/**
- * @var gWifiNetInfoMutex
+ * @var g_wifiNetInfoMutex
* @brief Mutex for synchronizing access to cached interface and IP address information.
*/
-static u_mutex gWifiNetInfoMutex = NULL;
+static u_mutex g_wifiNetInfoMutex = NULL;
/**
- * @var gWifiInterfaceName
+ * @var g_wifiInterfaceName
* @brief Maintains interface name.
*/
-static char *gWifiInterfaceName = NULL;
+static char *g_wifiInterfaceName = NULL;
/**
- * @var gWifiIPAddress
+ * @var g_wifiIPAddress
* @brief Maintains interface IP address.
*/
-static char *gWifiIPAddress = NULL;
+static char *g_wifiIPAddress = NULL;
/**
- * @var gWifiSubnetMask
+ * @var g_wifiSubnetMask
* @brief Maintains interface subnetmask.
*/
-static char *gWifiSubnetMask = NULL;
+static char *g_wifiSubnetMask = NULL;
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from adapter
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
/**
- * @var gStopNetworkMonitor
+ * @var g_stopNetworkMonitor
* @brief Flag to control the Network Monitor Thread
*/
-static bool gStopNetworkMonitor = false;
+static bool g_stopNetworkMonitor = false;
/**
* @var g_jvm
static jobject g_context = NULL;
/**
- * @var gNetworkChangeCb
+ * @var g_networkChangeCb
* @brief Maintains network connection state change callback.
*/
-static CAWiFiConnectionStateChangeCallback gNetworkChangeCb = NULL;
+static CAWiFiConnectionStateChangeCallback g_networkChangeCb = NULL;
/**
- * @fn CAWiFiGetInterfaceInformation
+ * @fn CAWiFiUpdateInterfaceInformation
* @brief This methods gets local interface name and IP address information.
*/
-static void CAWiFiGetInterfaceInformation(char **interfaceName, char **ipAddress,
- char **subnetMask);
+static void CAWiFiUpdateInterfaceInformation(char **interfaceName,
+ char **ipAddress, char **subnetMask);
/**
* @fn CACreateWiFiJNIInterfaceObject
* @brief creates new instance of CAWiFiInterface through JNI
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- gThreadPool = threadPool;
+ g_threadPool = threadPool;
- if (!gWifiNetInfoMutex)
+ if (!g_wifiNetInfoMutex)
{
- gWifiNetInfoMutex = u_mutex_new();
+ g_wifiNetInfoMutex = u_mutex_new();
}
CACreateWiFiJNIInterfaceObject(g_context);
- u_mutex_lock(gWifiNetInfoMutex);
- CAWiFiGetInterfaceInformation(&gWifiInterfaceName, &gWifiIPAddress, &gWifiSubnetMask);
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
+ CAWiFiUpdateInterfaceInformation(&g_wifiInterfaceName, &g_wifiIPAddress,
+ &g_wifiSubnetMask);
+ u_mutex_unlock(g_wifiNetInfoMutex);
- nwConnectivityStatus = (gWifiIPAddress) ? CA_INTERFACE_UP : CA_INTERFACE_DOWN;
+ g_nwConnectivityStatus = (g_wifiIPAddress) ? CA_INTERFACE_UP : CA_INTERFACE_DOWN;
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- gThreadPool = NULL;
+ g_threadPool = NULL;
+
+ u_mutex_lock(g_wifiNetInfoMutex);
- if (gWifiInterfaceName)
+ if (g_wifiInterfaceName)
{
- OICFree(gWifiInterfaceName);
- gWifiInterfaceName = NULL;
+ OICFree(g_wifiInterfaceName);
+ g_wifiInterfaceName = NULL;
}
- if (gWifiIPAddress)
+ if (g_wifiIPAddress)
{
- OICFree(gWifiIPAddress);
- gWifiIPAddress = NULL;
+ OICFree(g_wifiIPAddress);
+ g_wifiIPAddress = NULL;
}
- if (gWifiNetInfoMutex)
+ if (g_wifiSubnetMask)
{
- u_mutex_free(gWifiNetInfoMutex);
- gWifiNetInfoMutex = NULL;
+ OICFree(g_wifiSubnetMask);
+ g_wifiSubnetMask = NULL;
+ }
+
+ u_mutex_unlock(g_wifiNetInfoMutex);
+
+ if (g_wifiNetInfoMutex)
+ {
+ u_mutex_free(g_wifiNetInfoMutex);
+ g_wifiNetInfoMutex = NULL;
}
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- u_mutex_lock(gWifiNetInfoMutex);
- gStopNetworkMonitor = false;
- u_mutex_unlock(gWifiNetInfoMutex);
-
- if (gStopNetworkMonitor)
- {
- OIC_LOG_V(ERROR, WIFI_MONITOR_TAG, "Stop network monitor requested!");
- return CA_STATUS_FAILED;
- }
+ u_mutex_lock(g_wifiNetInfoMutex);
+ g_stopNetworkMonitor = false;
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- if (gStopNetworkMonitor)
+ u_mutex_lock(g_wifiNetInfoMutex);
+
+ if (g_stopNetworkMonitor)
{
OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "CAWiFiStopNetworkMonitor, already stopped");
-
+ u_mutex_unlock(g_wifiNetInfoMutex);
return CA_STATUS_OK;
}
- u_mutex_lock(gWifiNetInfoMutex);
- gStopNetworkMonitor = true;
- u_mutex_unlock(gWifiNetInfoMutex);
+ g_stopNetworkMonitor = true;
+
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(ipAddress, WIFI_MONITOR_TAG, "ip address");
// Get the interface and ipaddress information from cache
- u_mutex_lock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
- if(gWifiInterfaceName == NULL || gWifiIPAddress == NULL)
+ if(g_wifiInterfaceName == NULL || g_wifiIPAddress == NULL)
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "Network not enabled");
return CA_ADAPTER_NOT_ENABLED;
}
- *interfaceName = (gWifiInterfaceName) ? strndup(gWifiInterfaceName,strlen(gWifiInterfaceName))
+ *interfaceName = (g_wifiInterfaceName) ? OICStrdup((const char *)g_wifiInterfaceName)
: NULL;
- *ipAddress = (gWifiIPAddress) ? strndup(gWifiIPAddress,strlen(gWifiIPAddress))
+ *ipAddress = (g_wifiIPAddress) ? OICStrdup((const char *)g_wifiIPAddress)
: NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(subnetMask, WIFI_MONITOR_TAG, "subnet mask");
- u_mutex_lock(gWifiNetInfoMutex);
- if(NULL == gWifiSubnetMask)
+ u_mutex_lock(g_wifiNetInfoMutex);
+ if(NULL == g_wifiSubnetMask)
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "There is no subnet mask information!");
+ u_mutex_unlock(g_wifiNetInfoMutex);
return CA_STATUS_FAILED;
}
- *subnetMask = (gWifiSubnetMask) ? strndup(gWifiSubnetMask,strlen(gWifiSubnetMask))
+ *subnetMask = (g_wifiSubnetMask) ? OICStrdup((const char *)g_wifiSubnetMask)
: NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
bool CAWiFiIsConnected(void)
{
- OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
-
- if (nwConnectivityStatus == CA_INTERFACE_DOWN)
- return false;
-
- return true;
+ return(g_nwConnectivityStatus == CA_INTERFACE_UP);
}
void CAWiFiSetConnectionStateChangeCallback(
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- gNetworkChangeCb = callback;
+ g_networkChangeCb = callback;
+
+ OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
}
-void CAWiFiGetInterfaceInformation(char **interfaceName, char **ipAddress, char **subnetMask)
+void CAWiFiUpdateInterfaceInformation(char **interfaceName, char **ipAddress,
+ char **subnetMask)
{
char buf[1024] = { 0, };
struct ifconf ifc;
struct ifreq* ifr;
- int32_t sck;
+ int sck;
int32_t interfaces;
int32_t i;
const char *matchName = "wlan";
/* Iterate through the list of interfaces. */
ifr = ifc.ifc_req;
-// interfaces = ifc.ifc_len / sizeof(struct ifreq);
- interfaces = 2;
- OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "CAWiFiGetInterfaceInformation : %d", interfaces);
+ interfaces = ifc.ifc_len / sizeof(struct ifreq);
+
+ OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "CAWiFiUpdateInterfaceInformation : %d", interfaces);
for (i = 0; i < interfaces; i++)
{
- struct ifreq temp_ifr;
+ struct ifreq temp_ifr = {};
struct ifreq* item = &ifr[i];
char interfaceAddress[CA_IPADDR_SIZE] = {0};
char interfaceSubnetMask[CA_IPADDR_SIZE] = {0};
- socklen_t len = sizeof(struct sockaddr_in);
-
- memset(&temp_ifr, 0, sizeof(temp_ifr));
strcpy(temp_ifr.ifr_name, item->ifr_name);
- if (ioctl((int)sck, SIOCGIFFLAGS, &temp_ifr))
+ if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr))
{
- OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "CAWiFiGetInterfaceInformation, SIOCGIFFLAGS Failed");
+ OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG,
+ "CAWiFiUpdateInterfaceInformation, SIOCGIFFLAGS Failed");
continue;
}
continue;
}
- if (!strncasecmp(item->ifr_name,matchName,strlen(matchName))) {
- // get the interface ip address
+ if (!strncasecmp(item->ifr_name, matchName, strlen(matchName))) {
+
+ socklen_t len = sizeof(struct sockaddr_in);
+
+ // get the interface ip address
if (0 != getnameinfo(&item->ifr_addr, len, interfaceAddress,
sizeof(interfaceAddress), NULL, 0, NI_NUMERICHOST))
{
break;
}
+ // set interface name
+ *interfaceName = OICStrdup(item->ifr_name);
+
+ // set local ip address
+ *ipAddress = OICStrdup(interfaceAddress);
+
+ if (ioctl((int)sck, SIOCGIFNETMASK, item) < 0)
+ {
+ OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG,
+ "CAWiFiUpdateInterfaceInformation, SIOCGIFNETMASK Failed");
+ continue;
+ }
+
// get the interface subnet mask
if (0 != getnameinfo(&item->ifr_netmask, len, interfaceSubnetMask,
sizeof(interfaceSubnetMask), NULL, 0, NI_NUMERICHOST))
break;
}
- // set interface name
- *interfaceName = strndup(item->ifr_name, strlen(item->ifr_name));
-
- // set local ip address
- *ipAddress = strndup(interfaceAddress, strlen(interfaceAddress));
-
- // set subnet mask
- // *subnetMask = strndup(interfaceSubnetMask, strlen(interfaceSubnetMask));
- *subnetMask = strndup("255.255.255.0", strlen("255.255.255.0"));
+ *subnetMask = strndup(interfaceSubnetMask, strlen(interfaceSubnetMask));
}
else
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "did not match name : wlan");
- // set interface name
- *interfaceName = strndup(item->ifr_name, strlen(item->ifr_name));
-
- // set local ip address
- *ipAddress = strndup(ip, strlen(ip));
}
- OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "ipAddress : %s, interfaceName : %s, subnetmask : %s", *ipAddress, *interfaceName, *subnetMask);
+ OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG,
+ "ipAddress : %s, interfaceName : %s, subnetmask : %s",
+ *ipAddress, *interfaceName, *subnetMask);
break;
}
char *ipAddress = NULL;
char *subnetMask = NULL;
- if (gStopNetworkMonitor)
+ u_mutex_lock(g_wifiNetInfoMutex);
+
+ if (g_stopNetworkMonitor)
{
OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "Stop Network Monitor Thread is called");
+ u_mutex_unlock(g_wifiNetInfoMutex);
return;
}
- if(NULL == gNetworkChangeCb)
+ if(NULL == g_networkChangeCb)
{
- OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "[WiFiCore] gNetworkChangeCb is NULL");
+ OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "[WiFiCore] g_networkChangeCb is NULL");
+ u_mutex_lock(g_wifiNetInfoMutex);
return;
}
// if network status is changed
- if (currNetworkStatus != nwConnectivityStatus)
- {
- CAWiFiGetInterfaceInformation(&interfaceName, &ipAddress, & subnetMask);
+ CAWiFiUpdateInterfaceInformation(&interfaceName, &ipAddress, & subnetMask);
- // set current network information
- u_mutex_lock(gWifiNetInfoMutex);
+ // set current network information
+ g_nwConnectivityStatus = currNetworkStatus;
- nwConnectivityStatus = currNetworkStatus;
+ g_wifiInterfaceName = (interfaceName) ? OICStrdup(interfaceName) : NULL;
+ g_wifiIPAddress = (ipAddress) ? OICStrdup(ipAddress) : NULL;
- gWifiInterfaceName = (interfaceName) ? strndup(interfaceName, strlen(interfaceName)) : NULL;
- gWifiIPAddress = (ipAddress) ? strndup(ipAddress, strlen(ipAddress)) : NULL;
+ u_mutex_unlock(g_wifiNetInfoMutex);
- u_mutex_unlock(gWifiNetInfoMutex);
+ g_networkChangeCb(g_wifiIPAddress, g_nwConnectivityStatus);
- gNetworkChangeCb(gWifiIPAddress, nwConnectivityStatus);
- }
OICFree(interfaceName);
OICFree(ipAddress);
OICFree(subnetMask);
}
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CAWiFiInterface_CAWiFiStateEnabled
+JNIEXPORT void JNICALL Java_com_iotivity_jar_cawifiinterface_CAWiFiStateEnabled
(JNIEnv *env, jclass class)
{
- CALocalConnectivity_t info;
-
CANetworkStatus_t currNetworkStatus = CA_INTERFACE_UP;
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "[WiFiCore] CAWiFiStateEnabled");
+ if (currNetworkStatus == g_nwConnectivityStatus)
+ {
+ OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "[WiFiCore] Network State not changed");
+ return;
+ }
+
CASendNetworkChangeCallback(currNetworkStatus);
}
-JNIEXPORT void JNICALL Java_com_iotivity_jar_CAWiFiInterface_CAWiFiStateDisabled
+JNIEXPORT void JNICALL Java_com_iotivity_jar_cawifiinterface_CAWiFiStateDisabled
(JNIEnv *env, jclass class)
{
- CALocalConnectivity_t info;
-
CANetworkStatus_t currNetworkStatus = CA_INTERFACE_DOWN;
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "[WiFiCore] CAWiFiStateDisabled");
+ if (currNetworkStatus == g_nwConnectivityStatus)
+ {
+ OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "[WiFiCore] Network State not changed");
+ return;
+ }
CASendNetworkChangeCallback(currNetworkStatus);
}
+
#include "caadapternetdtls.h"
#endif
#include "umutex.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
/**
* @def WIFI_SERVER_TAG
#define IPNAMESIZE 16
/**
- * @var gUnicastServerSocketFD
+ * @var g_unicastServerSocketFD
* @brief Unicast server socket descriptor
*/
-static int32_t gUnicastServerSocketFD = -1;
+static int32_t g_unicastServerSocketFD = -1;
/**
- * @var gMutexUnicastServer
+ * @var g_mutexUnicastServer
* @brief Mutex to synchronize unicast server
*/
-static u_mutex gMutexUnicastServer = NULL;
+static u_mutex g_mutexUnicastServer = NULL;
/**
- * @var gStopUnicast
+ * @var g_stopUnicast
* @brief Flag to control the Receive Unicast Data Thread
*/
-static bool gStopUnicast = false;
+static bool g_stopUnicast = false;
/**
- * @var gMulticastServerSocketFD
+ * @var g_multicastServerSocketFD
* @brief socket descriptor for multicast server
*/
-static int32_t gMulticastServerSocketFD = -1;
+static int32_t g_multicastServerSocketFD = -1;
/**
- * @var gMutexMulticastServer
+ * @var g_mutexMulticastServer
* @brief Mutex to synchronize secure multicast server
*/
-static u_mutex gMutexMulticastServer = NULL;
+static u_mutex g_mutexMulticastServer = NULL;
/**
- * @var gStopMulticast
+ * @var g_stopMulticast
* @brief Flag to control the Receive Multicast Data Thread
*/
-static bool gStopMulticast = false;
+static bool g_stopMulticast = false;
#ifdef __WITH_DTLS__
/**
- * @var gSecureUnicastServerSocketFD
+ * @var g_secureUnicastServerSocketFD
* @brief Secure unicast server socket descriptor
*/
-static int32_t gSecureUnicastServerSocketFD = -1;
+static int32_t g_secureUnicastServerSocketFD = -1;
/**
- * @var gMutexSecureUnicastServer
+ * @var g_mutexSecureUnicastServer
* @brief Mutex to synchronize secure unicast server
*/
-static u_mutex gMutexSecureUnicastServer = NULL;
+static u_mutex g_mutexSecureUnicastServer = NULL;
/**
- * @var gStopSecureUnicast
+ * @var g_stopSecureUnicast
* @brief Flag to control the unicast secure data receive thread
*/
-static bool gStopSecureUnicast = false;
+static bool g_stopSecureUnicast = false;
#endif
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from adapter
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
/**
- * @var gMulticastServerInterface
+ * @var g_multicastServerInterface
* @brief Local interface on which multicast server is running
*/
-static char gMulticastServerInterface[IPNAMESIZE];
+static char g_multicastServerInterface[IPNAMESIZE];
/**
- * @var gMulticastMemberReq
+ * @var g_multicastMemberReq
* @brief ip_mreq structure passed to join a multicast group
*/
-static struct ip_mreq gMulticastMemberReq;
+static struct ip_mreq g_multicastMemberReq;
/**
- * @var gPacketReceivedCallback
+ * @var g_packetReceivedCallback
* @brief Callback for notifying the upper layer on receival data from remote OIC device
*/
-static CAWiFiPacketReceivedCallback gPacketReceivedCallback = NULL;
+static CAWiFiPacketReceivedCallback g_packetReceivedCallback = NULL;
/**
- * @var gExceptionCallback
+ * @var g_exceptionCallback
* @brief Callback for notifying the upper layer when unicast/multicast server encounters exception
*/
-static CAWiFiExceptionCallback gExceptionCallback = NULL;
+static CAWiFiExceptionCallback g_exceptionCallback = NULL;
/**
@brief Thread context information for unicast, multicast and secured unicast server
typedef struct
{
bool *stopFlag;
- int32_t socket_fd;
+ int socket_fd;
CAAdapterServerType_t type;
} CAAdapterReceiveThreadContext_t;
VERIFY_NON_NULL_VOID(data, WIFI_SERVER_TAG, "Invalid thread context");
CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *)data;
- fd_set reads;
- struct timeval timeout;
- char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
-
while (true != *(ctx->stopFlag))
{
+ fd_set reads;
+ struct timeval timeout;
+
timeout.tv_sec = 1;
timeout.tv_usec = 0;
FD_ZERO(&reads);
FD_SET(ctx->socket_fd, &reads);
- int32_t ret = select(ctx->socket_fd + 1, &reads, NULL, NULL, &timeout);
+ int ret = select(ctx->socket_fd + 1, &reads, NULL, NULL, &timeout);
if (*(ctx->stopFlag) == true)
{
OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Stop request received for [%d] server", ctx->type);
continue;
}
- memset(recvBuffer, 0, sizeof(recvBuffer));
-
// Read data from socket
struct sockaddr_in srcSockAddress;
int32_t recvLen;
socklen_t srcAddressLen = sizeof(srcSockAddress);
+ char recvBuffer[COAP_MAX_PDU_SIZE] = {};
+
if (-1 == (recvLen = recvfrom(ctx->socket_fd, recvBuffer,
sizeof(recvBuffer), 0, (struct sockaddr *) &srcSockAddress,
&srcAddressLen)))
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Server socket shutdown [%d]!", ctx->type);
// Notify upper layer this exception
- if (gExceptionCallback)
+ if (g_exceptionCallback)
{
- gExceptionCallback(ctx->type);
+ g_exceptionCallback(ctx->type);
}
OICFree(ctx);
return;
}
- const char *srcIPAddress = NULL;
- int32_t srcPort = -1;
+ const char *ipAddress = inet_ntoa(srcSockAddress.sin_addr);
+ uint16_t srcPort = ntohs(srcSockAddress.sin_port);
- srcIPAddress = inet_ntoa(srcSockAddress.sin_addr);
- srcPort = ntohs(srcSockAddress.sin_port);
+ char *srcIPAddress = OICStrdup(ipAddress);
+ if(NULL == srcIPAddress)
+ {
+ OICFree(ctx);
+ OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Error in OICStrdup, exit CAReceiveHandler");
+ break;
+ }
OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Received packet from %s:%d\n",
srcIPAddress, srcPort);
if (CA_STATUS_OK != CAWiFiGetInterfaceSubnetMask(&netMask))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to get ethernet subnet");
+ OICFree(srcIPAddress);
continue;
}
- if (!CAAdapterIsSameSubnet(gMulticastServerInterface, srcIPAddress, netMask))
+ if (!CAAdapterIsSameSubnet(g_multicastServerInterface, srcIPAddress, netMask))
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "Packet received from different subnet, Ignore!");
+ OICFree(srcIPAddress);
+ OICFree(netMask);
continue;
}
case CA_UNICAST_SERVER:
case CA_MULTICAST_SERVER:
// Notify data to upper layer
- if (gPacketReceivedCallback)
+ if (g_packetReceivedCallback)
{
- gPacketReceivedCallback(srcIPAddress, srcPort, recvBuffer, recvLen, false);
+ g_packetReceivedCallback(srcIPAddress, srcPort, recvBuffer, recvLen, false);
}
break;
#ifdef __WITH_DTLS__
default:
// Should never occur
OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Invalid server type");
+ OICFree(srcIPAddress);
OICFree(ctx);
return;
}
+
+ OICFree(srcIPAddress);
+
}
+ OICFree(ctx);
+
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
-static CAResult_t CAWiFiCreateSocket(int32_t *socketFD, const char *localIp, int16_t *port,
- const bool forceStart)
+static CAResult_t CAWiFiCreateSocket(int *socketFD, const char *localIp, uint16_t *port,
+ bool forceStart)
{
- int32_t sock = -1;
+ int sock = -1;
// Create a UDP socket
if (-1 == (sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)))
{
struct sockaddr_in sockAddr;
bool isBound = false;
- int16_t serverPort = *port;
+ uint16_t serverPort = *port;
- memset((char *) &sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(serverPort);
if (localIp)
return CA_STATUS_OK;
}
-static CAResult_t CAWiFiCloseSocket(int32_t *socketFD)
+static CAResult_t CAWiFiCloseSocket(int *socketFD)
{
if (-1 == *socketFD)
{
return CA_STATUS_OK;
}
-static CAResult_t CAStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, bool isSecured, int32_t *serverFD)
+static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port,
+ bool forceStart, bool isSecured, int *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopUnicast;
+ ctx->stopFlag = &g_stopUnicast;
ctx->socket_fd = *serverFD;
ctx->type = isSecured ? CA_SECURED_UNICAST_SERVER : CA_UNICAST_SERVER;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CAReceiveHandler, (void *)ctx))
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CAReceiveHandler, (void *)ctx))
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to create read thread!");
- OICFree((void *)ctx);
+ OICFree(ctx);
close(*serverFD);
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- if (gMutexUnicastServer)
+ if (g_mutexUnicastServer)
{
- u_mutex_free(gMutexUnicastServer);
- gMutexUnicastServer = NULL;
+ u_mutex_free(g_mutexUnicastServer);
+ g_mutexUnicastServer = NULL;
}
#ifdef __WITH_DTLS__
- if (gMutexSecureUnicastServer)
+ if (g_mutexSecureUnicastServer)
{
- u_mutex_free(gMutexSecureUnicastServer);
- gMutexSecureUnicastServer = NULL;
+ u_mutex_free(g_mutexSecureUnicastServer);
+ g_mutexSecureUnicastServer = NULL;
}
#endif
- if (gMutexMulticastServer)
+ if (g_mutexMulticastServer)
{
- u_mutex_free(gMutexMulticastServer);
- gMutexMulticastServer = NULL;
+ u_mutex_free(g_mutexMulticastServer);
+ g_mutexMulticastServer = NULL;
}
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gMutexUnicastServer = u_mutex_new();
- if (!gMutexUnicastServer)
+ g_mutexUnicastServer = u_mutex_new();
+ if (!g_mutexUnicastServer)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
#ifdef __WITH_DTLS__
- gMutexSecureUnicastServer = u_mutex_new();
- if (!gMutexSecureUnicastServer)
+ g_mutexSecureUnicastServer = u_mutex_new();
+ if (!g_mutexSecureUnicastServer)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
}
#endif
- gMutexMulticastServer = u_mutex_new();
- if (!gMutexMulticastServer)
+ g_mutexMulticastServer = u_mutex_new();
+ if (!g_mutexMulticastServer)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
- gThreadPool = threadPool;
+ g_threadPool = threadPool;
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gThreadPool = NULL;
+ g_threadPool = NULL;
// Destroy mutex
CAWiFiServerDestroyMutex();
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
-CAResult_t CAWiFiStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, const CABool_t isSecured,
+CAResult_t CAWiFiStartUnicastServer(const char *localAddress, uint16_t *port,
+ const bool forceStart, const bool isSecured,
int32_t *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
}
*serverFD = -1;
- if (CA_FALSE == isSecured)
+ if (false == isSecured)
{
- u_mutex_lock(gMutexUnicastServer);
- if (-1 != gUnicastServerSocketFD)
+ u_mutex_lock(g_mutexUnicastServer);
+ if (-1 != g_unicastServerSocketFD)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Unicast Server is Started Already!",
CA_SERVER_STARTED_ALREADY);
- *serverFD = gUnicastServerSocketFD;
- u_mutex_unlock(gMutexUnicastServer);
+ *serverFD = g_unicastServerSocketFD;
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_SERVER_STARTED_ALREADY;
}
- gStopUnicast = false;
+ g_stopUnicast = false;
if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
- &gUnicastServerSocketFD))
+ &g_unicastServerSocketFD))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to start unicast server!");
- close(gUnicastServerSocketFD);
- gUnicastServerSocketFD = -1;
- u_mutex_unlock(gMutexUnicastServer);
+ close(g_unicastServerSocketFD);
+ g_unicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gUnicastServerSocketFD;
- u_mutex_unlock(gMutexUnicastServer);
+ *serverFD = g_unicastServerSocketFD;
+ u_mutex_unlock(g_mutexUnicastServer);
}
#ifdef __WITH_DTLS__
else // Start unicast server for secured communication
{
- u_mutex_lock(gMutexSecureUnicastServer);
- if (-1 != gSecureUnicastServerSocketFD)
+ u_mutex_lock(g_mutexSecureUnicastServer);
+ if (-1 != g_secureUnicastServerSocketFD)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Unicast Server is Started Already!",
CA_SERVER_STARTED_ALREADY);
- *serverFD = gSecureUnicastServerSocketFD;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ *serverFD = g_secureUnicastServerSocketFD;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
return CA_SERVER_STARTED_ALREADY;
}
- gStopSecureUnicast = false;
+ g_stopSecureUnicast = false;
if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
- &gSecureUnicastServerSocketFD))
+ &g_secureUnicastServerSocketFD))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to start unicast server!");
- gSecureUnicastServerSocketFD = -1;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ g_secureUnicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gSecureUnicastServerSocketFD;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ *serverFD = g_secureUnicastServerSocketFD;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
}
#endif
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD)
+ const uint16_t multicastPort, int32_t *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
// Input validation
VERIFY_NON_NULL(localAddress, WIFI_SERVER_TAG, "Local address is NULL");
VERIFY_NON_NULL(multicastAddress, WIFI_SERVER_TAG, "Multicast address is NULL");
+ VERIFY_NON_NULL(serverFD, WIFI_SERVER_TAG, "serverFD address is NULL");
- int16_t port = multicastPort;
+ uint16_t port = multicastPort;
if (0 >= port)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Invalid input: Multicast port is invalid!");
return CA_STATUS_INVALID_PARAM;
}
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
- if (gMulticastServerSocketFD != -1)
+ if (g_multicastServerSocketFD != -1)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Multicast Server is already running!");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_SERVER_STARTED_ALREADY;
}
- CAResult_t ret = CAWiFiCreateSocket(&gMulticastServerSocketFD, multicastAddress, &port, true);
+ CAResult_t ret = CAWiFiCreateSocket(&g_multicastServerSocketFD, multicastAddress, &port, true);
if (ret != CA_STATUS_OK)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to create multicast socket");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return ret;
}
// Add membership to receiving socket (join group)
- memset(&gMulticastMemberReq, 0, sizeof(struct ip_mreq));
- gMulticastMemberReq.imr_interface.s_addr = inet_addr(localAddress);
- inet_aton(multicastAddress, &gMulticastMemberReq.imr_multiaddr);
+ memset(&g_multicastMemberReq, 0, sizeof(struct ip_mreq));
+ g_multicastMemberReq.imr_interface.s_addr = inet_addr(localAddress);
+ inet_aton(multicastAddress, &g_multicastMemberReq.imr_multiaddr);
- if (-1 == setsockopt(gMulticastServerSocketFD, IPPROTO_IP, IP_ADD_MEMBERSHIP,
- (char *) &gMulticastMemberReq,
+ if (-1 == setsockopt(g_multicastServerSocketFD, IPPROTO_IP, IP_ADD_MEMBERSHIP,
+ (char *) &g_multicastMemberReq,
sizeof(struct ip_mreq)))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to add to multicast group, Error code: %s\n",
strerror(errno));
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
- u_mutex_unlock(gMutexMulticastServer);
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_STATUS_FAILED;
}
if (!ctx)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Out of memory!");
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopMulticast;
- ctx->socket_fd = gMulticastServerSocketFD;
+ ctx->stopFlag = &g_stopMulticast;
+ ctx->socket_fd = g_multicastServerSocketFD;
ctx->type = CA_MULTICAST_SERVER;
- gStopMulticast = false;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CAReceiveHandler, (void *)ctx))
+ g_stopMulticast = false;
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CAReceiveHandler, (void *)ctx))
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "thread_pool_add_task failed!");
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
- gStopMulticast = true;
- u_mutex_unlock(gMutexMulticastServer);
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
+ g_stopMulticast = true;
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gMulticastServerSocketFD;
- strncpy(gMulticastServerInterface, localAddress, IPNAMESIZE);
- u_mutex_unlock(gMutexMulticastServer);
+ *serverFD = g_multicastServerSocketFD;
+ strncpy(g_multicastServerInterface, localAddress, IPNAMESIZE);
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexUnicastServer);
- gStopUnicast = true;
- CAResult_t ret = CAWiFiCloseSocket(&gUnicastServerSocketFD);
- u_mutex_unlock(gMutexUnicastServer);
+ u_mutex_lock(g_mutexUnicastServer);
+ g_stopUnicast = true;
+ CAResult_t ret = CAWiFiCloseSocket(&g_unicastServerSocketFD);
+ u_mutex_unlock(g_mutexUnicastServer);
OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Unicast server stopped [%d]", ret);
return ret;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexSecureUnicastServer);
- gStopSecureUnicast = true;
- CAResult_t ret = CAWiFiCloseSocket(&gSecureUnicastServerSocketFD);
- u_mutex_unlock(gMutexSecureUnicastServer);
+ u_mutex_lock(g_mutexSecureUnicastServer);
+ g_stopSecureUnicast = true;
+ CAResult_t ret = CAWiFiCloseSocket(&g_secureUnicastServerSocketFD);
+ u_mutex_unlock(g_mutexSecureUnicastServer);
OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Secured unicast server stopped [%d]", ret);
return ret;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
- if (gMulticastServerSocketFD == -1)
+ if (g_multicastServerSocketFD == -1)
{
OIC_LOG(INFO, WIFI_SERVER_TAG, "Multicast server is not yet started");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_SERVER_NOT_STARTED;
}
- gStopMulticast = true;
+ g_stopMulticast = true;
// leave the group after you are done
- if (-1 == setsockopt(gMulticastServerSocketFD, IPPROTO_IP, IP_DROP_MEMBERSHIP,
- (char *)&gMulticastMemberReq,
+ if (-1 == setsockopt(g_multicastServerSocketFD, IPPROTO_IP, IP_DROP_MEMBERSHIP,
+ (char *)&g_multicastMemberReq,
sizeof(struct ip_mreq)))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to leave multicast group, Error code: %s\n",
strerror(errno));
}
- CAResult_t ret = CAWiFiCloseSocket(&gMulticastServerSocketFD);
- u_mutex_unlock(gMutexMulticastServer);
+ CAResult_t ret = CAWiFiCloseSocket(&g_multicastServerSocketFD);
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Multicast server stopped [%d]", ret);
return ret;
}
-CAResult_t CAWiFiGetUnicastServerInfo(const CABool_t isSecured, char **ipAddress,
- int16_t *port, int32_t *serverFD)
+CAResult_t CAWiFiGetUnicastServerInfo(const bool isSecured, char **ipAddress,
+ uint16_t *port, int32_t *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
struct sockaddr_in sockAddr;
socklen_t len = sizeof(struct sockaddr_in);
- if (-1 == getsockname(gUnicastServerSocketFD, (struct sockaddr *)&sockAddr, &len))
+ if (-1 == getsockname(g_unicastServerSocketFD, (struct sockaddr *)&sockAddr, &len))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed in getsockname [%s]!", strerror(errno));
return CA_STATUS_FAILED;
*ipAddress = (serverAddress) ? strndup(serverAddress, strlen(serverAddress)) : NULL;
*port = ntohs(sockAddr.sin_port);
#ifdef __WITH_DTLS__
- *serverFD = (CA_TRUE == isSecured) ? gSecureUnicastServerSocketFD : gUnicastServerSocketFD;
+ *serverFD = (true == isSecured) ? g_secureUnicastServerSocketFD : g_unicastServerSocketFD;
#else
- *serverFD = gUnicastServerSocketFD;
+ *serverFD = g_unicastServerSocketFD;
#endif
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gPacketReceivedCallback = callback;
+ g_packetReceivedCallback = callback;
}
void CAWiFiSetExceptionCallback(CAWiFiExceptionCallback callback)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gExceptionCallback = callback;
+ g_exceptionCallback = callback;
}
+
--- /dev/null
+#include <jni.h>
+/* Header for class com_iotivity_jar_cawifiinterface */
+
+#ifndef _Included_com_iotivity_jar_cawifiinterface
+#define _Included_com_iotivity_jar_cawifiinterface
+#ifdef __cplusplus
+extern "C" {
+#endif
+/*
+ * Class: com_iotivity_jar_cawifiinterface
+ * Method: CAWiFiStateEnabled
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_cawifiinterface_CAWiFiStateEnabled
+(JNIEnv *, jclass);
+
+/*
+ * Class: com_iotivity_jar_cawifiinterface
+ * Method: CAWiFiStateDisabled
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL
+Java_com_iotivity_jar_cawifiinterface_CAWiFiStateDisabled
+(JNIEnv *, jclass);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
+
static WiFiUDP Udp;
-void CAWiFiSetUnicastSocket(const int32_t socketID)
+void CAWiFiSetUnicastSocket(int socketID)
{
}
-uint32_t CAWiFiSendData(const char *remoteAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, bool isMulticast)
+uint32_t CAWiFiSendData(const char *remoteAddress, uint32_t port,
+ const void *data, uint32_t dataLength, bool isMulticast)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
- VERIFY_NON_NULL(data, MOD_NAME, "data");
- VERIFY_NON_NULL(remoteAddress, MOD_NAME, "address");
+ VERIFY_NON_NULL_RET(data, MOD_NAME, "data", 0);
+ VERIFY_NON_NULL_RET(remoteAddress, MOD_NAME, "address", 0);
- int32_t ret = 1;
OIC_LOG_V(DEBUG, MOD_NAME, "remoteip: %s", remoteAddress);
OIC_LOG_V(DEBUG, MOD_NAME, "port: %d", port);
- Udp.beginPacket(remoteAddress, (uint16_t)port);
- ret = (int32_t)Udp.write((char *)data);
- Udp.endPacket();
+
+ uint8_t ip[4] = {0};
+ uint16_t parsedPort = 0;
+ CAResult_t res = CAParseIPv4AddressInternal(remoteAddress, ip, sizeof(ip),
+ &parsedPort);
+ if (res != CA_STATUS_OK)
+ {
+ OIC_LOG_V(ERROR, MOD_NAME, "Remote adrs parse fail %d", res);
+ return 0;
+ }
+
+ IPAddress remoteIp(ip);
+ Udp.beginPacket(remoteIp, (uint16_t)port);
+ int32_t ret = (int32_t)Udp.write((char *)data, dataLength);
+ if (Udp.endPacket() == 0)
+ {
+ OIC_LOG(ERROR, MOD_NAME, "Failed to send");
+ return 0;
+ }
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return ret;
}
+
* limitations under the License.
*
******************************************************************/
+/**
+ * @file cawifinwmonitor.cpp
+ * @brief This file is to keep design in sync with other platforms. Right now there is no
+ * api for network monitioring in arduino.
+ */
#include "cawifiinterface_singlethread.h"
-#include <Arduino.h>
-#include <WiFi.h>
-#include <WiFiUdp.h>
-#include <SPI.h>
-#include <utility/server_drv.h>
-#include <utility/wifi_drv.h>
-#include <IPAddress.h>
-#include "logger.h"
-#include "caadapterutils.h"
-#include "cawifiadapter_singlethread.h"
-
#define WIFI_MONITOR_TAG "WIFI_MONITOR"
CAResult_t CAWiFiInitializeNetworkMonitor(void)
bool CAWiFiIsConnected(void)
{
- return CA_TRUE;
+ return true;
}
void CAWiFiSetConnectionStateChangeCallback(CAWiFiConnectionStateChangeCallback callback)
void CAWiFiTerminateNetworkMonitor(void)
{
return;
-}
\ No newline at end of file
+}
#include "caadapterutils.h"
#include "oic_malloc.h"
-#define COAP_MAX_PDU_SIZE 320
#define MOD_NAME "WS"
-char ssid[] = "NETGEAR99"; // your network SSID (name)
-const char pass[] = "jollysky325"; // your network password
-int16_t status = WL_IDLE_STATUS; // the Wifi radio's status
-
// Length of the IP address decimal notation string
#define IPNAMESIZE (16)
CAResult_t CAWiFiInitializeServer(void)
{
+ /**
+ * This API is to keep design in sync with other platforms.
+ * The required implementation is done in Start() api's.
+ */
return CA_STATUS_OK;
}
void CAWiFiTerminateServer(void)
{
-
+ /**
+ * This API is to keep design in sync with other platforms.
+ * The required implementation is done in Stop() api's.
+ */
}
-CAResult_t CAWiFiGetUnicastServerInfo(char **ipAddress, int *port, int32_t *serverID)
+CAResult_t CAWiFiGetUnicastServerInfo(char **ipAddress, int *port, int *serverID)
{
+ /*
+ * This API is to keep design in sync with other platforms.
+ * Will be implemented as and when CA layer wants this info.
+ */
return CA_STATUS_OK;
}
CAResult_t CAWiFiStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, int32_t *serverFD)
+ bool forceStart, int *serverFD)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
VERIFY_NON_NULL(port, MOD_NAME, "port");
- // WiFiClass WiFi;
- if (WiFi.status() == WL_NO_SHIELD)
+ if (gServerRunning)
{
+ // already running
OIC_LOG(DEBUG, MOD_NAME, "Error");
return CA_STATUS_FAILED;
}
- while (status != WL_CONNECTED)
+ if (WiFi.status() != WL_CONNECTED)
{
- OIC_LOG_V(ERROR, MOD_NAME, "connecting: %s", ssid);
- status = WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network:
-
- // wait 10 seconds for connection:
- delay(10000);
+ OIC_LOG(ERROR, MOD_NAME, "ERROR:No WIFI");
+ return CA_STATUS_FAILED;
}
char localIpAddress[CA_IPADDR_SIZE];
int32_t localIpAddressLen = sizeof(localIpAddress);
CAArduinoGetInterfaceAddress(localIpAddress, localIpAddressLen);
OIC_LOG_V(DEBUG, MOD_NAME, "address: %s", localIpAddress);
-
- if (gServerRunning)
- {
- // already running
- OIC_LOG(DEBUG, MOD_NAME, "Error");
- return CA_STATUS_FAILED;
- }
-
OIC_LOG_V(DEBUG, MOD_NAME, "port: %d", *port);
+
Udp.begin((uint16_t ) *port);
+ gServerRunning = true;
- // start thread to monitor socket here
- if (!gServerRunning)
- {
- gServerRunning = true;
- }
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD)
+ int16_t multicastPort, int *serverFD)
{
// wifi shield does not support multicast
OIC_LOG(DEBUG, MOD_NAME, "IN");
OIC_LOG(DEBUG, MOD_NAME, "IN");
Udp.stop();
- // Terminate server thread
gServerRunning = false;
OIC_LOG(DEBUG, MOD_NAME, "OUT");
return CA_STATUS_OK;
CAArduinoCheckData();
}
-/// Retrieves the IP address assigned to Arduino Ethernet shield
+/// Retrieves the IP address assigned to Arduino WiFi shield
CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
{
OIC_LOG(DEBUG, MOD_NAME, "IN");
- // WiFiClass WiFi;
- if (WiFi.status() == WL_NO_SHIELD)
+ if (WiFi.status() != WL_CONNECTED)
{
- OIC_LOG(DEBUG, MOD_NAME, "WIFI SHIELD NOT PRESENT");
+ OIC_LOG(DEBUG, MOD_NAME, "No WIFI");
return CA_STATUS_FAILED;
}
- while ( status != WL_CONNECTED)
- {
- OIC_LOG_V(ERROR, MOD_NAME, "Connecting to WPA SSID: %s", ssid);
- status = WiFi.begin(ssid, pass); // Connect to WPA/WPA2 network:
-
- // wait 10 seconds for connection:
- delay(10000);
- OIC_LOG(DEBUG, MOD_NAME, "Attempting connection again");
- }
-
VERIFY_NON_NULL(address, MOD_NAME, "Invalid address");
if (addrLen < IPNAMESIZE)
{
}
+
* @brief Unicast port number (to listen for incoming data on unicast server).
* Note :- Actual port number may differ based on result of bind() operation.
*/
-#define CA_PORT 5298
+#define CA_PORT 6298
/**
* @def CA_SECURE_PORT
} CAWiFiData;
/**
- * @var gNetworkPacketCallback
+ * @var g_networkPacketCallback
* @brief Network Packet Received Callback to CA
*/
-static CANetworkPacketReceivedCallback gNetworkPacketCallback = NULL;
+static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
/**
* @var gNetworkChangeCb
* @brief Network Changed Callback to CA
*/
-static CANetworkChangeCallback gNetworkChangeCallback = NULL;
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
/**
- * @var gIsMulticastServerStarted
+ * @var g_isMulticastServerStarted
* @brief Flag to check if multicast server is started
*/
-static bool gIsMulticastServerStarted = false;
+static bool g_isMulticastServerStarted = false;
/**
* @var gIsStartServerCalled
* @brief Flag to check if server start requested by CA.
*/
-static bool gStartUnicastServerRequested = false;
+static bool g_startUnicastServerRequested = false;
/**
- * @var gUnicastServerport
+ * @var g_unicastServerport
* @brief port number on which unicast server is running.
*/
-static int16_t gUnicastServerport = 0;
+static int16_t g_unicastServerport = 0;
#ifdef __WITH_DTLS__
/**
- * @var gSecureUnicastServerport
+ * @var g_secureUnicastServerport
* @brief port number on which secure unicast server is running.
*/
-static int16_t gSecureUnicastServerport = 0;
+static int16_t g_secureUnicastServerport = 0;
#endif
/**
* @var gIsStartServerCalled
* @brief Flag to check if server start requested by CA.
*/
-static bool gStartMulticastServerRequested = false;
+static bool g_startMulticastServerRequested = false;
/**
- * @var gSendQueueHandle
+ * @var g_sendQueueHandle
* @brief Queue handle for Send Data
*/
-static CAQueueingThread_t *gSendQueueHandle = NULL;
+static CAQueueingThread_t *g_sendQueueHandle = NULL;
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from CA
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
static CAResult_t CAWiFiInitializeQueueHandles();
static void CAWiFiDeinitializeQueueHandles();
-static void CAWiFiNotifyNetworkChange(const char *address, const int16_t port,
- const CANetworkStatus_t status);
+static void CAWiFiNotifyNetworkChange(const char *address, uint16_t port,
+ CANetworkStatus_t status);
static void CAWiFiConnectionStateCB(const char *ipAddress,
- const CANetworkStatus_t status);
-static void CAWiFiPacketReceivedCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength,
- const CABool_t isSecured);
+ CANetworkStatus_t status);
+static void CAWiFiPacketReceivedCB(const char *ipAddress, uint16_t port,
+ const void *data, uint32_t dataLength,
+ bool isSecured);
+
#ifdef __WITH_DTLS__
-static uint32_t CAWiFiPacketSendCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength);
+static uint32_t CAWiFiPacketSendCB(const char *ipAddress, uint16_t port,
+ const void *data, uint32_t dataLength);
#endif
static CAResult_t CAWiFiStopServers();
static void CAWiFiSendDataThread(void *threadData);
-static CAWiFiData *CACreateWiFiData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+static CAWiFiData *CACreateWiFiData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength);
void CAFreeWiFiData(CAWiFiData *wifiData);
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
// Check if the message queue is already initialized
- if (gSendQueueHandle)
+ if (g_sendQueueHandle)
{
- OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "Already queue is initialized!");
+ OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "send queue handle is already initialized!");
return CA_STATUS_OK;
}
// Create send message queue
- gSendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
- if (!gSendQueueHandle)
+ g_sendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
+ if (!g_sendQueueHandle)
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Memory allocation failed!");
return CA_MEMORY_ALLOC_FAILED;
}
- if (CA_STATUS_OK != CAQueueingThreadInitialize(gSendQueueHandle, gThreadPool,
+ if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_threadPool,
CAWiFiSendDataThread, CADataDestroyer))
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Failed to Initialize send queue thread");
- OICFree(gSendQueueHandle);
- gSendQueueHandle = NULL;
+ OICFree(g_sendQueueHandle);
+ g_sendQueueHandle = NULL;
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
- CAQueueingThreadDestroy(gSendQueueHandle);
- OICFree(gSendQueueHandle);
- gSendQueueHandle = NULL;
+ CAQueueingThreadDestroy(g_sendQueueHandle);
+ OICFree(g_sendQueueHandle);
+ g_sendQueueHandle = NULL;
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
}
-void CAWiFiNotifyNetworkChange(const char *address, const int16_t port,
- const CANetworkStatus_t status)
+void CAWiFiNotifyNetworkChange(const char *address, uint16_t port,
+ CANetworkStatus_t status)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
}
localEndpoint->addressInfo.IP.port = port;
- if (NULL != gNetworkChangeCallback)
+ if (NULL != g_networkChangeCallback)
{
- gNetworkChangeCallback(localEndpoint, status);
+ g_networkChangeCallback(localEndpoint, status);
}
CAAdapterFreeLocalEndpoint(localEndpoint);
}
void CAWiFiConnectionStateCB(const char *ipAddress,
- const CANetworkStatus_t status)
+ CANetworkStatus_t status)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
*/
if (CA_INTERFACE_UP == status)
{
- int16_t port = CA_PORT;
+ uint16_t port = CA_PORT;
int32_t serverFd = -1;
// Start Unicast server if requested earlier
- if (gStartUnicastServerRequested)
+ if (g_startUnicastServerRequested)
{
ret = CAWiFiStartUnicastServer("0.0.0.0", &port, false, false, &serverFd);
if (CA_STATUS_OK == ret)
{
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Unicast server started on %d port", port);
CAWiFiSetUnicastSocket(serverFd);
- gUnicastServerport = port;
+ g_unicastServerport = port;
}
else
{
{
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Secure Unicast server started on %d", port);
CAWiFiSetSecureUnicastSocket(serverFd);
- gSecureUnicastServerport = port;
+ g_secureUnicastServerport = port;
}
else
{
}
// Start Multicast server if requested earlier
- if (gStartMulticastServerRequested)
+ if (g_startMulticastServerRequested)
{
- int16_t multicastPort = CA_MCAST_PORT;
+ uint16_t multicastPort = CA_MCAST_PORT;
int32_t multicastFd = 0;
ret = CAWiFiStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort,
&multicastFd);
{
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Multicast server started on %d port",
multicastPort);
- gIsMulticastServerStarted = true;
+ g_isMulticastServerStarted = true;
}
else
{
}
#ifdef __WITH_DTLS__
-uint32_t CAWiFiPacketSendCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength)
+uint32_t CAWiFiPacketSendCB(const char *ipAddress, uint16_t port,
+ const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
- uint32_t sentLength = CAWiFiSendData(ipAddress, port, data, dataLength, CA_FALSE, CA_TRUE);
+ uint32_t sentLength = CAWiFiSendData(ipAddress, port, data, dataLength, false, true);
- OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Successfully sent %d of encripted data!", sentLength);
+ OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Successfully sent %d of encrypted data!", sentLength);
return sentLength;
}
#endif
-void CAWiFiPacketReceivedCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, const CABool_t isSecured)
+void CAWiFiPacketReceivedCB(const char *ipAddress, uint16_t port,
+ const void *data, uint32_t dataLength, bool isSecured)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Address: %s, port:%d, data:%s", ipAddress, port, data);
endPoint->addressInfo.IP.port = port;
endPoint->isSecured = isSecured;
- void *buf = OICMalloc(dataLength + 1);
+ void *buf = OICMalloc(dataLength);
if (NULL == buf)
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Out of memory");
CAAdapterFreeRemoteEndpoint(endPoint);
return;
}
+
memcpy(buf, data, dataLength);
- memset(buf + dataLength, 0, 1);
- if (gNetworkPacketCallback)
+
+ if (g_networkPacketCallback)
{
- gNetworkPacketCallback(endPoint, buf, dataLength);
+ g_networkPacketCallback(endPoint, buf, dataLength);
}
else
{
VERIFY_NON_NULL(netCallback, WIFI_ADAPTER_TAG, "netCallback");
VERIFY_NON_NULL(handle, WIFI_ADAPTER_TAG, "thread pool handle");
- gThreadPool = handle;
- gNetworkChangeCallback = netCallback;
- gNetworkPacketCallback = networkPacketCallback;
+ g_threadPool = handle;
+ g_networkChangeCallback = netCallback;
+ g_networkPacketCallback = networkPacketCallback;
- CAResult_t ret = CAWiFiInitializeNetworkMonitor(gThreadPool);
+ CAResult_t ret = CAWiFiInitializeNetworkMonitor(g_threadPool);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to initialize n/w monitor![%d]", ret);
}
CAWiFiSetConnectionStateChangeCallback(CAWiFiConnectionStateCB);
- ret = CAWiFiInitializeServer(gThreadPool);
+ ret = CAWiFiInitializeServer(g_threadPool);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to initialize server![%d]", ret);
- CATerminateWIfI();
+ CATerminateWIFI();
return ret;
}
CAConnectivityHandler_t wifiHandler;
wifiHandler.startAdapter = CAStartWIFI;
wifiHandler.startListenServer = CAStartWIFIListeningServer;
- wifiHandler.startDiscoverServer = CAStartWIFIDiscoveryServer;
+ wifiHandler.startDiscoveryServer = CAStartWIFIDiscoveryServer;
wifiHandler.sendData = CASendWIFIUnicastData;
wifiHandler.sendDataToAll = CASendWIFIMulticastData;
wifiHandler.GetnetInfo = CAGetWIFIInterfaceInformation;
wifiHandler.readData = CAReadWIFIData;
wifiHandler.stopAdapter = CAStopWIFI;
- wifiHandler.terminate = CATerminateWIfI;
+ wifiHandler.terminate = CATerminateWIFI;
registerCallback(wifiHandler, CA_WIFI);
if (CA_STATUS_OK != CAWiFiInitializeQueueHandles())
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Failed to Initialize Queue Handle");
- CATerminateWIfI();
+ CATerminateWIFI();
return CA_STATUS_FAILED;
}
if (CA_STATUS_OK != ret)
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Failed to Start n/w monitor");
+ return ret;
}
// Start send queue thread
- if (CA_STATUS_OK != CAQueueingThreadStart(gSendQueueHandle))
+ if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Failed to Start Send Data Thread");
+ CAStopWIFI();
return CA_STATUS_FAILED;
}
- gStartUnicastServerRequested = true;
+ g_startUnicastServerRequested = true;
bool retVal = CAWiFiIsConnected();
if (false == retVal)
{
return ret;
}
- int16_t unicastPort = CA_PORT;
+ uint16_t unicastPort = CA_PORT;
int32_t serverFd = 0;
// Address is hardcoded as we are using Single Interface
ret = CAWiFiStartUnicastServer(ifcAdrs, &unicastPort, false, false, &serverFd);
{
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Unicast server started on %d port", unicastPort);
CAWiFiSetUnicastSocket(serverFd);
- gUnicastServerport = unicastPort;
+ g_unicastServerport = unicastPort;
}
#ifdef __WITH_DTLS__
{
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Secure Unicast server started on %d port", unicastPort);
CAWiFiSetSecureUnicastSocket(serverFd);
- gSecureUnicastServerport = unicastPort;
+ g_secureUnicastServerport = unicastPort;
}
#endif
- if(ifcName)
- {
- OICFree(ifcName);
- }
- if(ifcAdrs)
- {
- OICFree(ifcAdrs);
- }
+
+ OICFree(ifcName);
+ OICFree(ifcAdrs);
+
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
return ret;
}
CAResult_t ret = CA_STATUS_OK;
int16_t multicastPort = CA_MCAST_PORT;
- if (gIsMulticastServerStarted == true)
+ if (g_isMulticastServerStarted == true)
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG,
"Failed to Start Multicast Server, Already Started!");
return CA_SERVER_STARTED_ALREADY;
}
- gStartMulticastServerRequested = true;
+ g_startMulticastServerRequested = true;
bool retVal = CAWiFiIsConnected();
if (false == retVal)
{
if (CA_STATUS_OK == ret)
{
OIC_LOG(INFO, WIFI_ADAPTER_TAG, "Multicast Server is Started Successfully");
- gIsMulticastServerStarted = true;
+ g_isMulticastServerStarted = true;
}
- if(ifcName)
- {
- OICFree(ifcName);
- }
- if(ifcAdrs)
- {
- OICFree(ifcAdrs);
- }
+ OICFree(ifcName);
+ OICFree(ifcAdrs);
+
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
return ret;
}
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
return CAStartWIFIListeningServer();
+ OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
}
-uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
- uint32_t dataLength)
+int32_t CASendWIFIData(const CARemoteEndpoint_t *remoteEndpoint, const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
- uint32_t dataSize = 0;
- VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ADAPTER_TAG, "remoteEndpoint", dataSize);
+ int32_t dataSize = -1;
VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", dataSize);
- VERIFY_NON_NULL_RET(gSendQueueHandle, WIFI_ADAPTER_TAG, "sendQueueHandle", dataSize);
+ VERIFY_NON_NULL_RET(g_sendQueueHandle, WIFI_ADAPTER_TAG, "sendQueueHandle", dataSize);
if (0 == dataLength)
{
if (!wifiData)
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to create wifidata!");
- return CA_MEMORY_ALLOC_FAILED;
+ return dataSize;
}
// Add message to send queue
- CAQueueingThreadAddData(gSendQueueHandle, wifiData, sizeof(CAWiFiData));
+ CAQueueingThreadAddData(g_sendQueueHandle, wifiData, sizeof(CAWiFiData));
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
- return dataLength;
+ return 0;
}
-uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLength)
+int32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+ uint32_t dataLength)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
- uint32_t dataSize = 0;
- VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", dataSize);
- VERIFY_NON_NULL_RET(gSendQueueHandle, WIFI_ADAPTER_TAG, "sendQueueHandle", dataSize);
+ int32_t dataSize = -1;
+ VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ADAPTER_TAG, "remoteEndpoint", dataSize);
- if (0 == dataLength)
- {
- OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Invalid Data Length");
- return dataSize;
- }
+ dataSize = CASendWIFIData(remoteEndpoint, data, dataLength);
- // Create WifiData to add to queue
- CAWiFiData *wifiData = CACreateWiFiData(NULL, data, dataLength);
- if (!wifiData)
- {
- OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to create wifidata!");
- return CA_MEMORY_ALLOC_FAILED;
- }
+ OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+ return dataSize;
+}
- // Add message to send queue
- CAQueueingThreadAddData(gSendQueueHandle, wifiData, sizeof(CAWiFiData));
+int32_t CASendWIFIMulticastData(const void *data, uint32_t dataLength)
+{
+ OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+ int32_t dataSize = CASendWIFIData(NULL, data, dataLength);
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
- return dataLength;
+ return dataSize;
}
CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
int32_t netInfoSize = 1;
#ifdef __WITH_DTLS__
- if (gSecureUnicastServerport)
+ if (g_secureUnicastServerport)
{
netInfoSize = 2;
}
#endif
- netInfo = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t) * netInfoSize);
+ netInfo = (CALocalConnectivity_t *) OICCalloc(netInfoSize, sizeof(CALocalConnectivity_t));
+
VERIFY_NON_NULL_RET(netInfo, WIFI_ADAPTER_TAG, "malloc failed", CA_MEMORY_ALLOC_FAILED);
- memset(netInfo, 0, sizeof(CALocalConnectivity_t) * netInfoSize);
char *ipAddress = NULL;
char *ifcName = NULL;
+
CAResult_t ret = CAWiFiGetInterfaceInfo(&ifcName, &ipAddress);
if (CA_STATUS_OK != ret || NULL == ipAddress)
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to get interface info [%d]", ret);
- if(netInfo)
- {
- OICFree(netInfo);
- }
- if(ipAddress)
- {
- OICFree(ipAddress);
- }
- if(ifcName)
- {
- OICFree(ifcName);
- }
+ OICFree(netInfo);
+ OICFree(ipAddress);
+ OICFree(ifcName);
+
return ret;
}
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to create Local Endpoint!",
CA_MEMORY_ALLOC_FAILED);
- if(netInfo)
- {
- OICFree(netInfo);
- }
- if(ipAddress)
- {
- OICFree(ipAddress);
- }
- if(ifcName)
- {
- OICFree(ifcName);
- }
+ OICFree(netInfo);
+ OICFree(ipAddress);
+ OICFree(ifcName);
+
return CA_MEMORY_ALLOC_FAILED;
}
- // copy unciast server information
- endpoint->isSecured = CA_FALSE;
- endpoint->addressInfo.IP.port = gUnicastServerport;
+ // copy unicast server information
+ endpoint->isSecured = false;
+ endpoint->addressInfo.IP.port = g_unicastServerport;
memcpy(&netInfo[0], endpoint, sizeof(CALocalConnectivity_t));
*size = 1;
#ifdef __WITH_DTLS__
- // copy sevure unicast server information
- if (gSecureUnicastServerport)
+ // copy secure unicast server information
+ if (g_secureUnicastServerport)
{
- endpoint->isSecured = CA_TRUE;
- endpoint->addressInfo.IP.port = gSecureUnicastServerport;
+ endpoint->isSecured = true;
+ endpoint->addressInfo.IP.port = g_secureUnicastServerport;
memcpy(&netInfo[1], endpoint, sizeof(CALocalConnectivity_t));
*size = 2;
}
#endif
*info = netInfo;
- if(ipAddress)
- {
- OICFree(ipAddress);
- }
- if(ifcName)
- {
- OICFree(ifcName);
- }
+ OICFree(ipAddress);
+ OICFree(ifcName);
+
CAAdapterFreeLocalEndpoint(endpoint);
OIC_LOG(INFO, WIFI_ADAPTER_TAG, "GetWIFIInterfaceInformation success");
if (CA_STATUS_OK == CAWiFiStopUnicastServer())
{
CAWiFiSetUnicastSocket(-1);
- gUnicastServerport = -1;
+ g_unicastServerport = -1;
}
#ifdef __WITH_DTLS__
// Stop secure unicast server and set client socket accordingly
if (CA_STATUS_OK == CAWiFiStopSecureUnicastServer())
{
CAWiFiSetSecureUnicastSocket(-1);
- gSecureUnicastServerport = -1;
+ g_secureUnicastServerport = -1;
}
#endif
//Stop multicast server and set the state accordingly
if (CA_STATUS_OK != CAWiFiStopMulticastServer())
{
- gIsMulticastServerStarted = false;
+ g_isMulticastServerStarted = false;
}
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
- gStartUnicastServerRequested = false;
- gStartMulticastServerRequested = false;
+ g_startUnicastServerRequested = false;
+ g_startMulticastServerRequested = false;
// Stop wifi network monitor
CAWiFiStopNetworkMonitor();
// Stop send queue thread
- if (gSendQueueHandle && CA_FALSE == gSendQueueHandle->isStop)
+ if (g_sendQueueHandle && false == g_sendQueueHandle->isStop)
{
- CAQueueingThreadStop(gSendQueueHandle);
+ CAQueueingThreadStop(g_sendQueueHandle);
}
// Stop Unicast, Secured unicast and Multicast servers running
return CA_STATUS_OK;
}
-void CATerminateWIfI()
+void CATerminateWIFI()
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
if (NULL != wifiData->remoteEndpoint)
{
char *address = wifiData->remoteEndpoint->addressInfo.IP.ipAddress;
- uint32_t port = wifiData->remoteEndpoint->addressInfo.IP.port;
+ uint16_t port = wifiData->remoteEndpoint->addressInfo.IP.port;
#ifdef __WITH_DTLS__
if (!wifiData->remoteEndpoint->isSecured)
}
else
{
- OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!");
+ OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt called!");
uint8_t cacheFalg = 0;
CAResult_t result = CAAdapterNetDtlsEncrypt(address, port, wifiData->data,
wifiData->dataLen, &cacheFalg, DTLS_WIFI);
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt failed!");
}
- OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt returned with cache[%d]",
+
+ OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "CAAdapterNetDtlsEncrypt returned with cache[%d]",
cacheFalg);
}
#else
return;
}
-CAWiFiData *CACreateWiFiData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+CAWiFiData *CACreateWiFiData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
uint32_t dataLength)
{
CAWiFiData *wifiData = (CAWiFiData *) OICMalloc(sizeof(CAWiFiData));
}
wifiData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
- wifiData->data = (void *)OICMalloc(dataLength);
+ wifiData->data = OICMalloc(dataLength);
if (NULL == wifiData->data)
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Memory allocation failed!");
+ CAAdapterFreeRemoteEndpoint(wifiData->remoteEndpoint);
CAFreeWiFiData(wifiData);
return NULL;
}
void CAFreeWiFiData(CAWiFiData *wifiData)
{
if (!wifiData)
+ {
return;
+ }
CAAdapterFreeRemoteEndpoint(wifiData->remoteEndpoint);
OICFree(wifiData->data);
CAFreeWiFiData(wfdata);
}
+
* @brief Port to listen for incoming data. Port 5683 is as per COAP RFC.
* Note :- Actual port number may differ based on result of bind() operation.
*/
-#define CA_PORT 5298
+#define CA_PORT 6298
/**
* @def CA_SECURE_PORT
/* Skip Queue */
/**
- * @var gNetworkPacketCallback
+ * @var g_networkPacketCallback
* @brief Network Packet Received Callback to CA
*/
-static CANetworkPacketReceivedCallback gNetworkPacketCallback = NULL;
+static CANetworkPacketReceivedCallback g_networkPacketCallback = NULL;
/**
- * @var gNetworkChangeCb
+ * @var g_networkChangeCallback
* @brief Network Changed Callback to CA
*/
-static CANetworkChangeCallback gNetworkChangeCallback = NULL;
+static CANetworkChangeCallback g_networkChangeCallback = NULL;
/**
- * @var gIsMulticastServerStarted
+ * @var g_isMulticastServerStarted
* @brief Flag to check if multicast server is started
*/
-static bool gIsMulticastServerStarted = false;
+static bool g_isMulticastServerStarted = false;
/**
- * @var gIsStartServerCalled
+ * @var g_startUnicastServerRequested
* @brief Flag to check if server start requested by CA.
*/
-static bool gStartUnicastServerRequested = false;
+static bool g_startUnicastServerRequested = false;
/**
- * @var gUnicastServerport
+ * @var g_unicastServerport
* @brief port number on which unicast server is running.
*/
-static int16_t gUnicastServerport = 0;
+static int16_t g_unicastServerport = 0;
/**
- * @var gIsStartServerCalled
+ * @var g_startMulticastServerRequested
* @brief Flag to check if server start requested by CA.
*/
-static bool gStartMulticastServerRequested = false;
+static bool g_startMulticastServerRequested = false;
-static void CAWiFiNotifyNetworkChange(const char *address, const int16_t port,
- const CANetworkStatus_t status);
+static void CAWiFiNotifyNetworkChange(const char *address, int16_t port,
+ CANetworkStatus_t status);
static void CAWiFiConnectionStateCB(const char *ipAddress,
- const CANetworkStatus_t status);
-static void CAWiFiPacketReceivedCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength);
+ CANetworkStatus_t status);
+static void CAWiFiPacketReceivedCB(const char *ipAddress, uint32_t port,
+ const void *data, uint32_t dataLength);
static CAResult_t CAWiFiStopServers();
-void CAWiFiNotifyNetworkChange(const char *address, const int16_t port,
- const CANetworkStatus_t status)
+void CAWiFiNotifyNetworkChange(const char *address, int16_t port,
+ CANetworkStatus_t status)
{
CALocalConnectivity_t *localEndpoint = CAAdapterCreateLocalEndpoint(CA_WIFI, address);
if (!localEndpoint)
}
localEndpoint->addressInfo.IP.port = port;
- if (NULL != gNetworkChangeCallback)
+ if (NULL != g_networkChangeCallback)
{
- gNetworkChangeCallback(localEndpoint, status);
+ g_networkChangeCallback(localEndpoint, status);
}
CAAdapterFreeLocalEndpoint(localEndpoint);
}
void CAWiFiConnectionStateCB(const char *ipAddr,
- const CANetworkStatus_t status)
+ CANetworkStatus_t status)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
int16_t port = CA_PORT;
int32_t serverFd = -1;
/* Start Unicast server if requested earlier */
- if (gStartUnicastServerRequested)
+ if (g_startUnicastServerRequested)
{
ret = CAWiFiStartUnicastServer("0.0.0.0", &port, false, &serverFd);
if (CA_STATUS_OK == ret)
{
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Unicast server started on %d port", port);
CAWiFiSetUnicastSocket(serverFd);
- gUnicastServerport = port;
+ g_unicastServerport = port;
}
else
{
- OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed [%d]", ret);
+ OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "strt ucast fail:%d", ret);
}
}
/* Start Multicast server if requested earlier */
- if (gStartMulticastServerRequested)
+ if (g_startMulticastServerRequested)
{
int16_t multicastPort = CA_MCAST_PORT;
ret = CAWiFiStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFd);
if (CA_STATUS_OK == ret)
{
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Multicast server started on %d port", multicastPort);
- gIsMulticastServerStarted = true;
+ g_isMulticastServerStarted = true;
}
else
{
- OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed [%d]", ret);
+ OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "strt mcast fail:%d", ret);
}
}
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
}
-void CAWiFiPacketReceivedCB(const char *ipAddress, const uint32_t port,
- const void *data, const uint32_t dataLength)
+void CAWiFiPacketReceivedCB(const char *ipAddress, uint32_t port,
+ const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Address: %s, port:%d ", ipAddress, port);
}
endPoint->addressInfo.IP.port = port;
- void *buf = OICMalloc(dataLength + 1);
- if (NULL == buf)
+ if (g_networkPacketCallback)
{
- OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Out of memory");
- CAAdapterFreeRemoteEndpoint(endPoint);
- return;
- }
- memcpy(buf, data, dataLength);
- memset(buf + dataLength, 0, 1);
- if (gNetworkPacketCallback)
- {
- gNetworkPacketCallback(endPoint, buf, dataLength);
+ g_networkPacketCallback(endPoint, data, dataLength);
}
CAAdapterFreeRemoteEndpoint(endPoint);
- OICFree(buf);
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
}
VERIFY_NON_NULL(networkPacketCallback, WIFI_ADAPTER_TAG, "networkPacketCallback");
VERIFY_NON_NULL(netCallback, WIFI_ADAPTER_TAG, "netCallback");
- gNetworkChangeCallback = netCallback;
- gNetworkPacketCallback = networkPacketCallback;
+ g_networkChangeCallback = netCallback;
+ g_networkPacketCallback = networkPacketCallback;
CAResult_t ret = CAWiFiInitializeNetworkMonitor();
if (CA_STATUS_OK != ret)
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to initialize server![%d]", ret);
- CATerminateWIfI();
+ CATerminateWIFI();
return ret;
}
CAWiFiSetPacketReceiveCallback(CAWiFiPacketReceivedCB);
CAConnectivityHandler_t wifiHandler;
wifiHandler.startAdapter = CAStartWIFI;
wifiHandler.startListenServer = CAStartWIFIListeningServer;
- wifiHandler.startDiscoverServer = CAStartWIFIDiscoveryServer;
+ wifiHandler.startDiscoveryServer = CAStartWIFIDiscoveryServer;
wifiHandler.sendData = CASendWIFIUnicastData;
wifiHandler.sendDataToAll = CASendWIFIMulticastData;
wifiHandler.GetnetInfo = CAGetWIFIInterfaceInformation;
wifiHandler.readData = CAReadWIFIData;
wifiHandler.stopAdapter = CAStopWIFI;
- wifiHandler.terminate = CATerminateWIfI;
+ wifiHandler.terminate = CATerminateWIFI;
registerCallback(wifiHandler, CA_WIFI);
OIC_LOG(INFO, WIFI_ADAPTER_TAG, "IntializeWifi Success");
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Failed to Start n/w monitor");
}
- gStartUnicastServerRequested = true;
+ g_startUnicastServerRequested = true;
bool retVal = CAWiFiIsConnected();
if (false == retVal)
{
{
OIC_LOG_V(DEBUG, WIFI_ADAPTER_TAG, "Unicast server started on %d port", unicastPort);
CAWiFiSetUnicastSocket(serverFd);
- gUnicastServerport = unicastPort;
+ g_unicastServerport = unicastPort;
}
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
CAResult_t ret = CA_STATUS_OK;
int16_t multicastPort = CA_MCAST_PORT;
- if (gIsMulticastServerStarted == true)
+ if (g_isMulticastServerStarted == true)
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Multicast Server, Already Started!");
return CA_SERVER_STARTED_ALREADY;
}
- gStartMulticastServerRequested = true;
+ g_startMulticastServerRequested = true;
// network monitor is yet to be implemented
bool retVal = CAWiFiIsConnected();
if (false == retVal)
{
OIC_LOG(INFO, WIFI_ADAPTER_TAG, "Multicast Server Started Successfully");
// iff wifi shield firmware upgrade allows multicast
- gIsMulticastServerStarted = true;
+ g_isMulticastServerStarted = true;
}
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
return CAStartWIFIListeningServer();
}
-uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
- uint32_t dataLength)
+int32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
+ uint32_t dataLength)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
- uint32_t dataSize = 0;
- VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ADAPTER_TAG, "remoteEndpoint", dataSize);
- VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", dataSize);
+ VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ADAPTER_TAG, "remoteEndpoint", -1);
+ VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", -1);
if (dataLength == 0)
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Invalid Data Length");
- return dataSize;
+ return -1;
}
CAWiFiSendData(remoteEndpoint->addressInfo.IP.ipAddress,
return dataLength;
}
-uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLength)
+int32_t CASendWIFIMulticastData(const void *data, uint32_t dataLength)
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
- uint32_t dataSize = 0;
- VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", dataSize);
+ VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", -1);
if (dataLength == 0)
{
OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Invalid Data Length");
- return dataSize;
+ return -1;
}
CAWiFiSendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, true);
if (false == retVal)
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG,
- "Failed to get interface address, WIFI not Connected", CA_ADAPTER_NOT_ENABLED);
+ "Failed to get interface address, Error Code: %d", CA_ADAPTER_NOT_ENABLED);
return CA_ADAPTER_NOT_ENABLED;
}
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to get interface info [%d]", ret);
+ OICFree(ipAddress);
+ OICFree(ifcName);
return ret;
}
(*info) = CAAdapterCreateLocalEndpoint(CA_WIFI, ipAddress);
if (NULL == (*info))
{
- OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to create Local Endpoint!",
+ OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to create Local Endpoint, Error Code:%d",
CA_MEMORY_ALLOC_FAILED);
OICFree(ipAddress);
OICFree(ifcName);
return CA_MEMORY_ALLOC_FAILED;
}
- (*info)->addressInfo.IP.port = gUnicastServerport;
+ (*info)->addressInfo.IP.port = g_unicastServerport;
(*size) = 1;
OICFree(ipAddress);
return result;
}
CAWiFiSetUnicastSocket(-1);
- gUnicastServerport = -1;
+ g_unicastServerport = -1;
result = CAWiFiStopMulticastServer();
if (CA_STATUS_OK != result)
OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Multicast Server![%d]", result);
return result;
}
- gIsMulticastServerStarted = false;
+ g_isMulticastServerStarted = false;
return result;
}
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
- gStartUnicastServerRequested = false;
- gStartMulticastServerRequested = false;
+ g_startUnicastServerRequested = false;
+ g_startMulticastServerRequested = false;
CAWiFiStopNetworkMonitor();
CAResult_t result = CAWiFiStopServers();
if (CA_STATUS_OK != result)
return result;
}
-void CATerminateWIfI()
+void CATerminateWIFI()
{
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
return;
}
-
#define WIFI_CLIENT_TAG "WIFI_CLIENT"
/**
- * @var gUnicastServerSocketDescClient
+ * @var g_unicastServerSocketDescClient
* @brief socket descriptor for unicast server
*/
-static int32_t gUnicastServerSocketDescClient = -1;
+static int32_t g_unicastServerSocketDescClient = -1;
#ifdef __WITH_DTLS__
/**
- * @var gUnicastServerSocketDescClient
+ * @var g_unicastServerSecureSocketDescClient
* @brief socket descriptor for secure unicast server
*/
-static int32_t gUnicastServerSecureSocketDescClient = -1;
+static int32_t g_unicastServerSecureSocketDescClient = -1;
#endif
-static uint32_t CASendData(const char *remoteAddress, const uint32_t port,
+static uint32_t CASendData(const char *remoteAddress, const uint16_t port,
const void *data, const uint32_t dataLength, int32_t sockfd)
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
- gUnicastServerSocketDescClient = socketFD;
+ g_unicastServerSocketDescClient = socketFD;
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT");
}
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
- gUnicastServerSecureSocketDescClient = socketFD;
+ g_unicastServerSecureSocketDescClient = socketFD;
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT");
}
#endif
-uint32_t CAWiFiSendData(const char *remoteAddress, const uint32_t port,
+uint32_t CAWiFiSendData(const char *remoteAddress, const uint16_t port,
const void *data, const uint32_t dataLength,
- CABool_t isMulticast, CABool_t isSecured)
+ bool isMulticast, bool isSecured)
{
uint32_t len = 0;
#ifdef __WITH_DTLS__
- if (CA_TRUE == isSecured)
+ if (true == isSecured)
{
len = CASendData(remoteAddress, port,
- data, dataLength, gUnicastServerSecureSocketDescClient);
+ data, dataLength, g_unicastServerSecureSocketDescClient);
}
else
{
#endif
len = CASendData(remoteAddress, port,
- data, dataLength, gUnicastServerSocketDescClient);
+ data, dataLength, g_unicastServerSocketDescClient);
#ifdef __WITH_DTLS__
}
#endif
}
+
#define WIFI_MONITOR_TAG "WIFI_MONITOR"
/**
- * @var nwConnectivityStatus
+ * @var g_nwConnectivityStatus
* @brief Maintains network status.
*/
-static CANetworkStatus_t nwConnectivityStatus;
+static CANetworkStatus_t g_nwConnectivityStatus;
/**
- * @var gWifiNetInfoMutex
+ * @var g_wifiNetInfoMutex
* @brief Mutex for synchronizing access to cached interface and IP address information.
*/
-static u_mutex gWifiNetInfoMutex = NULL;
+static u_mutex g_wifiNetInfoMutex = NULL;
/**
- * @var gWifiInterfaceName
+ * @var g_wifiInterfaceName
* @brief Maintains interface name.
*/
-static char *gWifiInterfaceName = NULL;
+static char *g_wifiInterfaceName = NULL;
/**
- * @var gWifiIPAddress
+ * @var g_wifiIPAddress
* @brief Maintains interface IP address.
*/
-static char *gWifiIPAddress = NULL;
+static char *g_wifiIPAddress = NULL;
/**
- * @var gWifiSubnetMask
+ * @var g_wifiSubnetMask
* @brief Maintains interface subnetmask.
*/
-static char *gWifiSubnetMask = NULL;
+static char *g_wifiSubnetMask = NULL;
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from adapter
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
/**
- * @var gStopNetworkMonitor
+ * @var g_stopNetworkMonitor
* @brief Flag to control the Network Monitor Thread
*/
-static bool gStopNetworkMonitor = false;
+static bool g_stopNetworkMonitor = false;
/**
- * @var gNetworkChangeCb
+ * @var g_networkChangeCb
* @brief Maintains network connection state change callback.
*/
-static CAWiFiConnectionStateChangeCallback gNetworkChangeCb = NULL;
+static CAWiFiConnectionStateChangeCallback g_networkChangeCb = NULL;
/**
* @fn CAWiFiGetInterfaceInformation
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- gThreadPool = threadPool;
+ g_threadPool = threadPool;
- if (!gWifiNetInfoMutex)
+ if (!g_wifiNetInfoMutex)
{
- gWifiNetInfoMutex = u_mutex_new();
+ g_wifiNetInfoMutex = u_mutex_new();
}
- u_mutex_lock(gWifiNetInfoMutex);
- CAWiFiGetInterfaceInformation(&gWifiInterfaceName, &gWifiIPAddress, &gWifiSubnetMask);
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
+ CAWiFiGetInterfaceInformation(&g_wifiInterfaceName, &g_wifiIPAddress, &g_wifiSubnetMask);
+ u_mutex_unlock(g_wifiNetInfoMutex);
- nwConnectivityStatus = (gWifiIPAddress) ? CA_INTERFACE_UP : CA_INTERFACE_DOWN;
+ g_nwConnectivityStatus = (g_wifiIPAddress) ? CA_INTERFACE_UP : CA_INTERFACE_DOWN;
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- gThreadPool = NULL;
+ g_threadPool = NULL;
- if (gWifiInterfaceName)
+ if (g_wifiInterfaceName)
{
- OICFree(gWifiInterfaceName);
- gWifiInterfaceName = NULL;
+ OICFree(g_wifiInterfaceName);
+ g_wifiInterfaceName = NULL;
}
- if (gWifiIPAddress)
+ if (g_wifiIPAddress)
{
- OICFree(gWifiIPAddress);
- gWifiIPAddress = NULL;
+ OICFree(g_wifiIPAddress);
+ g_wifiIPAddress = NULL;
}
- if (gWifiSubnetMask)
+ if (g_wifiSubnetMask)
{
- OICFree(gWifiSubnetMask);
- gWifiSubnetMask = NULL;
+ OICFree(g_wifiSubnetMask);
+ g_wifiSubnetMask = NULL;
}
- if (gWifiNetInfoMutex)
+ if (g_wifiNetInfoMutex)
{
- u_mutex_free(gWifiNetInfoMutex);
- gWifiNetInfoMutex = NULL;
+ u_mutex_free(g_wifiNetInfoMutex);
+ g_wifiNetInfoMutex = NULL;
}
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- u_mutex_lock(gWifiNetInfoMutex);
- gStopNetworkMonitor = false;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
+ g_stopNetworkMonitor = false;
+ u_mutex_unlock(g_wifiNetInfoMutex);
- if (gStopNetworkMonitor)
+ if (g_stopNetworkMonitor)
{
OIC_LOG_V(ERROR, WIFI_MONITOR_TAG, "Stop network monitor requested!");
return CA_STATUS_FAILED;
}
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CANetworkMonitorThread,
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CANetworkMonitorThread,
NULL))
{
OIC_LOG(ERROR, WIFI_MONITOR_TAG, "[ThreadPool] thread_pool_add_task failed!");
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- if (gStopNetworkMonitor)
+ if (g_stopNetworkMonitor)
{
OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "CAWiFiStopNetworkMonitor, already stopped");
return CA_STATUS_OK;
}
- u_mutex_lock(gWifiNetInfoMutex);
- gStopNetworkMonitor = true;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
+ g_stopNetworkMonitor = true;
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(ipAddress, WIFI_MONITOR_TAG, "ip address");
// Get the interface and ipaddress information from cache
- u_mutex_lock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
- if (gWifiInterfaceName == NULL || gWifiIPAddress == NULL)
+ if (g_wifiInterfaceName == NULL || g_wifiIPAddress == NULL)
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "Network not enabled");
return CA_ADAPTER_NOT_ENABLED;
}
- *interfaceName = (gWifiInterfaceName) ? strndup(gWifiInterfaceName, strlen(gWifiInterfaceName))
+ *interfaceName = (g_wifiInterfaceName) ? strndup(g_wifiInterfaceName, strlen(g_wifiInterfaceName))
: NULL;
- *ipAddress = (gWifiIPAddress) ? strndup(gWifiIPAddress, strlen(gWifiIPAddress))
+ *ipAddress = (g_wifiIPAddress) ? strndup(g_wifiIPAddress, strlen(g_wifiIPAddress))
: NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(subnetMask, WIFI_MONITOR_TAG, "subnet mask");
- u_mutex_lock(gWifiNetInfoMutex);
- if (NULL == gWifiSubnetMask)
+ u_mutex_lock(g_wifiNetInfoMutex);
+ if (NULL == g_wifiSubnetMask)
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "There is no subnet mask information!");
return CA_STATUS_FAILED;
}
- *subnetMask = (gWifiSubnetMask) ? strndup(gWifiSubnetMask, strlen(gWifiSubnetMask))
+ *subnetMask = (g_wifiSubnetMask) ? strndup(g_wifiSubnetMask, strlen(g_wifiSubnetMask))
: NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- if (nwConnectivityStatus == CA_INTERFACE_DOWN)
+ if (g_nwConnectivityStatus == CA_INTERFACE_DOWN)
return false;
return true;
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- gNetworkChangeCb = callback;
+ g_networkChangeCb = callback;
}
void CAWiFiGetInterfaceInformation(char **interfaceName, char **ipAddress, char **subnetMask)
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- while (!gStopNetworkMonitor)
+ while (!g_stopNetworkMonitor)
{
// Get network information
CANetworkStatus_t currNetworkStatus;
currNetworkStatus = (ipAddress) ? CA_INTERFACE_UP : CA_INTERFACE_DOWN;
// if network status is changed
- if (currNetworkStatus != nwConnectivityStatus)
+ if (currNetworkStatus != g_nwConnectivityStatus)
{
// set current network information
- u_mutex_lock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
- nwConnectivityStatus = currNetworkStatus;
+ g_nwConnectivityStatus = currNetworkStatus;
- OICFree(gWifiInterfaceName);
- OICFree(gWifiIPAddress);
- OICFree(gWifiSubnetMask);
- gWifiInterfaceName = (interfaceName) ? strndup(interfaceName, strlen(interfaceName)) : NULL;
- gWifiIPAddress = (ipAddress) ? strndup(ipAddress, strlen(ipAddress)) : NULL;
- gWifiSubnetMask = (subnetMask) ? strndup(subnetMask, strlen(subnetMask)) : NULL;
+ OICFree(g_wifiInterfaceName);
+ OICFree(g_wifiIPAddress);
+ OICFree(g_wifiSubnetMask);
+ g_wifiInterfaceName = (interfaceName) ? strndup(interfaceName, strlen(interfaceName)) : NULL;
+ g_wifiIPAddress = (ipAddress) ? strndup(ipAddress, strlen(ipAddress)) : NULL;
+ g_wifiSubnetMask = (subnetMask) ? strndup(subnetMask, strlen(subnetMask)) : NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
- if (gNetworkChangeCb)
+ if (g_networkChangeCb)
{
- gNetworkChangeCb(gWifiIPAddress, nwConnectivityStatus);
+ g_networkChangeCb(g_wifiIPAddress, g_nwConnectivityStatus);
}
}
OICFree(interfaceName);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
}
+
/******************************************************************
-*
-* Copyright 2014 Samsung Electronics All Rights Reserved.
-*
-*
-*
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-*
-******************************************************************/
+ *
+ * Copyright 2014 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
#include "cawifiinterface.h"
#include <sys/types.h>
#include "caadapternetdtls.h"
#endif
#include "umutex.h"
+#include "oic_malloc.h"
/**
* @def WIFI_SERVER_TAG
#define IPNAMESIZE 16
/**
- * @var gUnicastServerSocketFD
+ * @var g_unicastServerSocketFD
* @brief Unicast server socket descriptor
*/
-static int32_t gUnicastServerSocketFD = -1;
+static int32_t g_unicastServerSocketFD = -1;
/**
- * @var gMutexUnicastServer
+ * @var g_mutexUnicastServer
* @brief Mutex to synchronize unicast server
*/
-static u_mutex gMutexUnicastServer = NULL;
+static u_mutex g_mutexUnicastServer = NULL;
/**
- * @var gStopUnicast
+ * @var g_stopUnicast
* @brief Flag to control the Receive Unicast Data Thread
*/
-static bool gStopUnicast = false;
+static bool g_stopUnicast = false;
/**
- * @var gMulticastServerSocketFD
+ * @var g_multicastServerSocketFD
* @brief socket descriptor for multicast server
*/
-static int32_t gMulticastServerSocketFD = -1;
+static int32_t g_multicastServerSocketFD = -1;
/**
- * @var gMutexMulticastServer
+ * @var g_mutexMulticastServer
* @brief Mutex to synchronize secure multicast server
*/
-static u_mutex gMutexMulticastServer = NULL;
+static u_mutex g_mutexMulticastServer = NULL;
/**
- * @var gStopMulticast
+ * @var g_stopMulticast
* @brief Flag to control the Receive Multicast Data Thread
*/
-static bool gStopMulticast = false;
+static bool g_stopMulticast = false;
#ifdef __WITH_DTLS__
/**
- * @var gSecureUnicastServerSocketFD
+ * @var g_secureUnicastServerSocketFD
* @brief Secure unicast server socket descriptor
*/
-static int32_t gSecureUnicastServerSocketFD = -1;
+static int32_t g_secureUnicastServerSocketFD = -1;
/**
- * @var gMutexSecureUnicastServer
+ * @var g_mutexSecureUnicastServer
* @brief Mutex to synchronize secure unicast server
*/
-static u_mutex gMutexSecureUnicastServer = NULL;
+static u_mutex g_mutexSecureUnicastServer = NULL;
/**
- * @var gStopSecureUnicast
+ * @var g_stopSecureUnicast
* @brief Flag to control the unicast secure data receive thread
*/
-static bool gStopSecureUnicast = false;
+static bool g_stopSecureUnicast = false;
#endif
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from adapter
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
/**
- * @var gMulticastServerInterface
+ * @var g_multicastServerInterface
* @brief Local interface on which multicast server is running
*/
-static char gMulticastServerInterface[IPNAMESIZE];
+static char g_multicastServerInterface[IPNAMESIZE];
/**
- * @var gMulticastMemberReq
+ * @var g_multicastMemberReq
* @brief ip_mreq structure passed to join a multicast group
*/
-static struct ip_mreq gMulticastMemberReq;
+static struct ip_mreq g_multicastMemberReq;
/**
- * @var gPacketReceivedCallback
+ * @var g_packetReceivedCallback
* @brief Callback for notifying the upper layer on receival data from remote OIC device
*/
-static CAWiFiPacketReceivedCallback gPacketReceivedCallback = NULL;
+static CAWiFiPacketReceivedCallback g_packetReceivedCallback = NULL;
/**
- * @var gExceptionCallback
+ * @var g_exceptionCallback
* @brief Callback for notifying the upper layer when unicast/multicast server encounters exception
*/
-static CAWiFiExceptionCallback gExceptionCallback = NULL;
+static CAWiFiExceptionCallback g_exceptionCallback = NULL;
/**
@brief Thread context information for unicast, multicast and secured unicast server
// Input validation
VERIFY_NON_NULL_VOID(data, WIFI_SERVER_TAG, "Invalid thread context");
- CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *)data;
+ CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *) data;
fd_set reads;
struct timeval timeout;
- char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
+ char recvBuffer[COAP_MAX_PDU_SIZE] =
+ { 0 };
while (true != *(ctx->stopFlag))
{
struct sockaddr_in srcSockAddress;
int32_t recvLen;
socklen_t srcAddressLen = sizeof(srcSockAddress);
- if (-1 == (recvLen = recvfrom(ctx->socket_fd, recvBuffer,
- sizeof(recvBuffer), 0, (struct sockaddr *) &srcSockAddress,
- &srcAddressLen)))
+ if (-1
+ == (recvLen = recvfrom(ctx->socket_fd, recvBuffer, sizeof(recvBuffer), 0,
+ (struct sockaddr *) &srcSockAddress, &srcAddressLen)))
{
OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "%s", strerror(errno));
continue;
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Server socket shutdown [%d]!", ctx->type);
// Notify upper layer this exception
- if (gExceptionCallback)
+ if (g_exceptionCallback)
{
- gExceptionCallback(ctx->type);
+ g_exceptionCallback(ctx->type);
}
OICFree(ctx);
return;
}
const char *srcIPAddress = NULL;
- int32_t srcPort = -1;
+ uint16_t srcPort = 0;
srcIPAddress = inet_ntoa(srcSockAddress.sin_addr);
srcPort = ntohs(srcSockAddress.sin_port);
- OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Received packet from %s:%d\n",
- srcIPAddress, srcPort);
- OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Data: %s\t, DataLength: %d\n",
- recvBuffer, recvLen);
+ OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Received packet from %s:%d\n", srcIPAddress, srcPort);
+ OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Data: %s\t, DataLength: %d\n", recvBuffer, recvLen);
char *netMask = NULL;
if (CA_STATUS_OK != CAWiFiGetInterfaceSubnetMask(&netMask))
continue;
}
- if (!CAAdapterIsSameSubnet(gMulticastServerInterface, srcIPAddress, netMask))
+ if (!CAAdapterIsSameSubnet(g_multicastServerInterface, srcIPAddress, netMask))
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "Packet received from different subnet, Ignore!");
if (NULL != netMask)
case CA_UNICAST_SERVER:
case CA_MULTICAST_SERVER:
// Notify data to upper layer
- if (gPacketReceivedCallback)
+ if (g_packetReceivedCallback)
{
- gPacketReceivedCallback(srcIPAddress, srcPort, recvBuffer, recvLen, false);
+ g_packetReceivedCallback(srcIPAddress, srcPort, recvBuffer, recvLen, false);
}
break;
#ifdef __WITH_DTLS__
- case CA_SECURED_UNICAST_SERVER:
+ case CA_SECURED_UNICAST_SERVER:
{
CAResult_t ret = CAAdapterNetDtlsDecrypt(srcIPAddress,
- srcPort,
- (uint8_t *)recvBuffer,
- recvLen, DTLS_WIFI);
+ srcPort,
+ (uint8_t *)recvBuffer,
+ recvLen, DTLS_WIFI);
OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "CAAdapterNetDtlsDecrypt returns [%d]", ret);
}
break;
#endif //__WITH_DTLS__
default:
- // Should never occur
- OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Invalid server type");
+ // Should never occur\r OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Invalid server type");
OICFree(ctx);
return;
}
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
-static CAResult_t CAWiFiCreateSocket(int32_t *socketFD, const char *localIp, int16_t *port,
- const bool forceStart)
+static CAResult_t CAWiFiCreateSocket(int32_t *socketFD, const char *localIp, uint16_t *port,
+ const bool forceStart)
{
int32_t sock = -1;
// Create a UDP socket
if (-1 == (sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to create Socket, Error code: %s",
- strerror(errno));
+ strerror(errno));
return CA_STATUS_FAILED;
}
if (-1 == fcntl(sock, F_SETFL, O_NONBLOCK))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to set non-block mode, Error code: %s",
- strerror(errno));
+ strerror(errno));
close(sock);
return CA_STATUS_FAILED;
if (true == forceStart)
{
int32_t setOptionOn = 1;
- if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
- (char *) &setOptionOn,
- sizeof(setOptionOn)))
+ if (-1
+ == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &setOptionOn,
+ sizeof(setOptionOn)))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to set SO_REUSEADDR! Error code: %s",
- strerror(errno));
+ strerror(errno));
close(sock);
return CA_STATUS_FAILED;
struct sockaddr_in sockAddr;
bool isBound = false;
- int16_t serverPort = *port;
+ uint16_t serverPort = 0;
+ if (port)
+ {
+ serverPort = *port;
+ }
+ else
+ {
+ close(sock);
+ return CA_STATUS_INVALID_PARAM;
+ }
memset((char *) &sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
int16_t i;
for (i = 0; i < CA_UDP_BIND_RETRY_COUNT; i++)
{
- if (-1 == bind(sock, (struct sockaddr *) &sockAddr,
- sizeof(sockAddr)))
+ if (-1 == bind(sock, (struct sockaddr *) &sockAddr, sizeof(sockAddr)))
{
if (false == forceStart)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to bind socket[%s]. Trying again..",
- strerror(errno));
+ strerror(errno));
//Set the port to next one
serverPort += 1;
}
else
{
- OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to bind socket[%s]!",
- strerror(errno));
+ OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to bind socket[%s]!", strerror(errno));
break;
}
}
static CAResult_t CAWiFiCloseSocket(int32_t *socketFD)
{
+ if (socketFD == NULL)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
+
if (-1 == *socketFD)
{
OIC_LOG(INFO, WIFI_SERVER_TAG, "Server not running");
if (-1 == close(*socketFD))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to close the socket, Error code: %s\n",
- strerror(errno));
+ strerror(errno));
return CA_STATUS_FAILED;
}
return CA_STATUS_OK;
}
-static CAResult_t CAStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, bool isSecured, int32_t *serverFD)
+static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port,
+ const bool forceStart, bool isSecured, int32_t *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
+ if (serverFD == NULL)
+ {
+ return CA_STATUS_INVALID_PARAM;
+ }
+
CAResult_t ret = CAWiFiCreateSocket(serverFD, localAddress, port, forceStart);
if (CA_STATUS_OK != ret)
{
}
/**
- * The task to listen for data from unicast socket is added to the thread pool.
- * This is a blocking call is made where we try to receive some data..
- * We will keep waiting until some data is received.
- * This task will be terminated when thread pool is freed on stopping the adapters.
- * Thread context will be freed by thread on exit.
- */
- CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *)
- OICMalloc(sizeof(CAAdapterReceiveThreadContext_t));
+ * The task to listen for data from unicast socket is added to the thread pool.
+ * This is a blocking call is made where we try to receive some data..
+ * We will keep waiting until some data is received.
+ * This task will be terminated when thread pool is freed on stopping the adapters.
+ * Thread context will be freed by thread on exit.
+ */
+ CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *) OICMalloc(
+ sizeof(CAAdapterReceiveThreadContext_t));
if (!ctx)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Out of memory!");
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopUnicast;
+ ctx->stopFlag = &g_stopUnicast;
ctx->socket_fd = *serverFD;
ctx->type = isSecured ? CA_SECURED_UNICAST_SERVER : CA_UNICAST_SERVER;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CAReceiveHandler, (void *)ctx))
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CAReceiveHandler, (void *) ctx))
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to create read thread!");
- OICFree((void *)ctx);
+ OICFree((void *) ctx);
close(*serverFD);
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- if (gMutexUnicastServer)
+ if (g_mutexUnicastServer)
{
- u_mutex_free(gMutexUnicastServer);
- gMutexUnicastServer = NULL;
+ u_mutex_free(g_mutexUnicastServer);
+ g_mutexUnicastServer = NULL;
}
#ifdef __WITH_DTLS__
- if (gMutexSecureUnicastServer)
+ if (g_mutexSecureUnicastServer)
{
- u_mutex_free(gMutexSecureUnicastServer);
- gMutexSecureUnicastServer = NULL;
+ u_mutex_free(g_mutexSecureUnicastServer);
+ g_mutexSecureUnicastServer = NULL;
}
#endif
- if (gMutexMulticastServer)
+ if (g_mutexMulticastServer)
{
- u_mutex_free(gMutexMulticastServer);
- gMutexMulticastServer = NULL;
+ u_mutex_free(g_mutexMulticastServer);
+ g_mutexMulticastServer = NULL;
}
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gMutexUnicastServer = u_mutex_new();
- if (!gMutexUnicastServer)
+ g_mutexUnicastServer = u_mutex_new();
+ if (!g_mutexUnicastServer)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
#ifdef __WITH_DTLS__
- gMutexSecureUnicastServer = u_mutex_new();
- if (!gMutexSecureUnicastServer)
+ g_mutexSecureUnicastServer = u_mutex_new();
+ if (!g_mutexSecureUnicastServer)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
}
#endif
- gMutexMulticastServer = u_mutex_new();
- if (!gMutexMulticastServer)
+ g_mutexMulticastServer = u_mutex_new();
+ if (!g_mutexMulticastServer)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
return CA_STATUS_FAILED;
}
- gThreadPool = threadPool;
+ g_threadPool = threadPool;
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gThreadPool = NULL;
+ g_threadPool = NULL;
// Destroy mutex
CAWiFiServerDestroyMutex();
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
-CAResult_t CAWiFiStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, const CABool_t isSecured,
- int32_t *serverFD)
+CAResult_t CAWiFiStartUnicastServer(const char *localAddress, uint16_t *port, const bool forceStart,
+ const bool isSecured, int32_t *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
}
*serverFD = -1;
- if (CA_FALSE == isSecured)
+ if (false == isSecured)
{
- u_mutex_lock(gMutexUnicastServer);
- if (-1 != gUnicastServerSocketFD)
+ u_mutex_lock(g_mutexUnicastServer);
+ if (-1 != g_unicastServerSocketFD)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Unicast Server is Started Already!",
- CA_SERVER_STARTED_ALREADY);
+ CA_SERVER_STARTED_ALREADY);
- *serverFD = gUnicastServerSocketFD;
- u_mutex_unlock(gMutexUnicastServer);
+ *serverFD = g_unicastServerSocketFD;
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_SERVER_STARTED_ALREADY;
}
- gStopUnicast = false;
- if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
- &gUnicastServerSocketFD))
+ g_stopUnicast = false;
+ if (CA_STATUS_OK
+ != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
+ &g_unicastServerSocketFD))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to start unicast server!");
- gUnicastServerSocketFD = -1;
- u_mutex_unlock(gMutexUnicastServer);
+ g_unicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gUnicastServerSocketFD;
- u_mutex_unlock(gMutexUnicastServer);
+ *serverFD = g_unicastServerSocketFD;
+ u_mutex_unlock(g_mutexUnicastServer);
}
#ifdef __WITH_DTLS__
else // Start unicast server for secured communication
{
- u_mutex_lock(gMutexSecureUnicastServer);
- if (-1 != gSecureUnicastServerSocketFD)
+ u_mutex_lock(g_mutexSecureUnicastServer);
+ if (-1 != g_secureUnicastServerSocketFD)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Unicast Server is Started Already!",
- CA_SERVER_STARTED_ALREADY);
+ CA_SERVER_STARTED_ALREADY);
- *serverFD = gSecureUnicastServerSocketFD;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ *serverFD = g_secureUnicastServerSocketFD;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
return CA_SERVER_STARTED_ALREADY;
}
- gStopSecureUnicast = false;
+ g_stopSecureUnicast = false;
if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
- &gSecureUnicastServerSocketFD))
+ &g_secureUnicastServerSocketFD))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to start unicast server!");
- gSecureUnicastServerSocketFD = -1;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ g_secureUnicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gSecureUnicastServerSocketFD;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ *serverFD = g_secureUnicastServerSocketFD;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
}
#endif
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD)
+ const uint16_t multicastPort, int32_t *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
VERIFY_NON_NULL(multicastAddress, WIFI_SERVER_TAG, "port");
VERIFY_NON_NULL(serverFD, WIFI_SERVER_TAG, "server socket FD");
- int16_t port = multicastPort;
+ uint16_t port = multicastPort;
if (0 >= port)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Invalid input: Multicast port is invalid!");
return CA_STATUS_INVALID_PARAM;
}
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
- if (gMulticastServerSocketFD != -1)
+ if (g_multicastServerSocketFD != -1)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Multicast Server is already running!");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_SERVER_STARTED_ALREADY;
}
- CAResult_t ret = CAWiFiCreateSocket(&gMulticastServerSocketFD, multicastAddress, &port, true);
+ CAResult_t ret = CAWiFiCreateSocket(&g_multicastServerSocketFD, multicastAddress, &port, true);
if (ret != CA_STATUS_OK)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to create multicast socket");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return ret;
}
// Add membership to receiving socket (join group)
- memset(&gMulticastMemberReq, 0, sizeof(struct ip_mreq));
- gMulticastMemberReq.imr_interface.s_addr = inet_addr(localAddress);
- inet_aton(multicastAddress, &gMulticastMemberReq.imr_multiaddr);
+ memset(&g_multicastMemberReq, 0, sizeof(struct ip_mreq));
+ g_multicastMemberReq.imr_interface.s_addr = inet_addr(localAddress);
+ inet_aton(multicastAddress, &g_multicastMemberReq.imr_multiaddr);
- if (-1 == setsockopt(gMulticastServerSocketFD, IPPROTO_IP, IP_ADD_MEMBERSHIP,
- (char *) &gMulticastMemberReq,
- sizeof(struct ip_mreq)))
+ if (-1
+ == setsockopt(g_multicastServerSocketFD, IPPROTO_IP, IP_ADD_MEMBERSHIP,
+ (char *) &g_multicastMemberReq, sizeof(struct ip_mreq)))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to add to multicast group, Error code: %s\n",
- strerror(errno));
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
- u_mutex_unlock(gMutexMulticastServer);
+ strerror(errno));
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_STATUS_FAILED;
}
/**
- * The task to listen to data from multicastcast socket is added to the thread pool.
- * This is a blocking call is made where we try to receive some data.
- * We will keep waiting until some data is received.
- * This task will be terminated when thread pool is freed on stopping the adapters.
- * Thread context will be freed by thread on exit.
- */
- CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *)
- OICMalloc(sizeof(CAAdapterReceiveThreadContext_t));
+ * The task to listen to data from multicastcast socket is added to the thread pool.
+ * This is a blocking call is made where we try to receive some data.
+ * We will keep waiting until some data is received.
+ * This task will be terminated when thread pool is freed on stopping the adapters.
+ * Thread context will be freed by thread on exit.
+ */
+ CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *) OICMalloc(
+ sizeof(CAAdapterReceiveThreadContext_t));
if (!ctx)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Out of memory!");
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopMulticast;
- ctx->socket_fd = gMulticastServerSocketFD;
+ ctx->stopFlag = &g_stopMulticast;
+ ctx->socket_fd = g_multicastServerSocketFD;
ctx->type = CA_MULTICAST_SERVER;
- gStopMulticast = false;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CAReceiveHandler, (void *)ctx))
+ g_stopMulticast = false;
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CAReceiveHandler, (void *) ctx))
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "thread_pool_add_task failed!");
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
- gStopMulticast = true;
- u_mutex_unlock(gMutexMulticastServer);
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
+ g_stopMulticast = true;
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gMulticastServerSocketFD;
- strncpy(gMulticastServerInterface, localAddress, IPNAMESIZE);
- u_mutex_unlock(gMutexMulticastServer);
+ *serverFD = g_multicastServerSocketFD;
+ strncpy(g_multicastServerInterface, localAddress, IPNAMESIZE);
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexUnicastServer);
- gStopUnicast = true;
- CAResult_t ret = CAWiFiCloseSocket(&gUnicastServerSocketFD);
- u_mutex_unlock(gMutexUnicastServer);
+ u_mutex_lock(g_mutexUnicastServer);
+ g_stopUnicast = true;
+ CAResult_t ret = CAWiFiCloseSocket(&g_unicastServerSocketFD);
+ u_mutex_unlock(g_mutexUnicastServer);
OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Unicast server stopped [%d]", ret);
return ret;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexSecureUnicastServer);
- gStopSecureUnicast = true;
- CAResult_t ret = CAWiFiCloseSocket(&gSecureUnicastServerSocketFD);
- u_mutex_unlock(gMutexSecureUnicastServer);
+ u_mutex_lock(g_mutexSecureUnicastServer);
+ g_stopSecureUnicast = true;
+ CAResult_t ret = CAWiFiCloseSocket(&g_secureUnicastServerSocketFD);
+ u_mutex_unlock(g_mutexSecureUnicastServer);
OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Secured unicast server stopped [%d]", ret);
return ret;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
- if (gMulticastServerSocketFD == -1)
+ if (g_multicastServerSocketFD == -1)
{
OIC_LOG(INFO, WIFI_SERVER_TAG, "Multicast server is not yet started");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_SERVER_NOT_STARTED;
}
- gStopMulticast = true;
+ g_stopMulticast = true;
// leave the group after you are done
- if (-1 == setsockopt(gMulticastServerSocketFD, IPPROTO_IP, IP_DROP_MEMBERSHIP,
- (char *)&gMulticastMemberReq,
- sizeof(struct ip_mreq)))
+ if (-1
+ == setsockopt(g_multicastServerSocketFD, IPPROTO_IP, IP_DROP_MEMBERSHIP,
+ (char *) &g_multicastMemberReq, sizeof(struct ip_mreq)))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to leave multicast group, Error code: %s\n",
- strerror(errno));
+ strerror(errno));
}
- CAResult_t ret = CAWiFiCloseSocket(&gMulticastServerSocketFD);
- u_mutex_unlock(gMutexMulticastServer);
+ CAResult_t ret = CAWiFiCloseSocket(&g_multicastServerSocketFD);
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Multicast server stopped [%d]", ret);
return ret;
}
-CAResult_t CAWiFiGetUnicastServerInfo(const CABool_t isSecured, char **ipAddress,
- int16_t *port, int32_t *serverFD)
+CAResult_t CAWiFiGetUnicastServerInfo(const bool isSecured, char **ipAddress, uint16_t *port,
+ int32_t *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
struct sockaddr_in sockAddr;
socklen_t len = sizeof(struct sockaddr_in);
- if (-1 == getsockname(gUnicastServerSocketFD, (struct sockaddr *)&sockAddr, &len))
+ if (-1 == getsockname(g_unicastServerSocketFD, (struct sockaddr *) &sockAddr, &len))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed in getsockname [%s]!", strerror(errno));
return CA_STATUS_FAILED;
}
+ char serverAddress[CA_IPADDR_SIZE];
+ inet_ntop(AF_INET, &sockAddr.sin_addr.s_addr, serverAddress, sizeof(serverAddress));
- const char *serverAddress = inet_ntoa(sockAddr.sin_addr);
- *ipAddress = (serverAddress) ? strndup(serverAddress, strlen(serverAddress)) : NULL;
+ *ipAddress = strndup(serverAddress, strlen(serverAddress));
*port = ntohs(sockAddr.sin_port);
#ifdef __WITH_DTLS__
- *serverFD = (CA_TRUE == isSecured) ? gSecureUnicastServerSocketFD : gUnicastServerSocketFD;
+ *serverFD = (true == isSecured) ? g_secureUnicastServerSocketFD : g_unicastServerSocketFD;
#else
- *serverFD = gUnicastServerSocketFD;
+ *serverFD = g_unicastServerSocketFD;
#endif
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gPacketReceivedCallback = callback;
+ g_packetReceivedCallback = callback;
}
void CAWiFiSetExceptionCallback(CAWiFiExceptionCallback callback)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gExceptionCallback = callback;
+ g_exceptionCallback = callback;
}
-
#define WIFI_CLIENT_TAG "WIFI_CLIENT"
/**
- * @var gUnicastServerSocketDescClient
+ * @var g_unicastServerSocketDescClient
* @brief socket descriptor for unicast server
*/
-static int32_t gUnicastServerSocketDescClient = -1;
+static int g_unicastServerSocketDescClient = -1;
#ifdef __WITH_DTLS__
/**
- * @var gUnicastServerSocketDescClient
+ * @var g_unicastServerSocketDescClient
* @brief socket descriptor for secure unicast server
*/
-static int32_t gUnicastServerSecureSocketDescClient = -1;
+static int g_unicastServerSecureSocketDescClient = -1;
#endif
-static uint32_t CASendData(const char *remoteAddress, const uint32_t port,
- const void *data, const uint32_t dataLength, int32_t sockfd)
+static uint32_t CASendData(const char *remoteAddress, uint16_t port,
+ const void *data, uint32_t dataLength, int sockfd)
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
return 0;
}
- struct sockaddr_in destAddr;
- memset((char *)&destAddr, 0, sizeof(destAddr));
+ struct sockaddr_in destAddr = {0};
destAddr.sin_family = AF_INET;
destAddr.sin_port = htons(port);
return 0;
}
- int32_t sendDataLength = sendto(sockfd, data, dataLength, 0,
+ int sendDataLength = sendto(sockfd, data, dataLength, 0,
(struct sockaddr *)&destAddr, sizeof(destAddr));
if (sendDataLength == -1)
{
return sendDataLength;
}
-void CAWiFiSetUnicastSocket(const int32_t socketFD)
+void CAWiFiSetUnicastSocket(int socketFD)
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
- gUnicastServerSocketDescClient = socketFD;
+ g_unicastServerSocketDescClient = socketFD;
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT");
}
#ifdef __WITH_DTLS__
-void CAWiFiSetSecureUnicastSocket(const int32_t socketFD)
+void CAWiFiSetSecureUnicastSocket(int socketFD)
{
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
- gUnicastServerSecureSocketDescClient = socketFD;
+ g_unicastServerSecureSocketDescClient = socketFD;
OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT");
}
#endif
-uint32_t CAWiFiSendData(const char *remoteAddress, const uint32_t port,
- const void *data, const uint32_t dataLength,
- CABool_t isMulticast, CABool_t isSecured)
+uint32_t CAWiFiSendData(const char *remoteAddress, uint16_t port,
+ const void *data, uint32_t dataLength,
+ bool isMulticast, bool isSecured)
{
uint32_t len = 0;
#ifdef __WITH_DTLS__
- if (CA_TRUE == isSecured)
+ if (true == isSecured)
{
len = CASendData(remoteAddress, port,
- data, dataLength, gUnicastServerSecureSocketDescClient);
+ data, dataLength, g_unicastServerSecureSocketDescClient);
}
else
{
#endif
len = CASendData(remoteAddress, port,
- data, dataLength, gUnicastServerSocketDescClient);
+ data, dataLength, g_unicastServerSocketDescClient);
#ifdef __WITH_DTLS__
}
#endif
}
+
#include "caadapterutils.h"
#include "umutex.h"
#include "oic_malloc.h"
+#include "oic_string.h"
#define WIFI_MONITOR_TAG "WIFI_MONITOR"
/**
- * @var gWifiNetInfoMutex
+ * @var g_wifiNetInfoMutex
* @brief Mutex for synchronizing access to cached interface and IP address information.
*/
-static u_mutex gWifiNetInfoMutex = NULL;
+static u_mutex g_wifiNetInfoMutex = NULL;
/**
- * @var gWifiInterfaceName
+ * @var g_wifiInterfaceName
* @brief Maintains interface name.
*/
-static char *gWifiInterfaceName = NULL;
+static char *g_wifiInterfaceName = NULL;
/**
- * @var gWifiIPAddress
+ * @var g_wifiIPAddress
* @brief Maintains interface IP address.
*/
-static char *gWifiIPAddress = NULL;
+static char *g_wifiIPAddress = NULL;
/**
- * @var gWifiSubnetMask
+ * @var g_wifiSubnetMask
* @brief Maintains interface subnetmask.
*/
-static char *gWifiSubnetMask = NULL;
+static char *g_wifiSubnetMask = NULL;
/**
- * @var gNetworkChangeCb
+ * @var g_networkChangeCb
* @brief Maintains network connection state change callback.
*/
-static CAWiFiConnectionStateChangeCallback gNetworkChangeCb = NULL;
+static CAWiFiConnectionStateChangeCallback g_networkChangeCb = NULL;
/**
* @fn CAWIFIConnectionStateChangedCb
return CA_STATUS_FAILED;
}
- if (!gWifiNetInfoMutex)
+ if (!g_wifiNetInfoMutex)
{
- gWifiNetInfoMutex = u_mutex_new();
+ g_wifiNetInfoMutex = u_mutex_new();
}
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
OIC_LOG_V(INFO, WIFI_MONITOR_TAG, "wifi_deinitialize failed");
}
- if (gWifiInterfaceName)
+ if (g_wifiInterfaceName)
{
- OICFree(gWifiInterfaceName);
- gWifiInterfaceName = NULL;
+ OICFree(g_wifiInterfaceName);
+ g_wifiInterfaceName = NULL;
}
- if (gWifiIPAddress)
+ if (g_wifiIPAddress)
{
- OICFree(gWifiIPAddress);
- gWifiIPAddress = NULL;
+ OICFree(g_wifiIPAddress);
+ g_wifiIPAddress = NULL;
}
- if (gWifiSubnetMask)
+ if (g_wifiSubnetMask)
{
- OICFree(gWifiSubnetMask);
- gWifiSubnetMask = NULL;
+ OICFree(g_wifiSubnetMask);
+ g_wifiSubnetMask = NULL;
}
- if (gWifiNetInfoMutex)
+ if (g_wifiNetInfoMutex)
{
- u_mutex_free(gWifiNetInfoMutex);
- gWifiNetInfoMutex = NULL;
+ u_mutex_free(g_wifiNetInfoMutex);
+ g_wifiNetInfoMutex = NULL;
}
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_FAILED;
}
- CAWiFiGetInterfaceInformation(&gWifiInterfaceName, &gWifiIPAddress, &gWifiSubnetMask);
+ CAWiFiGetInterfaceInformation(&g_wifiInterfaceName, &g_wifiIPAddress, &g_wifiSubnetMask);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(interfaceName, WIFI_MONITOR_TAG, "interface name holder is NULL");
VERIFY_NON_NULL(ipAddress, WIFI_MONITOR_TAG, "IP address holder is NULL");
- u_mutex_lock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
- if (NULL == gWifiInterfaceName || NULL == gWifiIPAddress)
+ if (NULL == g_wifiInterfaceName || NULL == g_wifiIPAddress)
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "Network not enabled");
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
return CA_ADAPTER_NOT_ENABLED;
}
- if (gWifiInterfaceName && strlen(gWifiInterfaceName))
+ if (g_wifiInterfaceName && strlen(g_wifiInterfaceName))
{
- *interfaceName = strndup(gWifiInterfaceName, strlen(gWifiInterfaceName));
+ *interfaceName = OICStrdup((const char *)g_wifiInterfaceName);
}
- if (gWifiIPAddress && strlen(gWifiIPAddress))
+ if (g_wifiIPAddress && strlen(g_wifiIPAddress))
{
- *ipAddress = strndup(gWifiIPAddress, strlen(gWifiIPAddress));
+ *ipAddress = OICStrdup((const char *)g_wifiIPAddress);
}
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
VERIFY_NON_NULL(subnetMask, WIFI_MONITOR_TAG, "subnet mask");
- u_mutex_lock(gWifiNetInfoMutex);
- if (NULL == gWifiSubnetMask)
+ u_mutex_lock(g_wifiNetInfoMutex);
+ if (NULL == g_wifiSubnetMask)
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "There is no subnet mask information!");
+ u_mutex_unlock(g_wifiNetInfoMutex);
return CA_STATUS_FAILED;
}
- *subnetMask = (gWifiSubnetMask) ? strndup(gWifiSubnetMask, strlen(gWifiSubnetMask))
- : NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ *subnetMask = (g_wifiSubnetMask) ? OICStrdup((const char *)g_wifiSubnetMask): NULL;
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "IN");
- gNetworkChangeCb = callback;
+ g_networkChangeCb = callback;
}
void CAWIFIConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap,
CAWiFiGetInterfaceInformation(&interfaceName, &ipAddress, &subnetMask);
// Update the cached network information
- u_mutex_lock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
- OICFree(gWifiInterfaceName);
- OICFree(gWifiIPAddress);
- OICFree(gWifiSubnetMask);
- gWifiInterfaceName = interfaceName;
- gWifiIPAddress = ipAddress;
- gWifiSubnetMask = subnetMask;
+ OICFree(g_wifiInterfaceName);
+ OICFree(g_wifiIPAddress);
+ OICFree(g_wifiSubnetMask);
+ g_wifiInterfaceName = interfaceName;
+ g_wifiIPAddress = ipAddress;
+ g_wifiSubnetMask = subnetMask;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
}
else
{
nwStatus = CA_INTERFACE_DOWN;
}
- if (gNetworkChangeCb)
+ if (g_networkChangeCb)
{
- gNetworkChangeCb(gWifiIPAddress, nwStatus);
+ g_networkChangeCb(g_wifiIPAddress, nwStatus);
}
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
return;
}
- u_mutex_lock(gWifiNetInfoMutex);
+ u_mutex_lock(g_wifiNetInfoMutex);
// Get wifi interface name
if (WIFI_ERROR_NONE != (ret = wifi_get_network_interface_name(interfaceName)))
{
OIC_LOG_V(ERROR, WIFI_MONITOR_TAG, "Failed to get interface name! error num [%d]", ret);
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
return;
}
OICFree(*interfaceName);
*interfaceName = NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
return;
}
ret);
OICFree(*interfaceName);
*interfaceName = NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
return;
}
OICFree(*interfaceName);
*ipAddress = NULL;
*interfaceName = NULL;
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
return;
}
- u_mutex_unlock(gWifiNetInfoMutex);
+ u_mutex_unlock(g_wifiNetInfoMutex);
OIC_LOG_V(DEBUG, WIFI_MONITOR_TAG, "OUT");
}
+
#include "caadapternetdtls.h"
#endif
#include "umutex.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
/**
* @def WIFI_SERVER_TAG
#define IPNAMESIZE 16
/**
- * @var gUnicastServerSocketFD
+ * @var g_unicastServerSocketFD
* @brief Unicast server socket descriptor
*/
-static int32_t gUnicastServerSocketFD = -1;
+static int g_unicastServerSocketFD = -1;
/**
- * @var gMutexUnicastServer
+ * @var g_mutexUnicastServer
* @brief Mutex to synchronize unicast server
*/
-static u_mutex gMutexUnicastServer = NULL;
+static u_mutex g_mutexUnicastServer = NULL;
/**
- * @var gStopUnicast
+ * @var g_stopUnicast
* @brief Flag to control the Receive Unicast Data Thread
*/
-static bool gStopUnicast = false;
+static bool g_stopUnicast = false;
/**
- * @var gMulticastServerSocketFD
+ * @var g_multicastServerSocketFD
* @brief socket descriptor for multicast server
*/
-static int32_t gMulticastServerSocketFD = -1;
+static int g_multicastServerSocketFD = -1;
/**
- * @var gMutexMulticastServer
+ * @var g_mutexMulticastServer
* @brief Mutex to synchronize secure multicast server
*/
-static u_mutex gMutexMulticastServer = NULL;
+static u_mutex g_mutexMulticastServer = NULL;
/**
- * @var gStopMulticast
+ * @var g_stopMulticast
* @brief Flag to control the Receive Multicast Data Thread
*/
-static bool gStopMulticast = false;
+static bool g_stopMulticast = false;
#ifdef __WITH_DTLS__
/**
- * @var gSecureUnicastServerSocketFD
+ * @var g_secureUnicastServerSocketFD
* @brief Secure unicast server socket descriptor
*/
-static int32_t gSecureUnicastServerSocketFD = -1;
+static int g_secureUnicastServerSocketFD = -1;
/**
- * @var gMutexSecureUnicastServer
+ * @var g_mutexSecureUnicastServer
* @brief Mutex to synchronize secure unicast server
*/
-static u_mutex gMutexSecureUnicastServer = NULL;
+static u_mutex g_mutexSecureUnicastServer = NULL;
/**
- * @var gStopSecureUnicast
+ * @var g_stopSecureUnicast
* @brief Flag to control the unicast secure data receive thread
*/
-static bool gStopSecureUnicast = false;
+static bool g_stopSecureUnicast = false;
#endif
/**
- * @var gThreadPool
+ * @var g_threadPool
* @brief ThreadPool for storing u_thread_pool_t handle passed from adapter
*/
-static u_thread_pool_t gThreadPool = NULL;
+static u_thread_pool_t g_threadPool = NULL;
/**
- * @var gMulticastServerInterface
+ * @var g_multicastServerInterface
* @brief Local interface on which multicast server is running
*/
-static char gMulticastServerInterface[IPNAMESIZE];
+static char g_multicastServerInterface[IPNAMESIZE];
/**
- * @var gMulticastMemberReq
+ * @var g_multicastMemberReq
* @brief ip_mreq structure passed to join a multicast group
*/
-static struct ip_mreq gMulticastMemberReq;
+static struct ip_mreq g_multicastMemberReq;
/**
- * @var gPacketReceivedCallback
+ * @var g_packetReceivedCallback
* @brief Callback for notifying the upper layer on receival data from remote OIC device
*/
-static CAWiFiPacketReceivedCallback gPacketReceivedCallback = NULL;
+static CAWiFiPacketReceivedCallback g_packetReceivedCallback = NULL;
/**
- * @var gExceptionCallback
+ * @var g_exceptionCallback
* @brief Callback for notifying the upper layer when unicast/multicast server encounters exception
*/
-static CAWiFiExceptionCallback gExceptionCallback = NULL;
+static CAWiFiExceptionCallback g_exceptionCallback = NULL;
/**
@brief Thread context information for unicast, multicast and secured unicast server
typedef struct
{
bool *stopFlag;
- int32_t socket_fd;
+ int socket_fd;
CAAdapterServerType_t type;
} CAAdapterReceiveThreadContext_t;
VERIFY_NON_NULL_VOID(data, WIFI_SERVER_TAG, "Invalid thread context");
CAAdapterReceiveThreadContext_t *ctx = (CAAdapterReceiveThreadContext_t *)data;
- fd_set reads;
- struct timeval timeout;
+
+
char recvBuffer[COAP_MAX_PDU_SIZE] = {0};
while (true != *(ctx->stopFlag))
{
+ struct timeval timeout;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
+ fd_set reads;
FD_ZERO(&reads);
FD_SET(ctx->socket_fd, &reads);
- int32_t ret = select(ctx->socket_fd + 1, &reads, NULL, NULL, &timeout);
+ int ret = select(ctx->socket_fd + 1, &reads, NULL, NULL, &timeout);
if (*(ctx->stopFlag) == true)
{
OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "Stop request received for [%d] server", ctx->type);
continue;
}
- memset(recvBuffer, 0, sizeof(recvBuffer));
-
// Read data from socket
- struct sockaddr_in srcSockAddress;
- int32_t recvLen;
+ struct sockaddr_in srcSockAddress = {0};
+ int recvLen = 0;
socklen_t srcAddressLen = sizeof(srcSockAddress);
if (-1 == (recvLen = recvfrom(ctx->socket_fd, recvBuffer,
sizeof(recvBuffer), 0, (struct sockaddr *) &srcSockAddress,
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Server socket shutdown [%d]!", ctx->type);
// Notify upper layer this exception
- if (gExceptionCallback)
+ if (g_exceptionCallback)
{
- gExceptionCallback(ctx->type);
+ g_exceptionCallback(ctx->type);
}
OICFree(ctx);
return;
}
const char *srcIPAddress = NULL;
- int32_t srcPort = -1;
+ uint16_t srcPort = 0;
srcIPAddress = inet_ntoa(srcSockAddress.sin_addr);
srcPort = ntohs(srcSockAddress.sin_port);
continue;
}
- if (!CAAdapterIsSameSubnet(gMulticastServerInterface, srcIPAddress, netMask))
+ if (!CAAdapterIsSameSubnet(g_multicastServerInterface, srcIPAddress, netMask))
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "Packet received from different subnet, Ignore!");
if (NULL != netMask)
{
OICFree(netMask);
}
- netMask = NULL;
continue;
}
case CA_UNICAST_SERVER:
case CA_MULTICAST_SERVER:
// Notify data to upper layer
- if (gPacketReceivedCallback)
+ if (g_packetReceivedCallback)
{
- gPacketReceivedCallback(srcIPAddress, srcPort, recvBuffer, recvLen, false);
+ g_packetReceivedCallback(srcIPAddress, srcPort, recvBuffer, recvLen, false);
}
break;
#ifdef __WITH_DTLS__
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
-static CAResult_t CAWiFiCreateSocket(int32_t *socketFD, const char *localIp, int16_t *port,
- const bool forceStart)
+static CAResult_t CAWiFiCreateSocket(int *socketFD, const char *localIp, uint16_t *port,
+ bool forceStart)
{
- int32_t sock = -1;
+ VERIFY_NON_NULL(socketFD, WIFI_SERVER_TAG, "socketFD is NULL");
+ VERIFY_NON_NULL(port, WIFI_SERVER_TAG, "port is NULL");
+ VERIFY_NON_NULL(localIp, WIFI_SERVER_TAG, "localIp is NULL");
+
+ int sock = -1;
// Create a UDP socket
if (-1 == (sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)))
{
if (true == forceStart)
{
- int32_t setOptionOn = 1;
+ int setOptionOn = 1;
if (-1 == setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
(char *) &setOptionOn,
sizeof(setOptionOn)))
}
}
- struct sockaddr_in sockAddr;
+ struct sockaddr_in sockAddr = {0};
bool isBound = false;
- int16_t serverPort = *port;
+ uint16_t serverPort = *port;
- memset((char *) &sockAddr, 0, sizeof(sockAddr));
sockAddr.sin_family = AF_INET;
sockAddr.sin_port = htons(serverPort);
if (localIp)
sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
}
- int16_t i;
+ int16_t i = 0;
for (i = 0; i < CA_UDP_BIND_RETRY_COUNT; i++)
{
if (-1 == bind(sock, (struct sockaddr *) &sockAddr,
return CA_STATUS_OK;
}
-static CAResult_t CAWiFiCloseSocket(int32_t *socketFD)
+static CAResult_t CAWiFiCloseSocket(int *socketFD)
{
+ VERIFY_NON_NULL(socketFD, WIFI_SERVER_TAG, "socketFD is NULL");
+
if (-1 == *socketFD)
{
OIC_LOG(INFO, WIFI_SERVER_TAG, "Server not running");
return CA_STATUS_OK;
}
-static CAResult_t CAStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, bool isSecured, int32_t *serverFD)
+static CAResult_t CAStartUnicastServer(const char *localAddress, uint16_t *port,
+ bool forceStart, bool isSecured, int *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
+ VERIFY_NON_NULL(localAddress, WIFI_SERVER_TAG, "localAddress is NULL");
+ VERIFY_NON_NULL(serverFD, WIFI_SERVER_TAG, "socketFD is NULL");
+ VERIFY_NON_NULL(port, WIFI_SERVER_TAG, "port is NULL");
+
CAResult_t ret = CAWiFiCreateSocket(serverFD, localAddress, port, forceStart);
if (CA_STATUS_OK != ret)
{
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopUnicast;
+ ctx->stopFlag = &g_stopUnicast;
ctx->socket_fd = *serverFD;
ctx->type = isSecured ? CA_SECURED_UNICAST_SERVER : CA_UNICAST_SERVER;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CAReceiveHandler, (void *)ctx))
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CAReceiveHandler, (void *)ctx))
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to create read thread!");
- OICFree((void *)ctx);
+ OICFree(ctx);
close(*serverFD);
return CA_STATUS_FAILED;
}
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- if (gMutexUnicastServer)
+ if (g_mutexUnicastServer)
{
- u_mutex_free(gMutexUnicastServer);
- gMutexUnicastServer = NULL;
+ u_mutex_free(g_mutexUnicastServer);
+ g_mutexUnicastServer = NULL;
}
#ifdef __WITH_DTLS__
- if (gMutexSecureUnicastServer)
+ if (g_mutexSecureUnicastServer)
{
- u_mutex_free(gMutexSecureUnicastServer);
- gMutexSecureUnicastServer = NULL;
+ u_mutex_free(g_mutexSecureUnicastServer);
+ g_mutexSecureUnicastServer = NULL;
}
#endif
- if (gMutexMulticastServer)
+ if (g_mutexMulticastServer)
{
- u_mutex_free(gMutexMulticastServer);
- gMutexMulticastServer = NULL;
+ u_mutex_free(g_mutexMulticastServer);
+ g_mutexMulticastServer = NULL;
}
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gMutexUnicastServer = u_mutex_new();
- if (!gMutexUnicastServer)
+ if(!g_mutexUnicastServer)
{
- OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
- return CA_STATUS_FAILED;
+ g_mutexUnicastServer = u_mutex_new();
+ if (!g_mutexUnicastServer)
+ {
+ OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
+ return CA_STATUS_FAILED;
+ }
}
#ifdef __WITH_DTLS__
- gMutexSecureUnicastServer = u_mutex_new();
- if (!gMutexSecureUnicastServer)
+ if(!g_mutexSecureUnicastServer)
{
- OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
+ g_mutexSecureUnicastServer = u_mutex_new();
+ if (!g_mutexSecureUnicastServer)
+ {
+ OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
- CAWiFiServerDestroyMutex();
- return CA_STATUS_FAILED;
+ CAWiFiServerDestroyMutex();
+ return CA_STATUS_FAILED;
+ }
}
#endif
- gMutexMulticastServer = u_mutex_new();
- if (!gMutexMulticastServer)
+ if(!g_mutexMulticastServer)
{
- OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
+ g_mutexMulticastServer = u_mutex_new();
+ if (!g_mutexMulticastServer)
+ {
+ OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to created mutex!");
- CAWiFiServerDestroyMutex();
- return CA_STATUS_FAILED;
+ CAWiFiServerDestroyMutex();
+ return CA_STATUS_FAILED;
+ }
}
-
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
}
return CA_STATUS_FAILED;
}
- gThreadPool = threadPool;
+ g_threadPool = threadPool;
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gThreadPool = NULL;
+ g_threadPool = NULL;
// Destroy mutex
CAWiFiServerDestroyMutex();
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
-CAResult_t CAWiFiStartUnicastServer(const char *localAddress, int16_t *port,
- const bool forceStart, const CABool_t isSecured,
- int32_t *serverFD)
+CAResult_t CAWiFiStartUnicastServer(const char *localAddress, uint16_t *port,
+ bool forceStart, bool isSecured,
+ int *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
}
*serverFD = -1;
- if (CA_FALSE == isSecured)
+ if (false == isSecured)
{
- u_mutex_lock(gMutexUnicastServer);
- if (-1 != gUnicastServerSocketFD)
+ u_mutex_lock(g_mutexUnicastServer);
+ if (-1 != g_unicastServerSocketFD)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Unicast Server is Started Already!",
CA_SERVER_STARTED_ALREADY);
- *serverFD = gUnicastServerSocketFD;
- u_mutex_unlock(gMutexUnicastServer);
+ *serverFD = g_unicastServerSocketFD;
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_SERVER_STARTED_ALREADY;
}
- gStopUnicast = false;
+ g_stopUnicast = false;
if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
- &gUnicastServerSocketFD))
+ &g_unicastServerSocketFD))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to start unicast server!");
- gUnicastServerSocketFD = -1;
- u_mutex_unlock(gMutexUnicastServer);
+ g_unicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexUnicastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gUnicastServerSocketFD;
- u_mutex_unlock(gMutexUnicastServer);
+ *serverFD = g_unicastServerSocketFD;
+ u_mutex_unlock(g_mutexUnicastServer);
}
#ifdef __WITH_DTLS__
else // Start unicast server for secured communication
{
- u_mutex_lock(gMutexSecureUnicastServer);
- if (-1 != gSecureUnicastServerSocketFD)
+ u_mutex_lock(g_mutexSecureUnicastServer);
+ if (-1 != g_secureUnicastServerSocketFD)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Unicast Server is Started Already!",
CA_SERVER_STARTED_ALREADY);
- *serverFD = gSecureUnicastServerSocketFD;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ *serverFD = g_secureUnicastServerSocketFD;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
return CA_SERVER_STARTED_ALREADY;
}
- gStopSecureUnicast = false;
+ g_stopSecureUnicast = false;
if (CA_STATUS_OK != CAStartUnicastServer(localAddress, port, forceStart, isSecured,
- &gSecureUnicastServerSocketFD))
+ &g_secureUnicastServerSocketFD))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to start unicast server!");
- gSecureUnicastServerSocketFD = -1;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ g_secureUnicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gSecureUnicastServerSocketFD;
- u_mutex_unlock(gMutexSecureUnicastServer);
+ *serverFD = g_secureUnicastServerSocketFD;
+ u_mutex_unlock(g_mutexSecureUnicastServer);
}
#endif
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
CAResult_t CAWiFiStartMulticastServer(const char *localAddress, const char *multicastAddress,
- const int16_t multicastPort, int32_t *serverFD)
+ uint16_t multicastPort, int *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
VERIFY_NON_NULL(multicastAddress, WIFI_SERVER_TAG, "port");
VERIFY_NON_NULL(serverFD, WIFI_SERVER_TAG, "server socket FD");
- int16_t port = multicastPort;
+ uint16_t port = multicastPort;
if (0 >= port)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Invalid input: Multicast port is invalid!");
return CA_STATUS_INVALID_PARAM;
}
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
- if (gMulticastServerSocketFD != -1)
+ if (g_multicastServerSocketFD != -1)
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Multicast Server is already running!");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_SERVER_STARTED_ALREADY;
}
- CAResult_t ret = CAWiFiCreateSocket(&gMulticastServerSocketFD, multicastAddress, &port, true);
+ CAResult_t ret = CAWiFiCreateSocket(&g_multicastServerSocketFD, multicastAddress, &port, true);
if (ret != CA_STATUS_OK)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Failed to create multicast socket");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return ret;
}
// Add membership to receiving socket (join group)
- memset(&gMulticastMemberReq, 0, sizeof(struct ip_mreq));
- gMulticastMemberReq.imr_interface.s_addr = inet_addr(localAddress);
- inet_aton(multicastAddress, &gMulticastMemberReq.imr_multiaddr);
+ memset(&g_multicastMemberReq, 0, sizeof(struct ip_mreq));
+ g_multicastMemberReq.imr_interface.s_addr = inet_addr(localAddress);
+ inet_aton(multicastAddress, &g_multicastMemberReq.imr_multiaddr);
- if (-1 == setsockopt(gMulticastServerSocketFD, IPPROTO_IP, IP_ADD_MEMBERSHIP,
- (char *) &gMulticastMemberReq,
+ if (-1 == setsockopt(g_multicastServerSocketFD, IPPROTO_IP, IP_ADD_MEMBERSHIP,
+ (char *) &g_multicastMemberReq,
sizeof(struct ip_mreq)))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to add to multicast group, Error code: %s\n",
strerror(errno));
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
- u_mutex_unlock(gMutexMulticastServer);
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_STATUS_FAILED;
}
if (!ctx)
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "Out of memory!");
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
return CA_MEMORY_ALLOC_FAILED;
}
- ctx->stopFlag = &gStopMulticast;
- ctx->socket_fd = gMulticastServerSocketFD;
+ ctx->stopFlag = &g_stopMulticast;
+ ctx->socket_fd = g_multicastServerSocketFD;
ctx->type = CA_MULTICAST_SERVER;
- gStopMulticast = false;
- if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPool, CAReceiveHandler, (void *)ctx))
+ g_stopMulticast = false;
+ if (CA_STATUS_OK != u_thread_pool_add_task(g_threadPool, CAReceiveHandler, (void *)ctx))
{
OIC_LOG(ERROR, WIFI_SERVER_TAG, "thread_pool_add_task failed!");
- close(gMulticastServerSocketFD);
- gMulticastServerSocketFD = -1;
- gStopMulticast = true;
- u_mutex_unlock(gMutexMulticastServer);
+ close(g_multicastServerSocketFD);
+ g_multicastServerSocketFD = -1;
+ g_stopMulticast = true;
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_STATUS_FAILED;
}
- *serverFD = gMulticastServerSocketFD;
- strncpy(gMulticastServerInterface, localAddress, sizeof(gMulticastServerInterface));
- u_mutex_unlock(gMutexMulticastServer);
+ *serverFD = g_multicastServerSocketFD;
+ strncpy(g_multicastServerInterface, localAddress, sizeof(g_multicastServerInterface));
+ u_mutex_unlock(g_mutexMulticastServer);
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexUnicastServer);
- gStopUnicast = true;
- CAResult_t ret = CAWiFiCloseSocket(&gUnicastServerSocketFD);
- u_mutex_unlock(gMutexUnicastServer);
+ u_mutex_lock(g_mutexUnicastServer);
+ g_stopUnicast = true;
+ CAResult_t ret = CAWiFiCloseSocket(&g_unicastServerSocketFD);
+ u_mutex_unlock(g_mutexUnicastServer);
OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Unicast server stopped [%d]", ret);
return ret;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexSecureUnicastServer);
- gStopSecureUnicast = true;
- CAResult_t ret = CAWiFiCloseSocket(&gSecureUnicastServerSocketFD);
- u_mutex_unlock(gMutexSecureUnicastServer);
+ u_mutex_lock(g_mutexSecureUnicastServer);
+ g_stopSecureUnicast = true;
+ CAResult_t ret = CAWiFiCloseSocket(&g_secureUnicastServerSocketFD);
+ u_mutex_unlock(g_mutexSecureUnicastServer);
- OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Secured unicast server stopped [%d]", ret);
+ OIC_LOG_V(INFO, WIFI_SERVER_TAG, "OUT Secured unicast server stopped [%d]", ret);
return ret;
}
#endif
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- u_mutex_lock(gMutexMulticastServer);
+ u_mutex_lock(g_mutexMulticastServer);
- if (gMulticastServerSocketFD == -1)
+ if (g_multicastServerSocketFD == -1)
{
OIC_LOG(INFO, WIFI_SERVER_TAG, "Multicast server is not yet started");
- u_mutex_unlock(gMutexMulticastServer);
+ u_mutex_unlock(g_mutexMulticastServer);
return CA_SERVER_NOT_STARTED;
}
- gStopMulticast = true;
+ g_stopMulticast = true;
// leave the group after you are done
- if (-1 == setsockopt(gMulticastServerSocketFD, IPPROTO_IP, IP_DROP_MEMBERSHIP,
- (char *)&gMulticastMemberReq,
+ if (-1 == setsockopt(g_multicastServerSocketFD, IPPROTO_IP, IP_DROP_MEMBERSHIP,
+ (char *)&g_multicastMemberReq,
sizeof(struct ip_mreq)))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed to leave multicast group, Error code: %s\n",
strerror(errno));
}
- CAResult_t ret = CAWiFiCloseSocket(&gMulticastServerSocketFD);
- u_mutex_unlock(gMutexMulticastServer);
+ CAResult_t ret = CAWiFiCloseSocket(&g_multicastServerSocketFD);
+ u_mutex_unlock(g_mutexMulticastServer);
- OIC_LOG_V(INFO, WIFI_SERVER_TAG, "Multicast server stopped [%d]", ret);
+ OIC_LOG_V(INFO, WIFI_SERVER_TAG, " OUT Multicast server stopped [%d]", ret);
return ret;
}
-CAResult_t CAWiFiGetUnicastServerInfo(const CABool_t isSecured, char **ipAddress,
- int16_t *port, int32_t *serverFD)
+CAResult_t CAWiFiGetUnicastServerInfo(bool isSecured, char **ipAddress,
+ uint16_t *port, int *serverFD)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
VERIFY_NON_NULL(port, WIFI_SERVER_TAG, "Port");
VERIFY_NON_NULL(serverFD, WIFI_SERVER_TAG, "Server ID");
- struct sockaddr_in sockAddr;
+ struct sockaddr_in sockAddr = {0};
socklen_t len = sizeof(struct sockaddr_in);
- if (-1 == getsockname(gUnicastServerSocketFD, (struct sockaddr *)&sockAddr, &len))
+ if (-1 == getsockname(g_unicastServerSocketFD, (struct sockaddr *)&sockAddr, &len))
{
OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Failed in getsockname [%s]!", strerror(errno));
return CA_STATUS_FAILED;
}
-
const char *serverAddress = inet_ntoa(sockAddr.sin_addr);
- *ipAddress = (serverAddress) ? strndup(serverAddress, strlen(serverAddress)) : NULL;
+ *ipAddress = (serverAddress) ? OICStrdup(serverAddress) : NULL;
*port = ntohs(sockAddr.sin_port);
#ifdef __WITH_DTLS__
- *serverFD = (CA_TRUE == isSecured) ? gSecureUnicastServerSocketFD : gUnicastServerSocketFD;
+ *serverFD = (true == isSecured) ? g_secureUnicastServerSocketFD : g_unicastServerSocketFD;
#else
- *serverFD = gUnicastServerSocketFD;
+ *serverFD = g_unicastServerSocketFD;
#endif
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
return CA_STATUS_OK;
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gPacketReceivedCallback = callback;
+ g_packetReceivedCallback = callback;
+
+ OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
void CAWiFiSetExceptionCallback(CAWiFiExceptionCallback callback)
{
OIC_LOG(DEBUG, WIFI_SERVER_TAG, "IN");
- gExceptionCallback = callback;
+ g_exceptionCallback = callback;
+
+ OIC_LOG(DEBUG, WIFI_SERVER_TAG, "OUT");
}
+
--- /dev/null
+#include "gtest/gtest.h"
+#include "cainterface.h"
+#include "cacommon.h"
+#include <string.h>
+
+void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo);
+void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
+
+static CAToken_t g_lastRequestToken = NULL;
+
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+{
+
+}
+
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+{
+
+}
+
+static char* uri = NULL;
+static CARemoteEndpoint_t* tempRep = NULL;
+static CARequestInfo_t requestInfo;
+static CAInfo_t requestData;
+static CAInfo_t responseData;
+static CAResponseInfo_t responseInfo;
+static CAToken_t tempToken = NULL;
+static const char URI[] = "coap://10.11.12.13:4545/a/light";
+static const char RESOURCE_URI[] = "/a/light";
+
+static const char SECURE_INFO_DATA[] =
+ "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+ "\"if\":[\"oc.mi.def\"],\"obs\":1,\"sec\":1,\"port\":%d}}]}";
+static const char NORMAL_INFO_DATA[] =
+ "{\"oc\":[{\"href\":\"%s\",\"prop\":{\"rt\":[\"core.led\"],"
+ "\"if\":[\"oc.mi.def\"],\"obs\":1}}]}";
+
+#ifdef __WITH_DTLS__
+static OCDtlsPskCredsBlob *pskCredsBlob = NULL;
+
+void clearDtlsCredentialInfo()
+{
+ printf("clearDtlsCredentialInfo IN\n");
+ if (pskCredsBlob)
+ {
+ // Initialize sensitive data to zeroes before freeing.
+ memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+ free(pskCredsBlob->creds);
+
+ memset(pskCredsBlob, 0, sizeof(OCDtlsPskCredsBlob));
+ free(pskCredsBlob);
+ pskCredsBlob = NULL;
+ }
+ printf("clearDtlsCredentialInfo OUT\n");
+}
+
+// Internal API. Invoked by OC stack to retrieve credentials from this module
+void CAGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo)
+{
+ printf("CAGetDtlsPskCredentials IN\n");
+
+ if (pskCredsBlob != NULL)
+ {
+ *credInfo = pskCredsBlob;
+ }
+
+ printf("CAGetDtlsPskCredentials OUT\n");
+}
+
+int32_t SetCredentials()
+{
+ printf("SetCredentials IN\n");
+ pskCredsBlob = (OCDtlsPskCredsBlob *)malloc(sizeof(OCDtlsPskCredsBlob));
+
+ memset(pskCredsBlob, 0x0, sizeof(OCDtlsPskCredsBlob));
+ memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+
+ pskCredsBlob->num = 1;
+
+ pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+
+ memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
+ memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
+
+ printf("SetCredentials OUT\n");
+ return 1;
+}
+#endif
+
+int main(int argc, char **argv)
+{
+ testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
+
+// CAInitialize TC
+// check return value
+TEST(InitializeTest, TC_01_Positive_01)
+{
+ EXPECT_EQ(CA_STATUS_OK, CAInitialize());
+}
+
+//CATerminate TC
+TEST(TerminateTest, TC_02_Positive_01)
+{
+ CATerminate();
+
+ char* check = (char *) "terminate success";
+ EXPECT_STREQ(check, "terminate success");
+
+ CAInitialize();
+}
+// CAStartListeningServer TC
+// check return value
+TEST(StartListeningServerTest, TC_03_Positive_01)
+{
+ CASelectNetwork(CA_WIFI);
+ EXPECT_EQ(CA_STATUS_OK, CAStartListeningServer());
+}
+
+// CAStartDiscoveryServer TC
+// check return value
+TEST(StartDiscoveryServerTest, TC_04_Positive_01)
+{
+ EXPECT_EQ(CA_STATUS_OK, CAStartDiscoveryServer());
+}
+
+// CARegisterHandlerTest TC
+// check return value
+TEST(RegisterHandlerTest, TC_05_Positive_01)
+{
+ CARegisterHandler(request_handler, response_handler);
+ char* check = (char *) "registerHandler success";
+ EXPECT_STREQ(check, "registerHandler success");
+}
+
+// CACreateRemoteEndpoint TC
+// check return value
+TEST(CreateRemoteEndpointTest, TC_06_Positive_01)
+{
+ uri = (char *) URI;
+
+ EXPECT_EQ(CA_STATUS_OK, CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep));
+
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+}
+
+// check remoteEndpoint and values of remoteEndpoint
+TEST(CreateRemoteEndpointTest, TC_07_Positive_02)
+{
+ uri = (char *) URI;
+
+ CACreateRemoteEndpoint(uri, CA_WIFI, &tempRep);
+
+ EXPECT_TRUE(tempRep != NULL);
+
+ if (tempRep != NULL)
+ {
+ EXPECT_STRNE(NULL, tempRep->resourceUri);
+ }
+
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+}
+
+// check return value when uri is NULL
+TEST(CreateRemoteEndpointTest, TC_08_Negative_01)
+{
+ uri = NULL;
+
+ EXPECT_EQ(CA_STATUS_FAILED, CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep));
+
+ if (tempRep != NULL)
+ {
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+ }
+}
+
+// check values of remoteEndpoint when uri is NULL
+TEST(CreateRemoteEndpointTest, TC_09_Negative_02)
+{
+ uri = NULL;
+ CACreateRemoteEndpoint(uri, CA_WIFI, &tempRep);
+
+ if (tempRep != NULL)
+ {
+ EXPECT_STREQ(NULL, tempRep->resourceUri);
+
+ }
+
+ if (tempRep != NULL)
+ {
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+ }
+}
+
+// CADestroyRemoteEndpoint TC
+// check destroyed remoteEndpoint
+TEST(DestroyRemoteEndpointTest, TC_10_Positive_01)
+{
+ uri = (char *) URI;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+
+ char * check = (char *) "destroy success";
+ EXPECT_STREQ(check, "destroy success");
+}
+
+// CAGerateToken TC
+// check return value
+TEST(GenerateTokenTest, TC_11_Positive_01)
+{
+ EXPECT_EQ(CA_STATUS_OK, CAGenerateToken(&tempToken));
+
+ CADestroyToken(tempToken);
+}
+
+// check return value when CAGenerateToken is passed a NULL instead a valid pointer
+TEST(GenerateTokenTest, TC_12_Negative_01)
+{
+ EXPECT_EQ(CA_STATUS_FAILED, CAGenerateToken(NULL));
+}
+
+// CADestroyToken TC
+// check destroyed token
+TEST(DestroyTokenTest, TC_13_Positive_01)
+{
+ CAGenerateToken(&tempToken);
+ CADestroyToken(tempToken);
+
+ char * check = (char *) "destroy success";
+ EXPECT_STREQ(check, "destroy success");
+}
+
+// CAFindResource TC
+// check return value
+TEST(FindResourceTest, TC_14_Positive_01)
+{
+ uri = (char *) RESOURCE_URI;
+
+ CAGenerateToken(&tempToken);
+ EXPECT_EQ(CA_STATUS_OK, CAFindResource(uri, tempToken));
+}
+
+// check return value when uri is NULL
+TEST(FindResourceTest, TC_15_Negative_01)
+{
+ uri = NULL;
+ CAGenerateToken(&tempToken);
+ EXPECT_EQ(CA_STATUS_FAILED, CAFindResource(uri, tempToken));
+}
+
+// CASendRequest TC
+// check return value
+TEST(SendRequestTest, TC_16_Positive_01)
+{
+ uri = (char *) URI;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ memset(&requestData, 0, sizeof(CAInfo_t));
+ CAGenerateToken(&tempToken);
+ requestData.token = tempToken;
+
+ int length = strlen(NORMAL_INFO_DATA) + strlen("a/light");
+ requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ snprintf(requestData.payload, length, NORMAL_INFO_DATA, "a/light");
+ requestData.type = CA_MSG_NONCONFIRM;
+
+ memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
+
+ EXPECT_EQ(CA_STATUS_OK, CASendRequest(tempRep, &requestInfo));
+
+ CADestroyToken(tempToken);
+
+ free(requestData.payload);
+
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+
+}
+
+// check return value when uri is NULL
+TEST(SendRequestTest, TC_17_Negative_01)
+{
+ uri = NULL;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ memset(&requestData, 0, sizeof(CAInfo_t));
+ CAGenerateToken(&tempToken);
+ requestData.token = tempToken;
+
+ int length = strlen(NORMAL_INFO_DATA) + strlen("a/light");
+ requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ snprintf(requestData.payload, length, NORMAL_INFO_DATA, "a/light");
+ requestData.type = CA_MSG_NONCONFIRM;
+
+ memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
+
+ EXPECT_EQ(CA_STATUS_FAILED, CASendRequest(tempRep, &requestInfo));
+
+ CADestroyToken(tempToken);
+
+ free(requestData.payload);
+
+ if (tempRep != NULL)
+ {
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+ }
+}
+
+// check return value when a NULL is passed instead of a valid CARequestInfo_t address
+TEST(SendRequestTest, TC_18_Negative_02)
+{
+ uri = (char *) URI;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ memset(&requestData, 0, sizeof(CAInfo_t));
+ CAGenerateToken(&tempToken);
+ requestData.token = tempToken;
+
+ int length = strlen(NORMAL_INFO_DATA) + strlen("a/light");
+ requestData.payload = (CAPayload_t) calloc(length, sizeof(char));
+ snprintf(requestData.payload, length, NORMAL_INFO_DATA, "a/light");
+ requestData.type = CA_MSG_NONCONFIRM;
+
+ memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
+
+ EXPECT_EQ(CA_STATUS_FAILED, CASendRequest(tempRep, NULL));
+
+ CADestroyToken(tempToken);
+
+ free(requestData.payload);
+
+ if (tempRep != NULL)
+ {
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+ }
+}
+
+// CASendResponse TC
+// check return value
+TEST(SendResponseTest, TC_19_Positive_01)
+{
+ uri = (char *) URI;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ memset(&responseData, 0, sizeof(CAInfo_t));
+ CAGenerateToken(&tempToken);
+ responseData.type = CA_MSG_NONCONFIRM;
+ responseData.messageId = 1;
+ responseData.payload = (char *) "response payload";
+
+ memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ responseInfo.result = CA_SUCCESS;
+ responseInfo.info = responseData;
+
+ EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo));
+
+ CADestroyToken(tempToken);
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+}
+
+// check return value when uri is NULL
+TEST(SendResponseTest, TC_20_Negative_01)
+{
+ uri = NULL;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ memset(&responseData, 0, sizeof(CAInfo_t));
+ CAGenerateToken(&tempToken);
+ responseData.type = CA_MSG_NONCONFIRM;
+ responseData.messageId = 1;
+ responseData.payload = (char *) "response payload";
+
+ memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ responseInfo.result = CA_SUCCESS;
+ responseInfo.info = responseData;
+
+ EXPECT_EQ(CA_STATUS_FAILED, CASendResponse(tempRep, &responseInfo));
+
+ CADestroyToken(tempToken);
+ if (tempRep != NULL)
+ {
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+ }
+}
+
+// check return value NULL is passed instead of a valid CAResponseInfo_t address
+TEST(SendResponseTest, TC_21_Negative_02)
+{
+ uri = (char *) URI;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ memset(&responseData, 0, sizeof(CAInfo_t));
+ CAGenerateToken(&tempToken);
+ responseData.type = CA_MSG_NONCONFIRM;
+ responseData.messageId = 1;
+ responseData.payload = (char *) "response payload";
+
+ memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ responseInfo.result = CA_SUCCESS;
+ responseInfo.info = responseData;
+
+ EXPECT_EQ(CA_STATUS_FAILED, CASendResponse(tempRep, NULL));
+
+ CADestroyToken(tempToken);
+ if (tempRep != NULL)
+ {
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+ }
+}
+
+// CASendNotification TC
+// check return value
+TEST(SendNotificationTest, TC_22_Positive_01)
+{
+ uri = (char *) URI;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ memset(&responseData, 0, sizeof(CAInfo_t));
+ responseData.token = (char *) "client token";
+ responseData.payload = (char *) "Temp Notification Data";
+
+ memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ responseInfo.result = CA_SUCCESS;
+ responseInfo.info = responseData;
+
+ EXPECT_EQ(CA_STATUS_OK, CASendNotification(tempRep, &responseInfo));
+
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+}
+
+// check return value when uri is NULL
+TEST(SendNotificationTest, TC_23_Negative_01)
+{
+ uri = NULL;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+
+ memset(&responseData, 0, sizeof(CAInfo_t));
+ responseData.token = (char *) "client token";
+ responseData.payload = (char *) "Temp Notification Data";
+
+ memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+ responseInfo.result = CA_SUCCESS;
+ responseInfo.info = responseData;
+
+ EXPECT_EQ(CA_STATUS_FAILED, CASendNotification(tempRep, &responseInfo));
+
+ if (tempRep != NULL)
+ {
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+ }
+}
+
+// CAAdvertiseResource TC
+// check return value
+TEST(AdvertiseResourceTest, TC_24_Positive_01)
+{
+ uri = (char *) RESOURCE_URI;
+ int optionNum = 2;
+
+ CAHeaderOption_t* headerOpt;
+ headerOpt = (CAHeaderOption_t *) calloc(1, optionNum * sizeof(CAHeaderOption_t));
+
+ char* tmpOptionData1 = (char *) "Hello";
+ headerOpt[0].optionID = 3000;
+ memcpy(headerOpt[0].optionData, tmpOptionData1, strlen(tmpOptionData1));
+ headerOpt[0].optionLength = (uint16_t) strlen(tmpOptionData1);
+
+ char* tmpOptionData2 = (char *) "World";
+ headerOpt[1].optionID = 3001;
+ memcpy(headerOpt[1].optionData, tmpOptionData2, strlen(tmpOptionData2));
+ headerOpt[1].optionLength = (uint16_t) strlen(tmpOptionData2);
+
+ CAGenerateToken(&tempToken);
+
+ EXPECT_EQ(CA_STATUS_OK, CAAdvertiseResource(uri, tempToken, headerOpt, (uint8_t )optionNum));
+
+ free(headerOpt);
+}
+
+// check return value when uri is NULL
+TEST(AdvertiseResourceTest, TC_25_Negative_01)
+{
+ uri = NULL;
+ int optionNum = 2;
+
+ CAHeaderOption_t* headerOpt;
+ headerOpt = (CAHeaderOption_t *) calloc(1, optionNum * sizeof(CAHeaderOption_t));
+
+ char* tmpOptionData1 = (char *) "Hello";
+ headerOpt[0].optionID = 3000;
+ memcpy(headerOpt[0].optionData, tmpOptionData1, strlen(tmpOptionData1));
+ headerOpt[0].optionLength = (uint16_t) strlen(tmpOptionData1);
+
+ char* tmpOptionData2 = (char *) "World";
+ headerOpt[1].optionID = 3001;
+ memcpy(headerOpt[1].optionData, tmpOptionData2, strlen(tmpOptionData2));
+ headerOpt[1].optionLength = (uint16_t) strlen(tmpOptionData2);
+
+ CAGenerateToken(&tempToken);
+
+ EXPECT_EQ(CA_STATUS_FAILED,
+ CAAdvertiseResource(uri, tempToken, headerOpt, (uint8_t )optionNum));
+
+ free(headerOpt);
+}
+
+// CASelectNewwork TC
+// check return value
+ TEST(SelectNetworkTest, TC_26_Positive_01)
+{
+ //Select wifi network
+ EXPECT_EQ(CA_STATUS_OK, CASelectNetwork(CA_WIFI));
+}
+
+// check return value when selected network is disable
+TEST(SelectNetworkTest, TC_27_Negative_01)
+{
+ //Select disable network
+ EXPECT_EQ(CA_NOT_SUPPORTED, CASelectNetwork(1000));
+}
+
+// CAUnSelectNewwork TC
+// check return value
+TEST(UnSelectNetworkTest, TC_28_Positive_01)
+{
+ //Unselect wifi network
+ EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_WIFI));
+}
+
+// check return value when selected network is disable
+TEST(UnSelectNetworkTest, TC_29_Negative_01)
+{
+ //UnSelect disable network
+ EXPECT_EQ(CA_STATUS_FAILED, CAUnSelectNetwork(1000));
+}
+
+// CAHandlerRequestResponse TC
+// check return value
+TEST (HandlerRequestResponseTest, TC_30_Positive_01)
+{
+ EXPECT_EQ(CA_STATUS_OK, CAHandleRequestResponse());
+}
+
+// CASendRequestToAll TC
+// check return value
+TEST (SendRequestToAllTest, TC_31_Positive_01)
+{
+ uri = (char *) RESOURCE_URI;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+ CAGroupEndpoint_t *group = NULL;
+ group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+ group->connectivityType = tempRep->connectivityType;
+ group->resourceUri = tempRep->resourceUri;
+
+ memset(&requestData, 0, sizeof(CAInfo_t));
+ CAGenerateToken(&tempToken);
+ requestData.token = tempToken;
+
+ requestData.payload = (char *) "Temp Json Payload";
+ requestData.type = CA_MSG_NONCONFIRM;
+ memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
+
+ EXPECT_EQ(CA_STATUS_OK, CASendRequestToAll(group, &requestInfo));
+
+ if (tempToken != NULL)
+ {
+ CADestroyToken(tempToken);
+ }
+
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+
+ free(group);
+}
+
+// check return value when group->resourceUri is NULL
+TEST (SendRequestToAllTest, TC_32_Negative_01)
+{
+ uri = (char *) RESOURCE_URI;
+ CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
+ CAGroupEndpoint_t *group = NULL;
+ group = (CAGroupEndpoint_t *) malloc(sizeof(CAGroupEndpoint_t));
+
+ if (tempRep != NULL)
+ {
+ group->connectivityType = tempRep->connectivityType;
+ group->resourceUri = NULL;
+ }
+
+ memset(&requestData, 0, sizeof(CAInfo_t));
+ CAGenerateToken(&tempToken);
+ requestData.token = tempToken;
+
+ requestData.payload = (char *) "Temp Json Payload";
+ requestData.type = CA_MSG_NONCONFIRM;
+ memset(&requestInfo, 0, sizeof(CARequestInfo_t));
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
+
+ EXPECT_EQ(CA_STATUS_INVALID_PARAM, CASendRequestToAll(group, &requestInfo));
+
+ if (tempToken != NULL)
+ {
+ CADestroyToken(tempToken);
+ }
+
+ if (tempRep != NULL)
+ {
+ CADestroyRemoteEndpoint(tempRep);
+ tempRep = NULL;
+ }
+
+ free(group);
+}
+
+// CAGetNetworkInformation TC
+// check return value
+TEST (GetNetworkInformationTest, TC_33_Positive_01)
+{
+ CALocalConnectivity_t *tempInfo = NULL;
+ uint32_t tempSize = 0;
+
+ EXPECT_EQ(CA_STATUS_OK, CAGetNetworkInformation(&tempInfo, &tempSize));
+}
+
+TEST(RegisterDTLSCredentialsHandlerTest, TC_34_positive_01)
+{
+#ifdef __WITH_DTLS__
+ if (SetCredentials() == 0)
+ {
+ printf("SetCredentials failed\n");
+ return 0;
+ }
+
+ res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
+ EXPECT_EQ(CA_STATUS_OK, CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials));
+#endif
+}
+
+++ /dev/null
-#include "gtest/gtest.h"
-#include "cainterface.h"
-#include "cacommon.h"
-#include <string.h>
-
-using namespace std;
-
-void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo);
-void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
-
-void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo)
-{
- cout << "request_handler, uri : " << (object != NULL) ? object->resourceUri : "";
- cout << ", data : " << (requestInfo != NULL) ? requestInfo->info.payload : "";
- cout << endl;
-}
-
-void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo)
-{
- cout << "response_handler, uri : " << (object != NULL) ? object->resourceUri : "";
- cout << ", data : " << (responseInfo != NULL) ? responseInfo->info.payload : "";
- cout << endl;
-}
-
-char* uri;
-CARemoteEndpoint_t* tempRep = NULL;
-CARequestInfo_t requestInfo;
-CAInfo_t responseData;
-CAResponseInfo_t responseInfo;
-CAToken_t tempToken;
-
-int main(int argc, char **argv)
-{
- testing::InitGoogleTest(&argc, argv);
- return RUN_ALL_TESTS();
-}
-
-// CAInitialize TC
-// check return value
-TEST(InitializeTest, TC_01_Positive_01)
-{
- EXPECT_EQ(CA_STATUS_OK, CAInitialize());
-}
-
-//CATerminate TC
-TEST(TerminateTest, TC_02_Positive_01)
-{
- CATerminate();
-
- char* check = (char *) "terminate success";
- EXPECT_STREQ(check, "terminate success");
-
- CAInitialize();
-}
-// CAStartListeningServer TC
-// check return value
-TEST(StartListeningServerTest, TC_03_Positive_01)
-{
- CASelectNetwork(CA_WIFI);
- EXPECT_EQ(CA_STATUS_OK, CAStartListeningServer());
-}
-
-// CAStartDiscoveryServer TC
-// check return value
-TEST(StartDiscoveryServerTest, TC_04_Positive_01)
-{
- EXPECT_EQ(CA_STATUS_OK, CAStartDiscoveryServer());
-}
-
-// CARegisterHandlerTest TC
-// check return value
-TEST(RegisterHandlerTest, TC_05_Positive_01)
-{
- CARegisterHandler(request_handler, response_handler);
-}
-
-// CACreateRemoteEndpoint TC
-// check return value
-TEST(CreateRemoteEndpointTest, TC_06_Positive_01)
-{
- uri = (char *) "123.123.123.123:1234/b/light";
-
- EXPECT_EQ(CA_STATUS_OK, CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep));
-
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// check remoteEndpoint and values of remoteEndpoint
-TEST(CreateRemoteEndpointTest, TC_07_Positive_02)
-{
- uri = (char *) "123.123.123.123:1234/b/light";
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
-
- EXPECT_TRUE(tempRep != NULL);
-
- if (tempRep != NULL)
- {
- EXPECT_STRNE(NULL, tempRep->resourceUri);
- }
-
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// check return value if uri is NULL
-TEST(CreateRemoteEndpointTest, TC_08_Nagative_01)
-{
- uri = NULL;
-
- EXPECT_EQ(CA_STATUS_FAILED, CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep));
-
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// check values of remoteEndpoint if uri is NULL
-TEST(CreateRemoteEndpointTest, TC_09_Nagative_02)
-{
- uri = NULL;
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
-
- if (tempRep != NULL)
- {
- EXPECT_STREQ(NULL, tempRep->resourceUri);
- }
-
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// CADestroyRemoteEndpoint TC
-// check destroyed remoteEndpoint
-TEST(DestroyRemoteEndpointTest, TC_10_Positive_01)
-{
- uri = (char *) "123.123.123.123:1234/b/light";
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
-
- CADestroyRemoteEndpoint(tempRep);
-
- char * check = (char *) "destroy success";
- EXPECT_STREQ(check, "destroy success");
-}
-
-// CAGerateToken TC
-// check return value
-TEST(GenerateTokenTest, TC_11_Positive_01)
-{
- EXPECT_EQ(CA_STATUS_OK, CAGenerateToken(&tempToken));
-
- CADestroyToken(tempToken);
-}
-
-// CADestroyToken TC
-// check destroyed token
-TEST(DestroyTokenTest, TC_12_Positive_01)
-{
- CAGenerateToken(&tempToken);
- CADestroyToken(tempToken);
-
- char * check = (char *) "destroy success";
- EXPECT_STREQ(check, "destroy success");
-}
-
-// CAFindResource TC
-// check return value
-TEST(FindResourceTest, TC_13_Positive_01)
-{
- CARegisterHandler(request_handler, response_handler);
- uri = (char *) "123.123.123.123:1234/b/light";
- EXPECT_EQ(CA_STATUS_OK, CAFindResource(uri));
-}
-
-// check return value if uri is NULL
-TEST(FindResourceTest, TC_14_Nagative_01)
-{
- CARegisterHandler(request_handler, response_handler);
- uri = NULL;
- EXPECT_EQ(CA_STATUS_FAILED, CAFindResource(uri));
-}
-
-// CASendRequest TC
-// check return value
-TEST(SendRequestTest, TC_15_Positive_01)
-{
- uri = (char *) "123.123.123.123:1234/b/light";
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
- CAGenerateToken(&tempToken);
- requestInfo.method = CA_GET;
- requestInfo.info.token = tempToken;
- requestInfo.info.payload = (char *) "request payload";
-
- EXPECT_EQ(CA_STATUS_OK, CASendRequest(tempRep, &requestInfo));
-
- CADestroyToken(tempToken);
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// check return value if uri is NULL
-TEST(SendRequestTest, TC_16_Nagative_01)
-{
- uri = NULL;
- memset(&requestInfo, 0, sizeof(CARequestInfo_t));
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
- CAGenerateToken(&tempToken);
- requestInfo.method = CA_GET;
- requestInfo.info.token = tempToken;
- requestInfo.info.payload = (char *) "request payload";
-
- EXPECT_EQ(CA_STATUS_FAILED, CASendRequest(tempRep, &requestInfo));
-
- CADestroyToken(tempToken);
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// CASendResponse TC
-// check return value
-TEST(SendResponseTest, TC_17_Positive_01)
-{
- uri = (char *) "123.123.123.123:1234/b/light";
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
-
- memset(&responseData, 0, sizeof(CAInfo_t));
- CAGenerateToken(&tempToken);
- responseData.token = tempToken;
- responseData.payload = (char *) "response payload";
-
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_VALID;
- responseInfo.info = responseData;
-
- EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo));
-
- CADestroyToken(tempToken);
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// check return value if uri is NULL
-TEST(SendResponseTest, TC_18_Nagative_01)
-{
- uri = NULL;
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
-
- memset(&responseData, 0, sizeof(CAInfo_t));
- CAGenerateToken(&tempToken);
- responseData.token = tempToken;
- responseData.payload = (char *) "response payload";
-
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_VALID;
- responseInfo.info = responseData;
-
- EXPECT_EQ(CA_STATUS_FAILED, CASendResponse(tempRep, &responseInfo));
-
- CADestroyToken(tempToken);
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// CASendNotification TC
-// check return value
-TEST(SendNotificationTest, TC_19_Positive_01)
-{
- uri = (char *) "123.123.123.123:1234/b/light";
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
-
- memset(&responseData, 0, sizeof(CAInfo_t));
- responseData.token = (char *) "client token";
- responseData.payload = (char *) "Temp Notification Data";
-
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_SUCCESS;
- responseInfo.info = responseData;
-
- EXPECT_EQ(CA_STATUS_OK, CASendNotification(tempRep, &responseInfo));
-
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// check return value if uri is NULL
-TEST(SendNotificationTest, TC_20_Nagative_01)
-{
- uri = NULL;
- CACreateRemoteEndpoint(uri, CA_ETHERNET, &tempRep);
-
- memset(&responseData, 0, sizeof(CAInfo_t));
- responseData.token = (char *) "client token";
- responseData.payload = (char *) "Temp Notification Data";
-
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_SUCCESS;
- responseInfo.info = responseData;
-
- EXPECT_EQ(CA_STATUS_FAILED, CASendNotification(tempRep, &responseInfo));
-
- CADestroyRemoteEndpoint(tempRep);
-}
-
-// CAAdvertiseResource TC
-// check return value
-TEST(AdvertiseResourceTest, TC_21_Positive_01)
-{
- uri = (char *) "123.123.123.123:1234/b/light";
- int optionNum = 1;
- char* optionData;
- CAHeaderOption_t* headerOpt;
- headerOpt = (CAHeaderOption_t*) malloc(sizeof(CAHeaderOption_t) * optionNum);
- memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
-
- int i;
- for(i = 0 ; i < optionNum ; i++)
- {
- int optionID = 2;
- headerOpt[i].optionID = optionID;
- optionData = (char *) "aaa";
- memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
- headerOpt[i].optionLength = (uint16_t)strlen(optionData);
- }
- EXPECT_EQ(CA_STATUS_OK, CAAdvertiseResource(uri, headerOpt, (uint8_t)optionNum));
-}
-
-// check return value if uri is NULL
-TEST(AdvertiseResourceTest, TC_22_Nagative_01)
-{
- uri = NULL;
- int optionNum = 1;
- char* optionData;
- CAHeaderOption_t* headerOpt;
- headerOpt = (CAHeaderOption_t*) malloc(sizeof(CAHeaderOption_t) * optionNum);
- memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
-
- int i;
- for(i = 0 ; i < optionNum ; i++)
- {
- int optionID = 2;
- headerOpt[i].optionID = optionID;
- optionData = (char *) "aaa";
- memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
- headerOpt[i].optionLength = (uint16_t)strlen(optionData);
- }
- EXPECT_EQ(CA_STATUS_FAILED, CAAdvertiseResource(uri, headerOpt, (uint8_t)optionNum));
-}
-
-// CASelectNewwork TC
-// check return value
-TEST(SelectNetworkTest, TC_23_Positive_01)
-{
- //Select wifi network
- EXPECT_EQ(CA_STATUS_OK, CASelectNetwork(CA_WIFI));
-}
-
-// check return value if selected network is disable
-TEST(SelectNetworkTest, TC_24_Nagative_01)
-{
- //Select disable network
- EXPECT_EQ(CA_NOT_SUPPORTED, CASelectNetwork(20));
-}
-
-// CAUnSelectNewwork TC
-// check return value
-TEST(UnSelectNetworkTest, TC_25_Positive_01)
-{
- //Unselect wifi network
- EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_WIFI));
-}
-
-// check return value if selected network is disable
-TEST(UnSelectNetworkTest, TC_26_Nagative_01)
-{
- //UnSelect disable network
- EXPECT_EQ(CA_NOT_SUPPORTED, CAUnSelectNetwork(20));
-}
-
-// CAHandlerRequestResponse TC
-// check return value
-TEST (HandlerRequestResponseTest, TC_27_Positive_01)
-{
- EXPECT_EQ(CA_STATUS_OK, CAHandleRequestResponse());
-}
-
-
-
+++ /dev/null
-TCT Unit tests for Tizen:
-==========================
-1. TCT tool should be setup in linux to execute these test cases. Please refer to "CoreAPI Test Manual.pptx" present in this folder.
-2. OIC-CA package should be built first.
-3. Copy liboic to <TCT Directory>/core-api/src.
-4. Copy packaging/core-liboic-tests.spec to <TCT Directory>/packaging.
-5. Build oic test case project with "sudo ./tctbuild build liboic".
-6. Install test framework to device with "sudo ./tctbuild install liboic".
-7. Run tct tool with "tct-mgr".
-
-Note: For BLE, please copy BLE libs and headers from the path /connectivity/lib/tizen/ble/libs to /usr/lib and from /connectivity/lib/tizen/ble/inc
-to /usr/include/network before building test case project.
\ No newline at end of file
+++ /dev/null
-SET(PKG_NAME "liboic")
-
-SET(EXEC_NAME "tct-${PKG_NAME}-core")
-SET(RPM_NAME "core-${PKG_NAME}-tests")
-
-SET(CAPI_LIB "liboic")
-SET(TC_SOURCES
- #utc-liboic.c
- wifi/utc-wifi-liboic.c
- #bt/utc-bt-liboic.c
-)
-
-#PKG_CHECK_MODULES(${CAPI_LIB} REQUIRED
-# ${CAPI_LIB}
-#)
-PKG_CHECK_MODULES(pkgs REQUIRED
- capi-network-bluetooth capi-network-wifi com.samsung.oicca dlog gobject-2.0 glib-2.0
-)
-
-INCLUDE_DIRECTORIES(
- ${${CAPI_LIB}_INCLUDE_DIRS}
- /usr/include/glib-2.0
- /usr/lib/glib-2.0/include
- /usr/lib/
- /usr/include/network
-)
-ADD_DEFINITIONS("-D__TIZEN__")
-ADD_EXECUTABLE(${EXEC_NAME} ${EXEC_NAME}.c ${TC_SOURCES})
-TARGET_LINK_LIBRARIES(${EXEC_NAME}
- ${${CAPI_LIB}_LIBRARIES} -loicinterface -lm -lpthread -lrt -ldl -lstdc++ -lgobject-2.0 -lgio-2.0 -lglib-2.0 -lcapi-network-wifi -ldlog -lcapi-network-bluetooth
-)
-
-INSTALL(PROGRAMS ${EXEC_NAME}
- DESTINATION ${BIN_DIR}/${EXEC_NAME}
-)
+++ /dev/null
-#include <assert.h>
-#include "interfaceHeaders/cacommon.h"
-#include "interfaceHeaders/caadapterinterface.h"
-#include "interfaceHeaders/caedradapter.h"
-#include "interfaceHeaders/uthreadpool.h"
-
-CALocalConnectivity_t *localBtEndpoint = NULL;
-// Global bt Addr. Change this before testing.
-char btAddr[CA_MACADDR_SIZE] = "BC:79:AD:E6:BC:F6";
-
-static u_thread_pool_t gBTThreadPool = NULL;
-
-// Hardcoded values to Test
-char coapData[500] = "{\"oc:\[{href\":\"/a/light\",\"ref\":{\"power\":\"20\",\"state\":\"true\"}}\]}";
-
-typedef struct ConnectivityHandlerList
-{
- CAConnectivityType_t type;
- CAConnectivityHandler_t handler;
- struct ConnectivityHandlerList *nextHandler;
-} ConnectivityHandlerList;
-
-CAConnectivityHandler_t *gConnectivityHandlers = NULL;
-
-void initializeThreadPool(int d)
-{
- if (CA_STATUS_OK != u_thread_pool_init(3, &gBTThreadPool))
- printf("Failed to create thread pool for BT adapter!\n");
-}
-
-void interfaceRegisterCallback(CAConnectivityHandler_t handler,
- CAConnectivityType_t connType)
-{
- printf("interfaceRegisterCallback Entry in Sample\n");
- ConnectivityHandlerList *newConnectivityHandler = (ConnectivityHandlerList *) malloc(sizeof(
- ConnectivityHandlerList));
- if (NULL == newConnectivityHandler)
- {
- printf("Memory allocation failed!\n");
- return;
- }
-
- newConnectivityHandler->type = connType;
- newConnectivityHandler->handler = handler;
- printf("interfaceRegisterCallback Exit in Sample\n");
-}
-
-void requestResponseHandler(CARemoteEndpoint_t *object, void *data)
-{
- printf("\nrequestResponseHandler Entry in Sample");
- if (NULL == object || NULL == data)
- {
- printf("\nNULL Object");
- return;
- }
-
- if (object->addressInfo.BT.btMacAddress)
- printf("\nData Received from %s\n", object->addressInfo.BT.btMacAddress);
- if (data)
- printf("\nReceived Data : %s \n", (char *)data);
-
- printf("\nrequestResponseHandler Exit in Sample");
-}
-
-
-void networkInterfaceCallback(CALocalConnectivity_t *localEndPoint,
- CANetworkStatus_t networkConnectivityState)
-{
- printf("\nnetworkInterfaceCallback Entry in Sample");
- if (NULL == localEndPoint)
- {
- printf("\nNULL Object");
- return;
- }
-
- if (localEndPoint->addressInfo.BT.btMacAddress)
- printf("\n Interface Address%s\n", localEndPoint->addressInfo.BT.btMacAddress);
-
- if (networkConnectivityState == CA_INTERFACE_UP)
- printf("\n BT Status is UP");
- else
- printf("\n BT Status is DOWN");
- printf("\nnetworkInterfaceCallback Exit in Sample");
-}
-
-void utc_liboic_startup(void)
-{
-
-}
-
-void utc_liboic_cleanup(void)
-{
-
-}
-
-
-int bt_tc_001_intializeBT_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- initializeThreadPool(0);
- error = CAInitializeEDR(interfaceRegisterCallback, requestResponseHandler,
- networkInterfaceCallback, gBTThreadPool);
- assert_eq(error, CA_STATUS_OK);
- CATerminateEDR();
- return 0;
-}
-
-int bt_tc_002_intializeBT_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- initializeThreadPool(0);
- error = CAInitializeEDR(NULL, NULL, NULL, gBTThreadPool);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- return 0;
-}
-
-int bt_tc_003_getBTInterfaceInformation_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- initializeThreadPool(0);
- // Startup
- CAInitializeEDR(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gBTThreadPool);
- uint32_t size = 0;
-
- error = CAGetEDRInterfaceInformation(&localBtEndpoint, &size);
- assert_eq(error, CA_STATUS_OK);
-
- CATerminateEDR();
- // Now, check local endpoint information
- //assert_neq(localBtEndpoint->endpoint_info, NULL);
- //assert_neq(localBtEndpoint->endpoint_info->address, NULL);
- return 0;
-}
-
-int bt_tc_004_getBTInterfaceInformation_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- error = CAGetEDRInterfaceInformation(NULL, NULL);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- return 0;
-}
-
-int bt_tc_005_startAdapter_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- initializeThreadPool(0);
- CAInitializeEDR(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gBTThreadPool);
- error = CAStartEDR();
- assert_eq(error, CA_STATUS_OK);
- CAStopEDR();
- CATerminateEDR();
- return 0;
-}
-
-int bt_tc_006_sendBTUnicastData_p(void)
-{
- int dataSize = 0;
- int ret = -1;
- int ref = 0;
-
- initializeThreadPool(0);
- // Startup
- CAInitializeEDR(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gBTThreadPool);
- CAStartEDR();
- CAStartEDRListeningServer();
-
- CARemoteEndpoint_t endpoint;
- endpoint.connectivityType = CA_EDR;
- strncpy(endpoint.addressInfo.BT.btMacAddress, btAddr, CA_MACADDR_SIZE - 1);
- endpoint.addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
- endpoint.resourceUri = NULL;
- ret = CASendEDRUnicastData(&endpoint, coapData, strlen(coapData) + 1);
- sleep(5);
-
- // Cleanup
- CAStopEDR();
- CATerminateEDR();
-
- assert_eq(ret, strlen(coapData) + 1);
- return 0;
-}
-
-int bt_tc_007_sendBTUnicastData_n(void)
-{
- int dataSize = 0;
- int ret = -1;
- initializeThreadPool(0);
- CAInitializeEDR(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gBTThreadPool);
- ret = CASendEDRUnicastData(NULL, NULL, NULL);
- CATerminateEDR();
- assert_eq(ret, 0);
- return 0;
-}
-
-int bt_tc_008_sendBTMulticastDataToAll_p(void)
-{
- int dataSize = 0;
- int ret = 0;
- CAStartEDRListeningServer();
- ret = CASendEDRMulticastData(coapData, strlen(coapData) + 1);
- assert_eq(ret, strlen(coapData) + 1);
- CAStopEDR();
- CATerminateEDR();
- return 0;
-}
-
-int bt_tc_009_sendBTMulticastDataToAll_n(void)
-{
- int dataSize = 0;
- int ret = -1;
- initializeThreadPool(0);
- CAInitializeEDR(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gBTThreadPool);
- ret = CASendEDRMulticastData(NULL, NULL);
- CATerminateEDR();
- assert_eq(ret, 0);
- return 0;
-}
-
-int bt_tc_010_StartListeningServer_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- int ref = 0;
- initializeThreadPool(0);
- // Startup
- CAInitializeEDR(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gBTThreadPool);
-
- error = CAStartEDRListeningServer();
- assert_eq(error, CA_STATUS_OK);
- // Cleanup
- CAStopEDR();
- CATerminateEDR();
- return 0;
-}
-
-int bt_tc_011_StopRfCommServer_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- int ref = 0;
- initializeThreadPool(0);
- // Startup
- CAInitializeEDR(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gBTThreadPool);
- CAStartEDRListeningServer();
-
- error = CAStopEDR();
- assert_eq(error, CA_STATUS_OK);
- // Cleanup
- CATerminateEDR();
- return 0;
-}
+++ /dev/null
-#include <stdio.h>
-#include <string.h>
-#include "tct-liboic-core.h"
-
-int main(int argc, const char* argv[])
-{
- int result = -1;
- int i;
-
- if (argc != 2) {
- printf("Usage: %s <testcase name>\n", argv[0]);
- return 2;
- }
-
- for (i = 0; tc_array[i].name; i++) {
- if (!strcmp(argv[1], tc_array[i].name)) {
- if (tc_array[i].startup)
- tc_array[i].startup();
-
- result = tc_array[i].function();
-
- if (tc_array[i].cleanup)
- tc_array[i].cleanup();
-
- return result;
- }
- }
-
- printf("Unknown testcase name: \"%s\"\n", argv[1]);
- return 2;
-}
+++ /dev/null
-#ifndef __TCT_LIBOIC_CORE_H__
-#define __TCT_LIBOIC_CORE_H__
-
-#include "testcase.h"
-
-extern void utc_liboic_startup(void);
-extern void utc_liboic_cleanup(void);
-
-extern int wifi_tc_001_initializeWifi_p(void);
-extern int wifi_tc_002_initializeWifi_n(void);
-extern int wifi_tc_003_getWIFIInterfaceInformation_p(void);
-extern int wifi_tc_004_getWIFIInterfaceInformation_n(void);
-extern int wifi_tc_005_sendWifiUnicastData_p(void);
-extern int wifi_tc_006_sendWifiUnicastData_n(void);
-extern int wifi_tc_007_sendWifiMulticastData_p(void);
-extern int wifi_tc_008_sendWifiMulticastData_n(void);
-extern int wifi_tc_009_startUnicastServer_p(void);
-extern int wifi_tc_010_startUnicastServer_n(void);
-extern int wifi_tc_011_startUnicastServer_n(void);
-extern int wifi_tc_012_startUnicastServer_n(void);
-extern int wifi_tc_013_startMulticastServer_p(void);
-extern int wifi_tc_014_startMulticastServer_n(void);
-extern int wifi_tc_015_startMulticastServer_n(void);
-extern int wifi_tc_016_startMulticastServer_n(void);
-extern int wifi_tc_017_startMulticastServer_n(void);
-
-testcase tc_array[] = {
- {"wifi_tc_001_initializeWifi_p", wifi_tc_001_initializeWifi_p, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_002_initializeWifi_n", wifi_tc_002_initializeWifi_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_003_getWIFIInterfaceInformation_p", wifi_tc_003_getWIFIInterfaceInformation_p, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_004_getWIFIInterfaceInformation_n", wifi_tc_004_getWIFIInterfaceInformation_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_005_sendWifiUnicastData_p", wifi_tc_005_sendWifiUnicastData_p, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_006_sendWifiUnicastData_n", wifi_tc_006_sendWifiUnicastData_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_007_sendWifiMulticastData_p", wifi_tc_007_sendWifiMulticastData_p, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_008_sendWifiMulticastData_n", wifi_tc_008_sendWifiMulticastData_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_009_startUnicastServer_p", wifi_tc_009_startUnicastServer_p, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_010_startUnicastServer_n", wifi_tc_010_startUnicastServer_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_011_startUnicastServer_n", wifi_tc_011_startUnicastServer_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_012_startUnicastServer_n", wifi_tc_012_startUnicastServer_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_013_startMulticastServer_p", wifi_tc_013_startMulticastServer_p, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_014_startMulticastServer_n", wifi_tc_014_startMulticastServer_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_015_startMulticastServer_n", wifi_tc_015_startMulticastServer_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_016_startMulticastServer_n", wifi_tc_016_startMulticastServer_n, utc_liboic_startup, utc_liboic_cleanup},
- {"wifi_tc_017_startMulticastServer_n", wifi_tc_017_startMulticastServer_n, utc_liboic_startup, utc_liboic_cleanup},
- {NULL, NULL}
-};
-
-#endif // __TCT_LIBOIC_CORE_H__
+++ /dev/null
-#include "assert.h"
-#include "oic-core/logger.h"
-#include "oic-core/csdk.h"
-#include "interfaceHeaders/common.h"
-#include "interfaceHeaders/connectivity_interface.h"
-#include "interfaceHeaders/WiFiInterface.h"
-#include "interfaceHeaders/bt_interface.h"
-
-//& set: Liboic
-
-void utc_liboic_startup(void)
-{
- /*Precondition for each TC*/
-}
-
-void utc_liboic_cleanup(void)
-{
- /*Postcondition for each TC*/
-}
-
-
-//& purpose: A purpose of a first positive TC.
-int first_tc_p(void)
-{
- return 0;
-}
-
-//& purpose: A purpose of a first negative TC.
-int first_tc_n(void)
-{
- return 0;
-}
+++ /dev/null
-#include <assert.h>
-#include <stdbool.h>
-#include <unistd.h>
-
-#include "interfaceHeaders/cacommon.h"
-#include "interfaceHeaders/caadapterinterface.h"
-#include "interfaceHeaders/cawifiadapter.h"
-#include "interfaceHeaders/uthreadpool.h"
-
-// & set: Liboic
-
-// Wifi callbacks
-
-CALocalConnectivity_t* localWifiEndpoint = NULL;
-CARemoteEndpoint_t remoteMulticastEndpoint;
-CARemoteEndpoint_t remoteEndpoint[10]; /* 10 RemoteEndpoints are currently kept */
-char remoteIPAddress[CA_IPADDR_SIZE] = "192.168.1.103"; // Change the Corresponding IP address during testing.
-char localIPAddress[CA_IPADDR_SIZE] = {0};
-static u_thread_pool_t gWiFiThreadPool = NULL;
-
-typedef struct ConnectivityHandlerList {
- CAConnectivityType_t type;
- CAConnectivityHandler_t handler;
- struct ConnectivityHandlerList* nextHandler;
-} ConnectivityHandlerList;
-
-// Hardcoded values to Test
-char coapData[500] = "{\"oc:\[{href\":\"/a/light\",\"ref\":{\"power\":\"20\",\"state\":\"true\"}}\]}";
-
-/**
- * @def CA_PORT
- * @brief Unicast port number (to listen for incoming data on unicast server).
- * Note :- Actual port number may differ based on result of bind() operation.
- */
-#define CA_PORT 5298
-
-/**
- * @def CA_MCAST_PORT
- * @brief Multicast port number as defined in COAP Specification, RFC-7252.
- */
-#define CA_MCAST_PORT 5683
-
-/**
- * @def CA_MULTICAST_IP
- * @brief Multicast IP Address
- */
-#define CA_MULTICAST_IP "224.0.1.187"
-
-
-CAConnectivityHandler_t* gCAConnectivityHandlers = NULL;
-
-void initializeThreadPool(int d)
-{
- if (CA_STATUS_OK != u_thread_pool_init(3, &gWiFiThreadPool))
- printf("Failed to create thread pool for WiFi adapter!\n");
-}
-
-int interfaceInitializeEndpoint(int d)
-{
- int i = 0;
- /* As of initializing one endpoint */
- for (i = 0; i < 1; i++)
- {
- remoteEndpoint[i].connectivityType = CA_WIFI;
- strncpy(remoteEndpoint[i].addressInfo.IP.ipAddress, remoteIPAddress, CA_IPADDR_SIZE);
- remoteEndpoint[i].addressInfo.IP.port = 5283; /* Send the corresponding port here */
- }
-
- remoteMulticastEndpoint.connectivityType = CA_WIFI;
-}
-
-void interfaceRegisterCallback(CAConnectivityHandler_t handler,
- CAConnectivityType_t connType)
-{
- printf("interfaceRegisterCallback Entry in Sample\n");
- ConnectivityHandlerList* newConnectivityHandler = (ConnectivityHandlerList*) malloc(sizeof(ConnectivityHandlerList));
- newConnectivityHandler->type = connType;
- newConnectivityHandler->handler = handler;
- printf("interfaceRegisterCallback Exit in Sample\n");
-}
-
-
-void requestResponseHandler(CARemoteEndpoint_t* object, void* data)
-{
- printf("\nrequestResponseHandler Entry in Sample");
- if (NULL == object || NULL == data) {
- printf("\nNULL Object");
- }
- if (object->addressInfo.IP.ipAddress)
- printf("\nData Received from %s\n", object->addressInfo.IP.ipAddress);
- if (data)
- printf("\nReceived Data : %s \n", (char*)data);
-
- printf("\nrequestResponseHandler Exit in Sample");
-}
-
-
-void networkInterfaceCallback(CALocalConnectivity_t* localEndPoint, CANetworkStatus_t networkConnectivityState)
-{
- printf("\nnetworkInterfaceCallback Entry in Sample");
- if (NULL == localEndPoint) {
- printf("\nNULL Object");
- }
- if (localEndPoint->addressInfo.IP.ipAddress)
- printf("\n Local Interface Address%s\n", localEndPoint->addressInfo.IP.ipAddress);
-
- if (networkConnectivityState == CA_INTERFACE_UP)
- printf("\n WiFi Network Status is UP");
- else
- printf("\n WiFi Network Status is DOWN");
- printf("\nnetworkInterfaceCallback Exit in Sample");
-}
-
-void utc_liboic_startup(void)
-{
-
-}
-
-void utc_liboic_cleanup(void)
-{
-
-}
-
-int wifi_tc_001_initializeWifi_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- initializeThreadPool(0);
- error = CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- assert_eq(error, CA_STATUS_OK);
- u_thread_pool_free(gWiFiThreadPool);
- return 0;
-}
-
-int wifi_tc_002_initializeWifi_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- initializeThreadPool(0);
- error = CAInitializeWifi(NULL, NULL, NULL, NULL);
- assert_eq(error, CA_STATUS_INVALID_PARAM); // Note: initializeWifi always return OC_STACK_OK
- u_thread_pool_free(gWiFiThreadPool);
- return 0;
-}
-
-int wifi_tc_003_getWIFIInterfaceInformation_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- uint32_t size = 0;
-
- //Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
- assert_eq(error, CA_STATUS_OK);
- return 0;
-}
-
-int wifi_tc_004_getWIFIInterfaceInformation_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- uint32_t size = 0;
- error = CAGetWIFIInterfaceInformation(NULL, &size);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- return 0;
-}
-
-int wifi_tc_005_sendWifiUnicastData_p(void)
-{
- uint32_t dataSize;
-
- //Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
- // localWifiEndpoint->addressInfo.IP.port = 5283;
- interfaceInitializeEndpoint(0);
- dataSize = CASendWIFIUnicastData(&remoteEndpoint[0], coapData, strlen(coapData));
- sleep(5);
-
- assert_eq(dataSize, strlen(coapData));
-
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_006_sendWifiUnicastData_n(void)
-{
- int dataSize = 0;
- dataSize = CASendWIFIUnicastData(NULL, NULL, NULL);
- assert_eq(dataSize, 0);
- return 0;
-}
-
-int wifi_tc_007_sendWifiMulticastData_p(void)
-{
- uint32_t dataSize = 0;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
-
- dataSize = CASendWIFIMulticastData(coapData, strlen(coapData));
- sleep(5);
- assert_eq(dataSize, strlen(coapData));
-
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_008_sendWifiMulticastData_n(void)
-{
- int dataSize = 0;
- dataSize = CASendWIFIMulticastData(NULL, NULL);
- assert_eq(dataSize, 0);
- return 0;
-}
-
-int wifi_tc_009_startUnicastServer_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- int16_t unicastPort = CA_PORT;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- // error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
- error = CAWiFiStartUnicastServer("0.0.0.0", &unicastPort, false, false, &serverFd);
- assert_eq(error, CA_STATUS_OK);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_010_startUnicastServer_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
-
- error = CAWiFiStartUnicastServer(NULL, &localWifiEndpoint->addressInfo.IP.port, false, false, &serverFd);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_011_startUnicastServer_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
-
- error = CAWiFiStartUnicastServer(localWifiEndpoint->addressInfo.IP.ipAddress, NULL, false, false, &serverFd);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_012_startUnicastServer_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
-
- error = CAWiFiStartUnicastServer(NULL, NULL, false, false, &serverFd);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_013_startMulticastServer_p(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- int16_t multicastPort = CA_MCAST_PORT;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
-
- error = CAWiFiStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, multicastPort, &serverFd);
- assert_eq(error, CA_STATUS_OK);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_014_startMulticastServer_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- int16_t multicastPort = CA_MCAST_PORT;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
-
- error = CAWiFiStartMulticastServer(NULL, "0.0.0.0", multicastPort, &serverFd);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_015_startMulticastServer_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- int16_t multicastPort = CA_MCAST_PORT;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
-
- error = CAWiFiStartMulticastServer(NULL, CA_MULTICAST_IP, multicastPort, &serverFd);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_016_startMulticastServer_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- int16_t multicastPort = CA_MCAST_PORT;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
-
- error = CAWiFiStartMulticastServer("0.0.0.0", CA_MULTICAST_IP, NULL, &serverFd);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
-int wifi_tc_017_startMulticastServer_n(void)
-{
- CAResult_t error = CA_STATUS_FAILED;
- int16_t multicastPort = CA_MCAST_PORT;
- // Startup
- initializeThreadPool(0);
- CAInitializeWifi(interfaceRegisterCallback, requestResponseHandler, networkInterfaceCallback, gWiFiThreadPool);
- CAStartWIFI();
- uint32_t size = 0;
- int32_t serverFd = 0;
- error = CAGetWIFIInterfaceInformation(&localWifiEndpoint, &size);
-
- error = CAWiFiStartMulticastServer(NULL, NULL, NULL, NULL, &serverFd);
- assert_eq(error, CA_STATUS_INVALID_PARAM);
- // Cleanup
- CAStopWIFI();
- u_thread_pool_free(gWiFiThreadPool);
- CATerminateWIfI();
- return 0;
-}
-
+++ /dev/null
-%define MODULE_NAME liboic
-%define MODULE_LIBNAME liboic
-Name: core-%{MODULE_NAME}-tests
-Summary: Core API unit TC (%{name})
-Version: 0.1
-Release: 0
-Group: Development/Tools
-License: Apache License, Version 2.0, Samsung Properietary
-Source0: %{name}-%{version}.tar.gz
-#BuildRequires: pkgconfig(%{MODULE_LIBNAME})
-BuildRequires: pkgconfig(capi-network-wifi)
-BuildRequires: pkgconfig(glib-2.0)
-BuildRequires: pkgconfig(capi-network-bluetooth)
-BuildRequires: pkgconfig(dlog)
-#BuildRequires: pkgconfig(oic-core)
-BuildRequires: pkgconfig(com.samsung.oicca)
-BuildRequires: cmake
-
-%description
-Core API unit TC (%{name})
-
-%prep
-%setup -q
-
-%build
-
-%define PREFIX "%{_libdir}/%{name}"
-
-export LDFLAGS+="-Wl,--rpath=%{PREFIX} -Wl,--as-needed"
-
-cmake . -DMODULE="%{MODULE_NAME}" -DCMAKE_INSTALL_PREFIX=%{_prefix}
-
-make %{?jobs:-j%jobs}
-
-%install
-rm -rf %{buildroot}
-%make_install
-mkdir -p %{buildroot}/opt/usr/share/license
-cp LICENSE %{buildroot}/opt/usr/share/license/%{name}
-mkdir -p %{buildroot}/tmp/
-cp scripts/add_all_smack_rule.sh %{buildroot}/tmp/
-cp scripts/all_smack.rule %{buildroot}/tmp/
-#mkdir -p %{buildroot}/opt/usr/bin/tct-liboic-core
-#cp src/liboic/libcapi-network-wifi.so.0 %{buildroot}/opt/usr/bin/tct-liboic-core
-#cp src/liboic/libcapi-network-wifi.so.0.1.20 %{buildroot}/opt/usr/bin/tct-liboic-core
-#cp src/liboic/libcapi-network-wifi.so.1 %{buildroot}/opt/usr/bin/tct-liboic-core
-%post
-
-%postun
-
-
-%files
-/opt/usr/bin/*
-#/usr/$(BIN_DIR)/lib*.so*
-/opt/usr/share/license/%{name}
-/tmp/add_all_smack_rule.sh
-/tmp/all_smack.rule
{
while (size--)
{
- if (info[size].isSecured == CA_TRUE && info[size].type == connType)
+ if (info[size].isSecured == true && info[size].type == connType)
{
if (info[size].type == CA_ETHERNET ||
info[size].type == CA_WIFI)
responseEndpoint.resourceUri = (CAURI_t) serverRequest->resourceUrl;
responseEndpoint.addressInfo = serverRequest->addressInfo;
responseEndpoint.connectivityType = serverRequest->connectivityType;
- responseEndpoint.isSecured = (CABool_t) serverRequest->secured;
+ responseEndpoint.isSecured = serverRequest->secured;
// Copy the info
switch (ehResponse->ehResult)