Implementation of connectivity abstraction feature Release v0.3
authorashok.channa <ashok.channa@samsung.com>
Thu, 4 Dec 2014 09:25:59 +0000 (18:25 +0900)
committerashok.channa <ashok.channa@samsung.com>
Thu, 4 Dec 2014 09:38:31 +0000 (18:38 +0900)
Connectivity Abstraction feature provides unified approach for multiple
Transports

Please read the RELEASE v0.3 @csdk\connectivity for more information.
releasing the source code.

Signed-off-by: ashok.channa <ashok.channa@samsung.com>
Change-Id: I1cbadc918e9f54e5664b2ffca8c4908e8acb010f

114 files changed:
resource/csdk/connectivity/RELEASE v0.3 [new file with mode: 0644]
resource/csdk/connectivity/api/cainterface.h
resource/csdk/connectivity/build/Makefile
resource/csdk/connectivity/build/arduino/Makefile [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/README.txt [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/arduinomega.properties [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/build.sh [new file with mode: 0644]
resource/csdk/connectivity/build/arduino/local.properties [new file with mode: 0644]
resource/csdk/connectivity/build/linux/Makefile
resource/csdk/connectivity/build/tizen/Makefile
resource/csdk/connectivity/common/inc/logger.h
resource/csdk/connectivity/common/inc/uarraylist.h
resource/csdk/connectivity/common/inc/umutex.h
resource/csdk/connectivity/common/inc/uthreadpool.h
resource/csdk/connectivity/common/src/logger.c
resource/csdk/connectivity/common/src/logger.cpp [new file with mode: 0644]
resource/csdk/connectivity/common/src/oic_malloc.c
resource/csdk/connectivity/common/src/uarraylist.c
resource/csdk/connectivity/common/src/umutex.c
resource/csdk/connectivity/common/src/uqueue.c
resource/csdk/connectivity/common/src/uthreadpool.c
resource/csdk/connectivity/doc/release/RELEASE v0.2 [moved from resource/csdk/connectivity/RELEASE v0.2 with 100% similarity]
resource/csdk/connectivity/inc/caadapterinterface.h
resource/csdk/connectivity/inc/caadapterutils.h
resource/csdk/connectivity/inc/caedradapter.h
resource/csdk/connectivity/inc/caedradapter_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caethernetadapter_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caethernetcore.h
resource/csdk/connectivity/inc/cainterfacecontroller.h
resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/caleadapter.h
resource/csdk/connectivity/inc/caleadapter_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/calecore.h [new file with mode: 0644]
resource/csdk/connectivity/inc/camessagehandler.h
resource/csdk/connectivity/inc/camessagehandler_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/camessagequeue.h
resource/csdk/connectivity/inc/canetworkconfigurator.h
resource/csdk/connectivity/inc/caprotocolmessage.h
resource/csdk/connectivity/inc/cawifiadapter.h
resource/csdk/connectivity/inc/cawifiadapter_singlethread.h [new file with mode: 0644]
resource/csdk/connectivity/inc/cawificore.h
resource/csdk/connectivity/lib/arduinomega.properties [new file with mode: 0644]
resource/csdk/connectivity/lib/libcoap-4.1.1/address.h
resource/csdk/connectivity/lib/libcoap-4.1.1/bits.h
resource/csdk/connectivity/lib/libcoap-4.1.1/block.c
resource/csdk/connectivity/lib/libcoap-4.1.1/block.h
resource/csdk/connectivity/lib/libcoap-4.1.1/coap_time.h
resource/csdk/connectivity/lib/libcoap-4.1.1/config.h
resource/csdk/connectivity/lib/libcoap-4.1.1/debug.c
resource/csdk/connectivity/lib/libcoap-4.1.1/encode.h
resource/csdk/connectivity/lib/libcoap-4.1.1/makefile_arduino.mak [new file with mode: 0644]
resource/csdk/connectivity/lib/libcoap-4.1.1/net.c
resource/csdk/connectivity/lib/libcoap-4.1.1/net.h
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c
resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h
resource/csdk/connectivity/lib/libcoap-4.1.1/resource.c
resource/csdk/connectivity/lib/local.properties [new file with mode: 0644]
resource/csdk/connectivity/samples/arduino/casample.cpp [new file with mode: 0644]
resource/csdk/connectivity/samples/arduino/sample_main.cpp [new file with mode: 0644]
resource/csdk/connectivity/samples/linux/sample_main.c
resource/csdk/connectivity/samples/tizen/casample.c
resource/csdk/connectivity/samples/tizen/interfacesample.c
resource/csdk/connectivity/src/adapter_util/caadapterutils.c
resource/csdk/connectivity/src/adapter_util/camessagequeue.c
resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtclient.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtclient.h
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtdevicelist.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtdevicelist.h
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtendpoint.h
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtmanager.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtmanager.h
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtserver.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtserver.h
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtutils.c
resource/csdk/connectivity/src/bt_edr_adapter/tizen/cabtutils.h
resource/csdk/connectivity/src/bt_edr_adapter/tizen/caedradapter.c
resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/linux/caleadapter.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclient.h
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclientutil.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableclientutil.h
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.c
resource/csdk/connectivity/src/bt_le_adapter/tizen/cableserver.h
resource/csdk/connectivity/src/caconnectivitymanager.c
resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/cainterfacecontroller.c
resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/connectivity/src/camessagehandler_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/canetworkconfigurator.c
resource/csdk/connectivity/src/canetworkconfigurator_singlethread.c [new file with mode: 0644]
resource/csdk/connectivity/src/caprotocolmessage.c
resource/csdk/connectivity/src/caqueueingthread.c
resource/csdk/connectivity/src/caremotehandler.c
resource/csdk/connectivity/src/ethernet_adapter/arduino/README.txt [new file with mode: 0644]
resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapter.c [new file with mode: 0644]
resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.h [new file with mode: 0644]
resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetadapter.c
resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetcore.c
resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapter.c [new file with mode: 0644]
resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapterutils.cpp [new file with mode: 0644]
resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapterutils.h [new file with mode: 0644]
resource/csdk/connectivity/src/wifi_adapter/linux/cawifiadapter.c
resource/csdk/connectivity/src/wifi_adapter/linux/cawificore.c
resource/csdk/connectivity/src/wifi_adapter/tizen/caethernetadapter.c
resource/csdk/connectivity/src/wifi_adapter/tizen/cawifiadapter.c
resource/csdk/connectivity/src/wifi_adapter/tizen/cawificlient.c
resource/csdk/connectivity/src/wifi_adapter/tizen/cawificlient.h
resource/csdk/connectivity/src/wifi_adapter/tizen/cawifimonitor.c
resource/csdk/connectivity/src/wifi_adapter/tizen/cawifiserver.c
resource/csdk/connectivity/unittests/tizen/tct/liboic/wifi/utc-wifi-liboic.c

diff --git a/resource/csdk/connectivity/RELEASE v0.3 b/resource/csdk/connectivity/RELEASE v0.3
new file mode 100644 (file)
index 0000000..034abe1
--- /dev/null
@@ -0,0 +1,87 @@
+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)
index a88e10f..6a2f6a2 100644 (file)
@@ -43,8 +43,8 @@ extern "C"
  *                              address based on the connectivity type.
  * @param   requestInfo [OUT]   Identifier which needs to be sent with request.
  */
-typedef void (*CARequestCallback)(const CARemoteEndpoint_tobject,
-        const CARequestInfo_t* requestInfo);
+typedef void (*CARequestCallback)(const CARemoteEndpoint_t *object,
+                                  const CARequestInfo_t *requestInfo);
 
 /**
  * @brief   Callback function type for response delivery.
@@ -52,8 +52,8 @@ typedef void (*CARequestCallback)(const CARemoteEndpoint_t* object,
  * @param   object          [OUT]   Endpoint object from which the response is received.
  * @param   responseInfo    [OUT]   Identifier which needs to be mapped with response.
  */
-typedef void (*CAResponseCallback)(const CARemoteEndpoint_tobject,
-        const CAResponseInfo_t* responseInfo);
+typedef void (*CAResponseCallback)(const CARemoteEndpoint_t *object,
+                                   const CAResponseInfo_t *responseInfo);
 
 /**
  * @brief   Initialize the connectivity abstraction module.
@@ -105,13 +105,13 @@ CAResult_t CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback Re
  * @param   object  [OUT ]  Endpoint object which contains the above parsed data
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, CARemoteEndpoint_t** object);
+CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, CARemoteEndpoint_t **object);
 
 /**
  * @brief   API Destroy the remote endpoint created
  * @param   object  [IN]    endpoint object created with CACreateRemoteEndpoint
  */
-void CADestroyRemoteEndpoint(CARemoteEndpoint_tobject);
+void CADestroyRemoteEndpoint(CARemoteEndpoint_t *object);
 
 /**
  * @brief   Generating the token for the requests/response.
@@ -119,7 +119,7 @@ void CADestroyRemoteEndpoint(CARemoteEndpoint_t* object);
  * @param   token   [OUT]   token for the request
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CAGenerateToken(CAToken_ttoken);
+CAResult_t CAGenerateToken(CAToken_t *token);
 
 /**
  * @brief   Destroy the token generated by CAGenerateToken
@@ -134,7 +134,7 @@ void CADestroyToken(CAToken_t token);
  * @param   resourceUri [IN]    Uri to send multicast search request
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CAFindResource(const CAURI_t resourceUri);
+CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token);
 
 /**
  * @brief   Send control Request on a resource
@@ -143,7 +143,7 @@ CAResult_t CAFindResource(const CAURI_t resourceUri);
  * @param   requestInfo [IN ]   information for the request.
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CASendRequest(const CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo);
+CAResult_t CASendRequest(const CARemoteEndpoint_t *object, CARequestInfo_t *requestInfo);
 
 /**
  * @brief   Sendi the response
@@ -152,7 +152,7 @@ CAResult_t CASendRequest(const CARemoteEndpoint_t* object, CARequestInfo_t* requ
  * @param   responseInfo    [IN ]   information for the response
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CASendResponse(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
+CAResult_t CASendResponse(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo);
 
 /**
  * @brief   Send notification to the remote object
@@ -161,7 +161,7 @@ CAResult_t CASendResponse(const CARemoteEndpoint_t* object, CAResponseInfo_t* re
  * @param   responseInfo    [IN ]   information for the response.
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CASendNotification(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo);
+CAResult_t CASendNotification(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo);
 
 /**
  * @brief   for advertise the resource
@@ -170,8 +170,8 @@ CAResult_t CASendNotification(const CARemoteEndpoint_t* object, CAResponseInfo_t
  * @param   numOptions  [IN]    number of options
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAHeaderOption_t* options,
-        uint8_t numOptions);
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAToken_t token, CAHeaderOption_t* options,
+                               uint8_t numOptions);
 
 /**
  * @brief   Select network to use
@@ -194,7 +194,7 @@ CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork);
  * @param   size    [OUT]   No Of Array objects
  * @return  CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
  */
-CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_tsize);
+CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size);
 
 /**
  * @brief   for usage of singled threaded application.
index da6eb11..f732213 100644 (file)
@@ -26,6 +26,7 @@
 BUILD   := debug
 PLATFORM := linux
 TRANSPORT := ALL
+APPNAME := casample
 OBJ_DIR := ./bin
 VERSION_MAJOR := 0
 VERSION_MINOR := 1
@@ -39,14 +40,14 @@ all:
 else ifeq ($(PLATFORM),arduinomega)
 $(info *********ArduinoMega Build!!**********)
 all:
-       sudo sh arduino/build.sh clean $(PLATFORM) $(TRANSPORT)
-       sudo sh arduino/build.sh make $(PLATFORM) $(TRANSPORT)
+       sudo sh arduino/build.sh clean $(PLATFORM) $(TRANSPORT) $(APPNAME)
+       sudo sh arduino/build.sh make $(PLATFORM) $(TRANSPORT) $(APPNAME)
 
 clean: 
-       sudo sh arduino/build.sh clean $(PLATFORM) $(TRANSPORT)
+       sudo sh arduino/build.sh clean $(PLATFORM) $(TRANSPORT) $(APPNAME)
 
 install:
-       sudo sh arduino/build.sh install $(PLATFORM) $(TRANSPORT)
+       sudo sh arduino/build.sh install $(PLATFORM) $(TRANSPORT) $(APPNAME)
        
 else
    $(info *********error**********)
diff --git a/resource/csdk/connectivity/build/arduino/Makefile b/resource/csdk/connectivity/build/arduino/Makefile
new file mode 100644 (file)
index 0000000..01b5ddd
--- /dev/null
@@ -0,0 +1,71 @@
+#
+# override with `make BUILD=debug`
+# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue`
+# TRANSPORT can be ETHERNET, WIFI, BT, BLE. Include Corresponding Transport during compilation. For Eg: `make PLATFORM=arduinomega TRANSPORT=BLE
+# default to release build
+# default to build for arduinomega
+# default to build for BLE Transport
+BUILD   := release
+PLATFORM := arduinomega
+TRANSPORT := BLE
+OBJ_DIR := ./bin
+APP_NAME := sample_main
+ARDUINO_PORT := ttyACM0
+
+include ./local.properties
+include ./$(PLATFORM).properties
+
+VPATH := $(SDIR_ARD_PLATFORM)
+
+#Include __ARDUINO_BLE__ flag for BLE Transport. Currently, BLE Sample APP is segregated with this MACRO
+ifeq ($(TRANSPORT),BLE)
+CFLAGS         := -Os -Wall -c -DTB_LOG -DOIC_ARDUINODUE -DINTERFACESAMPLE_ARDUINO -DARDUINO -DOIC_ARDUINODUE -D__ARDUINO__ -DWITH_ARDUINO -D__ARDUINO_BLE__ -DLE_ADAPTER
+else ifeq ($(TRANSPORT),WIFI)
+CFLAGS         := -Os -Wall -c -DTB_LOG -DOIC_ARDUINODUE -DINTERFACESAMPLE_ARDUINO -DARDUINO -DOIC_ARDUINODUE -D__ARDUINO__ -DWITH_ARDUINO -DWIFI_ADAPTER
+else
+CFLAGS         := -Os -Wall -c -DTB_LOG -DOIC_ARDUINODUE -DINTERFACESAMPLE_ARDUINO -DARDUINO -DOIC_ARDUINODUE -D__ARDUINO__ -DWITH_ARDUINO -DETHERNET_ADAPTER
+endif
+
+all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
+
+$(info *********PLATFORM_OBJS!!**********)
+core.a: $(PLATFORM_OBJS)
+       @cd $(OBJ_DIR) && $(AR) -x ../../../lib/libcoap-4.1.1/release/libcoap.a
+       $(AR) rcs $@ $(CORE_COBJ) $(CORE_CPPOBJ) $(PLATFORM_OBJS) $(OBJ_DIR)/*.o
+       $(RANLIB) $@
+
+prep_dirs:
+       -mkdir $(OBJ_DIR)
+
+%.c.o: %.c
+       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+%.o: %.c
+       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+%.o: %.cpp
+       $(CCPLUS) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+%.cpp.o: %.cpp
+       $(CCPLUS) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $@
+
+# core.a and $(APP_NAME).cpp.o are combined to generate $(APP_NAME).elf.
+# For Integration with Top Layer, we can link top layer with core.a
+$(APP_NAME).elf: $(APP_NAME).cpp.o core.a
+       $(CC) -w -Os -Wl,--gc-sections,--relax -mmcu=atmega2560 -o $@ $^ -L$(ARDUINO_DIR)/libraries -lm
+
+$(APP_NAME).hex: $(APP_NAME).elf
+       $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(APP_NAME).eep
+       $(AVR_OBJCOPY) -O ihex -R .eeprom $< $@
+
+install: all
+       $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(APP_NAME).hex:i
+
+
+.PHONY: clean
+clean:
+       @rm -f *.o *.d *.elf *.eep core.a *.hex *.bin *.map *-
+       @rm -rf $(OBJ_DIR)
+
+
+
diff --git a/resource/csdk/connectivity/build/arduino/README.txt b/resource/csdk/connectivity/build/arduino/README.txt
new file mode 100644 (file)
index 0000000..572df31
--- /dev/null
@@ -0,0 +1,35 @@
+Setting Wi-Fi SSID and Password for Arduino Wi-FI Shield
+=====================================
+PreCondition: In connectivity\src\wifi_adapter\arduino\cawifiadapterutils.cpp  
+Update the SSID and Password credentials before testing with Wi-Fi Shield
+char ssid[] = "";     //  your network SSID (name)
+char pass[] = "";  // your network password
+
+Compiling Interface APIs for ARDUINOMEGA:
+========================================
+PREREQ: Arduino MUST be installed in the machine where we compile
+1) Open the local.properties file and change the path for ARDUINO_DIR to your own arduino installation directory.
+2) Similarly change the path for ARDUINO_TOOLS_DIR to your arduino tools directory.
+NOTE: We have changed local.properties so that, this could be a generic location (/usr/share/arduino).
+So, this assumes arduino files to be installed in this location. If there's a change, we need to change accordingly in local.properties.
+
+3) Go to "connectivity\build\arduino" directory, Open Makefile and change ARDUINO_PORT according to connected PORT
+4) Go to "connectivity\build" directory. To build a specific TRANSPORT [ETHERNET,BLE,WIFI], use the following command :
+       sudo make PLATFORM=arduinomega TRANSPORT=<ETHERNET/BLE/WIFI>    
+
+Note: Prior to building for BLE Transport, following additional steps are required:
+-      Copy the directory "connectivity\src\bt_le_adapter\arduino\external\RBL_nRF8001" to "arduino-<x.x.x>/library" folder
+-      Download BLE library from internet and place it in "arduino-<x.x.x>/library" folder
+       
+       
+Flashing Interface APIs for ARDUINOMEGA:
+========================================       
+Precondition: Connect Arduino Mega Board to Linux PC. Open Arduino IDE and select corresponding connected PORT
+1) To Install, connect the ArduinoMega Board with corresponding Shields to Linux PC. 
+2) Perform sudo make install PLATFORM=arduinomega TRANSPORT=BLE    
+   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
diff --git a/resource/csdk/connectivity/build/arduino/arduinomega.properties b/resource/csdk/connectivity/build/arduino/arduinomega.properties
new file mode 100644 (file)
index 0000000..2389018
--- /dev/null
@@ -0,0 +1,126 @@
+#Source directories
+BASE_DIR = ../..
+SDIR_ARD_CORE1 = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
+SDIR_ARD_TIMED_ACTION = $(ARDUINO_DIR)/libraries/TimedAction
+SDIR_ARD_BASE1 = $(BASE_DIR)/common/src/
+SDIR_ARD_BASE2 = $(BASE_DIR)/samples/arduino/
+SDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+SDIR_ARD_CALOGIC = $(BASE_DIR)/src/
+SDIR_ARD_UTIL = $(BASE_DIR)/src/adapter_util/
+
+ifeq ($(TRANSPORT),ETHERNET)
+       SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet/src
+       SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility
+       SDIR_ARD_ETH1 = $(BASE_DIR)/src/ethernet_adapter/arduino/
+       SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE1):$(SDIR_ARD_TIME):$(SDIR_ARD_TIMED_ACTION):$(SDIR_ARD_BASE1):$(SDIR_ARD_BASE2):$(SDIR_ARD_SPI) \
+                                               $(SDIR_ARD_CALOGIC):$(SDIR_ARD_UTIL):$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL):$(SDIR_ARD_ETH1)
+else ifeq ($(TRANSPORT),WIFI)
+       SDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi/src
+       SDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/src/utility
+       SDIR_ARD_WIFI1 = $(BASE_DIR)/src/wifi_adapter/arduino/
+       SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE1):$(SDIR_ARD_TIME):$(SDIR_ARD_TIMED_ACTION):$(SDIR_ARD_BASE1):$(SDIR_ARD_BASE2):$(SDIR_ARD_SPI) \
+                                               $(SDIR_ARD_CALOGIC):$(SDIR_ARD_UTIL):$(SDIR_ARD_WIFI):$(SDIR_ARD_WIFI_UTIL):$(SDIR_ARD_WIFI1)
+else ifeq ($(TRANSPORT),BLE)
+       SDIR_ARD_BLE = $(ARDUINO_DIR)/libraries/BLE
+       SDIR_ARD_RBL = $(ARDUINO_DIR)/libraries/RBL_nRF8001
+       SDIR_ARD_BLE1 = $(BASE_DIR)/src/bt_le_adapter/arduino/
+       SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE1):$(SDIR_ARD_TIME):$(SDIR_ARD_TIMED_ACTION):$(SDIR_ARD_BASE1):$(SDIR_ARD_BASE2):$(SDIR_ARD_SPI) \
+                                               $(SDIR_ARD_CALOGIC):$(SDIR_ARD_UTIL):$(SDIR_ARD_BLE):$(SDIR_ARD_RBL):$(SDIR_ARD_BLE1)
+else
+   $(info *********error**********)
+   $(error Wrong value for TRANSPORT !!)
+endif
+
+#include directories
+IDIR_ARD_CORE1 = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+IDIR_ARD_CORE2 = $(ARDUINO_DIR)/hardware/tools/avr/avr/include/
+IDIR_ARD_CORE3 = $(ARDUINO_DIR)/hardware/arduino/avr/variants/mega
+INCD_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
+INCD_ARD_TIMED_ACTION = $(ARDUINO_DIR)/libraries/TimedAction
+IDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+INCD_ARD_BASE1 = $(BASE_DIR)/inc/
+INCD_ARD_BASE2 = $(BASE_DIR)/common/inc/
+INCD_ARD_BASE3 = $(BASE_DIR)/api/
+INCD_ARD_BASE4 = $(BASE_DIR)/lib/libcoap-4.1.1/
+#ntohs and htons are defined in util.h in the below path
+IDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility
+
+ifeq ($(TRANSPORT),ETHERNET)
+       IDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet/src
+       IDIR_ARD_ETH1 = $(BASE_DIR)/src/ethernet_adapter/arduino/
+       INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE1) -I$(IDIR_ARD_CORE2) -I$(IDIR_ARD_CORE3) \
+                                               -I$(INCD_ARD_TIME) -I$(INCD_ARD_TIMED_ACTION) \
+                                               -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) 
+else ifeq ($(TRANSPORT),WIFI)
+       IDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi/src
+       IDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/src/utility
+       IDIR_ARD_WIFI1 = $(BASE_DIR)/src/wifi_adapter/arduino/
+       INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE1) -I$(IDIR_ARD_CORE2) -I$(IDIR_ARD_CORE3) \
+                                       -I$(INCD_ARD_TIME) -I$(INCD_ARD_TIMED_ACTION) \
+                                       -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) -I$(IDIR_ARD_WIFI1) 
+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/
+       INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE1) -I$(IDIR_ARD_CORE2) -I$(IDIR_ARD_CORE3) \
+                                               -I$(INCD_ARD_TIME) -I$(INCD_ARD_TIMED_ACTION) \
+                                               -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_BLE) \
+                                               -I$(IDIR_ARD_RBL) -I$(INCD_ARD_BLE1)
+else
+   $(info *********error**********)
+   $(error Wrong value for TRANSPORT !!)
+endif
+
+#Compiler/Linker flags
+CFLAGS_PLATFORM =  -mmcu=atmega2560 -DF_CPU=16000000L -fno-exceptions -ffunction-sections -fdata-sections -MMD -DARDUINO=157 -DARDUINO_ARCH_AVR \
+                       -DARDUINO_AVR_ADK
+
+#Compilers
+$(info ************ arduinoMEGA file*****************)
+
+CCPLUS=$(ARDUINO_TOOLS_DIR)/avr-g++
+CC=$(ARDUINO_TOOLS_DIR)/avr-gcc
+AR=$(ARDUINO_TOOLS_DIR)/avr-ar
+RANLIB=$(ARDUINO_TOOLS_DIR)/avr-ranlib
+AVR_OBJCOPY=$(ARDUINO_TOOLS_DIR)/avr-objcopy
+AVR_PROGRAMMER=$(ARDUINO_TOOLS_DIR)/avrdude
+
+#Objects
+CORE_COBJ = hooks.c.o WInterrupts.c.o wiring.c.o wiring_digital.c.o wiring_analog.c.o wiring_shift.c.o wiring_pulse.c.o
+CORE_CPPOBJ = CDC.cpp.o HardwareSerial.cpp.o HardwareSerial0.cpp.o HardwareSerial1.cpp.o HardwareSerial2.cpp.o HardwareSerial3.cpp.o IPAddress.cpp.o HID.cpp.o \
+              main.cpp.o new.cpp.o Print.cpp.o Stream.cpp.o Tone.cpp.o USBCore.cpp.o WMath.cpp.o WString.cpp.o
+SPI_OBJ = SPI.cpp.o
+TIMED_OBJ = TimedAction.cpp.o
+LOGGER_OBJ = logger.cpp.o oic_logger.c.o oic_console_logger.c.o oic_malloc.c.o uarraylist.c.o
+UTIL_OBJ = caadapterutils.c.o
+CACOMMON_OBJ = caconnectivitymanager_singlethread.c.o cainterfacecontroller_singlethread.c.o camessagehandler_singlethread.c.o canetworkconfigurator_singlethread.c.o caprotocolmessage.c.o \
+                          caremotehandler.c.o 
+
+ifeq ($(TRANSPORT),ETHERNET)
+       ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o EthernetClient.o
+       ETH_UTIL_CPPOBJ = socket.o w5100.o
+       INTERFACE_OBJ = caethernetadapterutils.cpp.o caethernetadapter.c.o
+       PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(TIMED_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_UTIL_CPPOBJ = server_drv.cpp.o spi_drv.cpp.o wifi_drv.cpp.o
+       INTERFACE_OBJ = cawifiadapterutils.cpp.o cawifiadapter.c.o
+       PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(TIMED_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(WIFI_CPPOBJ) $(WIFI_UTIL_CPPOBJ) $(UTIL_OBJ) $(CACOMMON_OBJ)
+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.cpp.o caleserver.cpp.o 
+       PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(SPI_OBJ) $(TIMED_OBJ) $(LOGGER_OBJ) $(INTERFACE_OBJ) $(BLE_OBJ) $(RBL_OBJ) $(CACOMMON_OBJ)
+else
+   $(info *********error**********)
+   $(error Wrong value for TRANSPORT !!)
+endif
diff --git a/resource/csdk/connectivity/build/arduino/build.sh b/resource/csdk/connectivity/build/arduino/build.sh
new file mode 100644 (file)
index 0000000..2c23bfe
--- /dev/null
@@ -0,0 +1,13 @@
+#!/bin/sh
+if echo $1 | grep -q -i "make"
+then
+cd ../lib/libcoap-4.1.1/
+sudo make -f makefile_arduino.mak PLATFORM=$2
+cd ../../build/arduino
+sudo make PLATFORM=$2 TRANSPORT=$3 APP_NAME=$4
+else
+cd ../lib/libcoap-4.1.1/
+sudo make $1 -f makefile_arduino.mak PLATFORM=$2
+cd ../../build/arduino/
+sudo make $1 PLATFORM=$2 TRANSPORT=$3 APP_NAME=$4
+fi
\ No newline at end of file
diff --git a/resource/csdk/connectivity/build/arduino/local.properties b/resource/csdk/connectivity/build/arduino/local.properties
new file mode 100644 (file)
index 0000000..e318153
--- /dev/null
@@ -0,0 +1,2 @@
+ARDUINO_DIR = /usr/share/arduino
+ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
index bdc96c3..7f62225 100644 (file)
@@ -42,9 +42,10 @@ ETHERNET = ETHERNET_ADAPTER
 
 #Add Pre processor definitions
 DEFINE_FLAG = -D$(EDR) -D$(LE) -D$(WIFI) -D$(ETHERNET)
-
+#Add For memory checking
+#DEBUG_FLAG = -DENABLE_MALLOC_DEBUG
 #Add Debug flags here
-DEBUG_FLAG = -DTB_LOG
+DEBUG_FLAG += -DTB_LOG
 
 ##
 ##     definitions
@@ -120,8 +121,8 @@ vpath %.c $(BLE_ADAPTER_PATH)
 vpath %.c $(PROJECT_SRC_PATH)
 
 $(OBJ_DIR)/%.o: %.c
-       @$(MAKE_OBJ_PATH)
-       @$(CC) -o $@ $(CFLAGS) $(DFLAGS) $(IFLAGS) $<
+       $(MAKE_OBJ_PATH)
+       $(CC) -o $@ $(CFLAGS) $(DFLAGS) $(IFLAGS) $<
 
 all : $(TARGET)
        @echo   " "
index b7c2f04..59fffd1 100644 (file)
@@ -18,8 +18,8 @@ LIBCOAP=./lib/libcoap-4.1.1/
 LIBCOAP_OBJ_DIR=./lib/libcoap-4.1.1/obj
 
 # TODO : Currently Hardcoded WIFI_ADAPTER. Change it to generic
-CFLAGS.debug = -DWITH_POSIX -D__TIZEN__ -Wall -DSLP_SDK_LOG -g  -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
-CFLAGS.release = -DWITH_POSIX -D__TIZEN__ -Wall -DSLP_SDK_LOG  -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
+CFLAGS.debug = -DWITH_POSIX -D__TIZEN__ -Wall -std=c99 -DSLP_SDK_LOG -g -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
+CFLAGS.release = -DWITH_POSIX -D__TIZEN__ -Wall -std=c99 -DSLP_SDK_LOG -D_GNU_SOURCE -DTIZEN_DEBUG_ENABLE -DTB_LOG $(ADAPTER_MACRO)
 COMPILEFLAG = `pkg-config --cflags --libs capi-network-wifi dlog capi-network-bluetooth glib-2.0`
 
 # Include files will be copied into a single folder on gbsbuild.
index c09c76f..c4b6efa 100644 (file)
@@ -66,11 +66,10 @@ typedef enum
 #define FATAL DLOG_ERROR
 #endif
 
-#ifndef ARDUINO
 #ifdef __TIZEN__
 #define OICLog(level,tag,mes) LOG(level,tag,mes)
 #define OICLogv(level,tag,fmt,args...) LOG(level,tag,fmt,##args)
-#else
+#elif defined(ANDROID) || defined(__linux__)
 /**
  * Configure logger to use a context that defines a custom logger function
  *
@@ -98,7 +97,7 @@ void OICLogShutdown();
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLog(LogLevel level, const char * tag, const char * logStr);
+void OICLog(LogLevel level, const char *tag, const char *logStr);
 
 /**
  * Output a variable argument list log string with the specified priority level.
@@ -108,7 +107,7 @@ void OICLog(LogLevel level, const char * tag, const char * logStr);
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, const char * tag, const char * format, ...);
+void OICLogv(LogLevel level, const char *tag, const char *format, ...);
 
 /**
  * Output the contents of the specified buffer (in hex) with the specified priority level.
@@ -118,9 +117,8 @@ void OICLogv(LogLevel level, const char * tag, const char * format, ...);
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OICLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize);
-#endif //__TIZEN__
-#else
+void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize);
+#else  // For arduino platforms
 /**
  * Initialize the serial logger for Arduino
  * Only defined for Arduino
@@ -135,7 +133,7 @@ void OICLogInit();
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr);
+void OICLog(LogLevel level, const char *tag, const int16_t lineNum, const char *logStr);
 
 /**
  * Output the contents of the specified buffer (in hex) with the specified priority level.
@@ -145,7 +143,7 @@ void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logSt
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize);
+void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize);
 
 /**
  * Output a variable argument list log string with the specified priority level.
@@ -154,7 +152,7 @@ void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buff
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, const char * tag, const char * format, ...);
+void OICLogv(LogLevel level, const char *tag, const int16_t lineNum, const char *format, ...);
 #endif
 
 #ifdef TB_LOG
@@ -164,23 +162,20 @@ void OICLogv(LogLevel level, const char * tag, const char * format, ...);
 #define OIC_LOG_V(level,tag,fmt,args...) LOG_(LOG_ID_MAIN, level, tag, fmt,##args)
 #else // These macros are defined for Linux, Android, and Arduino
 #define OIC_LOG_INIT()    OICLogInit()
-#define OIC_LOG(level, tag, logStr)  OICLog((level), (tag), (logStr))
 #define OIC_LOG_BUFFER(level, tag, buffer, bufferSize)  OICLogBuffer((level), (tag), (buffer), (bufferSize))
+
 #ifdef ARDUINO
 #define OIC_LOG_CONFIG(ctx)
 #define OIC_LOG_SHUTDOWN()
-// Use full namespace for logInit to avoid function name collision
-#define OIC_LOG_INIT()    OICLogInit()
-// Don't define variable argument log function for Arduino
-#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__)
+#define OIC_LOG(level, tag, logStr)  OICLog((level), (tag), __LINE__, (logStr))
+#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __LINE__, __VA_ARGS__)
 #else
 #define OIC_LOG_CONFIG(ctx)    OICLogConfig((ctx))
 #define OIC_LOG_SHUTDOWN()     OICLogShutdown()
-// Define variable argument log function for Linux and Android
-#define OIC_LOG_V(level, tag, ...)  OICLogv((level), (tag), __VA_ARGS__)
+#define OIC_LOG(level, tag, logStr)  OICLog((level), (tag), (logStr))
+#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__)
 #endif //ARDUINO
 #endif //__TIZEN__
-
 #else //TB_LOG
 
 #define OIC_LOG_CONFIG(ctx)
index b26734e..386ea09 100644 (file)
@@ -54,7 +54,7 @@ u_arraylist_t* u_arraylist_create();
 /**
  * @brief Resets and deletes the array list
  * application should free the memory of data in array list
- * @param u_arraylist_t- u_arraylist pointer
+ * @param list- u_arraylist pointer
  * @return CAResult_t
  * CA_STATUS_OK if Success, CA_STATUS_FAILED otherwise
  */
@@ -62,7 +62,7 @@ CAResult_t u_arraylist_free(u_arraylist_t *list);
 
 /**
  * @brief Returns the data of the index from the array list
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @param index
  *     [IN] index of array list
@@ -72,7 +72,7 @@ void* u_arraylist_get(const u_arraylist_t *list, uint32_t index);
 
 /**
  * @brief Add data in the array list
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @param data
  *     [IN] pointer of data
@@ -83,7 +83,7 @@ CAResult_t u_arraylist_add(u_arraylist_t *list, void *data);
 
 /**
  * @brief Remove the data of the index from the array list
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @param index
  *     [IN] index of array list
@@ -93,7 +93,7 @@ void* u_arraylist_remove(u_arraylist_t *list, uint32_t index);
 
 /**
  * @brief Returns the length of the array list
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @return length of the array list
  */
@@ -101,7 +101,7 @@ uint32_t u_arraylist_length(const u_arraylist_t *list);
 
 /**
  * @brief Returns whether the data exists or not
- * @param u_arraylist
+ * @param list
  *     [IN] pointer of array list
  * @param data
  *     [IN] pointer of data
index 30f8336..6c222a9 100644 (file)
@@ -131,7 +131,7 @@ void u_cond_wait(u_cond cond, u_mutex mutex);
  * @fn  u_cond_free
  * @brief  Free the condition
  *
- * @param  mutex  The condition to be freed
+ * @param  cond  The condition to be freed
  *
  */
 void u_cond_free(u_cond cond);
index 908c400..28c34d7 100644 (file)
@@ -69,7 +69,7 @@ CAResult_t u_thread_pool_init(uint32_t num_of_threads, u_thread_pool_t *thread_p
 /**
  * This function adds a routine to be executed by the thread pool at some future time.
  *
- * @param pool The thread pool structure.
+ * @param thread_pool The thread pool structure.
  * @param routine The routine to be executed.
  * @param data The data to be passed to the routine.
  *
@@ -82,7 +82,7 @@ CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(v
  * This function stops all the worker threads (stop & exit). And frees all the allocated memory.
  * Function will return only after joining all threads executing the currently scheduled tasks.
  *
- * @param pool The thread pool structure.
+ * @param thread_pool The thread pool structure.
  */
 void u_thread_pool_free(u_thread_pool_t thread_pool);
 
index be4bcae..be92eea 100644 (file)
 #include "string.h"
 #include "oic_logger.h"
 #include "oic_console_logger.h"
+#ifdef ARDUINO
+#include "Arduino.h"
+#include <avr/pgmspace.h>
+#endif
 
 static oic_log_ctx_t *logCtx = 0;
 
 static oic_log_level LEVEL_XTABLE[] =
 { OIC_LOG_DEBUG, OIC_LOG_INFO, OIC_LOG_WARNING, OIC_LOG_ERROR, OIC_LOG_FATAL };
 
-static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 +
+        1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
 
 // Convert LogLevel to platform-specific severity level.  Store in PROGMEM on Arduino
 #ifdef __ANDROID__
+#ifdef ADB_SHELL
+static const char * LEVEL[] =
+{   "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+
+#else
 static android_LogPriority LEVEL[] =
 {   ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
+#endif
 #elif defined __linux__
-static const char * LEVEL[] __attribute__ ((unused)) =
+static const char *LEVEL[] __attribute__ ((unused)) =
 {   "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
 #elif defined ARDUINO
 #include <stdarg.h>
@@ -46,10 +57,10 @@ PROGMEM const char level2[] = "WARNING";
 PROGMEM const char level3[] = "ERROR";
 PROGMEM const char level4[] = "FATAL";
 
-PROGMEM const char * const LEVEL[] =
+PROGMEM const char *const LEVEL[] =
 {   level0, level1, level2, level3, level4};
 
-static void OICLogString(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr);
+static void OICLogString(LogLevel level, PROGMEM const char *tag, PROGMEM const char *logStr);
 #ifdef ARDUINO_ARCH_AVR
 //Mega2560 and other 8-bit AVR microcontrollers
 #define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_word(addr));}
@@ -91,7 +102,7 @@ void OICLogShutdown()
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLog(LogLevel level, const char * tag, const char * logStr)
+void OICLog(LogLevel level, const char *tag, const char *logStr)
 {
     if (!logStr || !tag)
     {
@@ -99,7 +110,13 @@ void OICLog(LogLevel level, const char * tag, const char * logStr)
     }
 
 #ifdef __ANDROID__
+
+#ifdef ADB_SHELL
+    printf("%s: %s: %s\n", LEVEL[level], tag, logStr);
+#else
     __android_log_write(LEVEL[level], tag, logStr);
+#endif
+
 #elif defined __linux__
     if (logCtx && logCtx->write_level)
     {
@@ -121,7 +138,7 @@ void OICLog(LogLevel level, const char * tag, const char * logStr)
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, const char * tag, const char * format, ...)
+void OICLogv(LogLevel level, const char *tag, const char *format, ...)
 {
     if (!format || !tag)
     {
@@ -144,7 +161,7 @@ void OICLogv(LogLevel level, const char * tag, const char * format, ...)
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OICLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize)
+void OICLogBuffer(LogLevel level, const char *tag, const uint8_t *buffer, uint16_t bufferSize)
 {
     if (!buffer || !tag || (bufferSize == 0))
     {
@@ -193,7 +210,7 @@ void OICLogInit()
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLogString(LogLevel level, PROGMEM const char * tag, const char * logStr)
+void OICLogString(LogLevel level, PROGMEM const char *tag, const char *logStr)
 {
     if (!logStr || !tag)
     {
@@ -225,7 +242,8 @@ void OICLogString(LogLevel level, PROGMEM const char * tag, const char * logStr)
  * @param buffer     - pointer to buffer of bytes
  * @param bufferSize - max number of byte in buffer
  */
-void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize)
+void OICLogBuffer(LogLevel level, PROGMEM const char *tag, const uint8_t *buffer,
+                  uint16_t bufferSize)
 {
     if (!buffer || !tag || (bufferSize == 0))
     {
@@ -240,7 +258,7 @@ void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buff
         // Format the buffer data into a line
         sprintf(&lineBuffer[lineIndex++ * 3], "%02X ", buffer[i]);
         // Output 16 values per line
-        if (((i+1)%16) == 0)
+        if (((i + 1) % 16) == 0)
         {
             OICLogString(level, tag, lineBuffer);
             memset(lineBuffer, 0, sizeof lineBuffer);
@@ -262,7 +280,7 @@ void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buff
  * @param tag    - Module name
  * @param logStr - log string
  */
-void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr)
+void OICLog(LogLevel level, PROGMEM const char *tag, PROGMEM const char *logStr)
 {
     if (!logStr || !tag)
     {
@@ -299,7 +317,7 @@ void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logSt
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, PROGMEM const char * tag, const char * format, ...)
+void OICLogv(LogLevel level, PROGMEM const char *tag, const char *format, ...)
 {
     char buffer[LINE_BUFFER_SIZE];
     va_list ap;
@@ -319,9 +337,9 @@ void OICLogv(LogLevel level, PROGMEM const char * tag, const char * format, ...)
     Serial.print(F(": "));
 
     vsnprintf(buffer, sizeof(buffer), format, ap);
-    for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines
+    for (char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines
     {
-        if(*p == '\n')
+        if (*p == '\n')
         {
             Serial.write('\r');
         }
@@ -338,7 +356,7 @@ void OICLogv(LogLevel level, PROGMEM const char * tag, const char * format, ...)
  * @param tag    - Module name
  * @param format - variadic log string
  */
-void OICLogv(LogLevel level, PROGMEM const char * tag, const __FlashStringHelper *format, ...)
+void OICLogv(LogLevel level, PROGMEM const char *tag, const __FlashStringHelper *format, ...)
 {
     char buffer[LINE_BUFFER_SIZE];
     va_list ap;
@@ -362,9 +380,9 @@ void OICLogv(LogLevel level, PROGMEM const char * tag, const __FlashStringHelper
 #else
     vsnprintf(buffer, sizeof(buffer), (const char *)format, ap); // for the rest of the world
 #endif
-    for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines
+    for (char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines
     {
-        if(*p == '\n')
+        if (*p == '\n')
         {
             Serial.write('\r');
         }
diff --git a/resource/csdk/connectivity/common/src/logger.cpp b/resource/csdk/connectivity/common/src/logger.cpp
new file mode 100644 (file)
index 0000000..9af46e2
--- /dev/null
@@ -0,0 +1,359 @@
+//******************************************************************
+//
+// Copyright 2014 Intel Mobile Communications GmbH 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 "logger.h"
+#include "string.h"
+
+static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 +
+        1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination
+
+// Convert LogLevel to platform-specific severity level.  Store in PROGMEM on Arduino
+#ifdef __ANDROID__
+static android_LogPriority LEVEL[] =
+{   ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL};
+
+#elif defined __linux__
+#include <dlog/dlog.h>
+#define LOG_TAG "CA"
+#define FONT_COLOR_RESET    "\033[0m"
+#define FONT_COLOR_RED      "\033[31m"
+#define FONT_COLOR_YELLOW   "\033[33m"
+#define FONT_COLOR_GREEN    "\033[32m"
+
+//#elif defined __linux__
+static const char *LEVEL[] =
+{   "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+static const char *LEVEL[] __attribute__((unused)) =
+{   "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"};
+#elif defined ARDUINO
+#include <stdarg.h>
+#include "Arduino.h"
+
+PROGMEM const char level0[] = "DEBUG";
+PROGMEM const char level1[] = "INFO";
+PROGMEM const char level2[] = "WARNING";
+PROGMEM const char level3[] = "ERROR";
+PROGMEM const char level4[] = "FATAL";
+
+PROGMEM const char LEVEL[] = "DIWEF";
+
+//    static void OCLogString(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr);
+#endif
+
+#if defined(__ANDROID__) || defined(__linux__) || defined(__TIZEN__)
+/**
+ * Output a variable argument list log string with the specified priority level.
+ * Only defined for Linux and Android
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param format - variadic log string
+ */
+void OICLogv(LogLevel level, const char *tag, const char *format, ...)
+{
+    if (!format || !tag)
+    {
+        return;
+    }
+    char buffer[MAX_LOG_V_BUFFER_SIZE];
+    memset(buffer, 0, sizeof buffer);
+    va_list args;
+    va_start(args, format);
+    vsnprintf(buffer, sizeof buffer - 1, format, args);
+    va_end(args);
+    OICLog(level, tag, buffer);
+}
+
+/**
+ * Output a log string with the specified priority level.
+ * Only defined for Linux and Android
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param logStr - log string
+ */
+void OICLog(LogLevel level, const char *tag, const char *logStr)
+{
+    if (!logStr || !tag)
+    {
+        return;
+    }
+
+#ifdef __ANDROID__
+    __android_log_write(LEVEL[level], tag, logStr);
+#else //#elif __TIZEN__
+    LOGD(logStr);
+    /*#ifdef LOG_TAG
+ #undef LOG_TAG
+ #define LOG_TAG tag
+ #endif
+    if(level == DEBUG || level == INFO){
+        LOGD(logStr);
+    }else if(level == WARNING){
+        LOGW(logStr);
+    }else if(level == ERROR || level == FATAL){
+        LOGE(logStr);
+    }*/
+    //#elif defined __linux__
+    printf("%s: %s: %s\n", LEVEL[level], tag, logStr);
+#endif
+}
+
+/**
+ * Output the contents of the specified buffer (in hex) with the specified priority level.
+ *
+ * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag        - Module name
+ * @param buffer     - pointer to buffer of bytes
+ * @param bufferSize - max number of byte in buffer
+ */
+/*
+ void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize) {
+ if (!buffer || !tag || (bufferSize == 0)) {
+ return;
+ }
+
+ char lineBuffer[LINE_BUFFER_SIZE];
+ memset(lineBuffer, 0, sizeof lineBuffer);
+ int lineIndex = 0;
+ int i;
+ for (i = 0; i < bufferSize; i++) {
+ // Format the buffer data into a line
+ sprintf(&lineBuffer[lineIndex++ * 3], "%02X ", buffer[i]);
+ // Output 16 values per line
+ if (((i+1)%16) == 0) {
+ OCLog(level, tag, lineBuffer);
+ memset(lineBuffer, 0, sizeof lineBuffer);
+ lineIndex = 0;
+ }
+ }
+ // Output last values in the line, if any
+ if (bufferSize % 16) {
+ OCLog(level, tag, lineBuffer);
+ }
+ }
+ */
+
+#endif
+
+#ifdef ARDUINO
+/**
+ * Initialize the serial logger for Arduino
+ * Only defined for Arduino
+ */
+void OICLogInit()
+{
+    Serial.begin(115200);
+}
+
+/**
+ * Output a log string with the specified priority level.
+ * Only defined for Arduino.  Only uses PROGMEM strings
+ * for the tag parameter
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param logStr - log string
+ */
+/*
+ void OCLogString(LogLevel level, PROGMEM const char * tag, const char * logStr) {
+ if (!logStr || !tag) {
+ return;
+ }
+
+ char buffer[LINE_BUFFER_SIZE] = {0};
+ strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
+ Serial.print(buffer);
+
+ char c;
+ Serial.print(F(": "));
+ while ((c = pgm_read_byte(tag))) {
+ Serial.write(c);
+ tag++;
+ }
+ Serial.print(F(": "));
+
+ Serial.println(logStr);
+ }
+ */
+/**
+ * Output the contents of the specified buffer (in hex) with the specified priority level.
+ *
+ * @param level      - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag        - Module name
+ * @param buffer     - pointer to buffer of bytes
+ * @param bufferSize - max number of byte in buffer
+ */
+
+/*
+ void OCLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize) {
+ if (!buffer || !tag || (bufferSize == 0)) {
+ return;
+ }
+
+ char lineBuffer[LINE_BUFFER_SIZE] = {0};
+ uint8_t lineIndex = 0;
+ for (uint8_t i = 0; i < bufferSize; i++) {
+ // Format the buffer data into a line
+ sprintf(&lineBuffer[lineIndex++ * 3], "%02X ", buffer[i]);
+ // Output 16 values per line
+ if (((i+1)%16) == 0) {
+ OCLogString(level, tag, lineBuffer);
+ memset(lineBuffer, 0, sizeof lineBuffer);
+ lineIndex = 0;
+ }
+ }
+ // Output last values in the line, if any
+ if (bufferSize % 16) {
+ OCLogString(level, tag, lineBuffer);
+ }
+ }
+ */
+/**
+ * Output a log string with the specified priority level.
+ * Only defined for Arduino.  Uses PROGMEM strings
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param logStr - log string
+ */
+void OICLog(LogLevel level, const char *tag, const int16_t lineNum, const char *logStr)
+{
+    if (!logStr || !tag)
+    {
+        return;
+    }
+
+    //char buffer[LINE_BUFFER_SIZE] = {0};
+    //strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
+    //Serial.print(buffer);
+    Serial.print(LEVEL[level]);
+
+    //char c;
+    Serial.print(F(": "));
+    /* while ((c = pgm_read_byte(tag))) {
+     Serial.write(c);
+     tag++;
+     } */
+    Serial.print(tag);
+    Serial.print(F(": "));
+    Serial.print(lineNum);
+    Serial.print(F(": "));
+    /* while ((c = pgm_read_byte(logStr))) {
+     Serial.write(c);
+     logStr++;
+     } */
+
+    Serial.print(logStr);
+
+    Serial.println();
+}
+
+/**
+ * Output a variable argument list log string with the specified priority level.
+ * Only defined for Arduino as depicted below.
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param format - variadic log string
+ */
+void OICLogv(LogLevel level, const char *tag, const int16_t lineNum, const char *format, ...)
+{
+    char buffer[LINE_BUFFER_SIZE];
+    va_list ap;
+    va_start(ap, format);
+    //strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
+    //Serial.print(buffer);
+
+    Serial.print(LEVEL[level]);
+    //char c;
+    Serial.print(F(": "));
+    /*while ((c = pgm_read_byte(tag))) {
+     Serial.write(c);
+     tag++;
+     }*/
+    Serial.print(tag);
+    Serial.print(F(": "));
+    Serial.print(lineNum);
+    Serial.print(F(": "));
+    vsnprintf(buffer, sizeof(buffer), format, ap);
+    for (char *p = &buffer[0]; *p; p++)
+    {
+        // emulate cooked mode for newlines
+        if (*p == '\n')
+        {
+            //Serial.write('\r');
+            Serial.print('\r');
+        }
+        //Serial.write(*p);
+        Serial.print(*p);
+    }
+    Serial.println();
+    va_end(ap);
+}
+/**
+ * Output a variable argument list log string with the specified priority level.
+ * Only defined for Arduino as depicted below.
+ *
+ * @param level  - DEBUG, INFO, WARNING, ERROR, FATAL
+ * @param tag    - Module name
+ * @param format - variadic log string
+ */
+void OICLogv(LogLevel level, const char *tag, const __FlashStringHelper *format, ...)
+{
+    Serial.print("OCLOGV : ");
+    char buffer[LINE_BUFFER_SIZE];
+    va_list ap;
+    va_start(ap, format);
+    // strcpy_P(buffer, (char*)pgm_read_word(&(LEVEL[level])));
+    // Serial.print(buffer);
+
+    Serial.print(LEVEL[level]);
+    // char c;
+    Serial.print(F(": "));
+
+    /*while ((c = pgm_read_byte(tag))) {
+     Serial.write(c);
+     tag++;
+     }*/
+    Serial.print(tag);
+    Serial.print(F(": "));
+
+#ifdef __AVR__
+    vsnprintf_P(buffer, sizeof(buffer), (const char *)format, ap); // progmem for AVR
+#else
+    vsnprintf(buffer, sizeof(buffer), (const char *)format, ap); // for the rest of the world
+#endif
+    for (char *p = &buffer[0]; *p; p++)
+    {
+        // emulate cooked mode for newlines
+        if (*p == '\n')
+        {
+            // Serial.write('\r');
+            Serial.print('\r');
+        }
+        //Serial.write(*p);
+        Serial.print(p);
+    }
+    Serial.println();
+    va_end(ap);
+}
+#endif
+
index 8136c97..ab9e52e 100644 (file)
 #include "oic_malloc.h"
 
 // Enable extra debug logging for malloc.  Comment out to disable
-//#define ENABLE_MALLOC_DEBUG  (1)
-
 #ifdef ENABLE_MALLOC_DEBUG
 #include "logger.h"
-#define TAG PCF("OICMalloc")
+#define TAG "OICMalloc"
 #endif
 
 //-----------------------------------------------------------------------------
@@ -55,6 +53,9 @@
 //-----------------------------------------------------------------------------
 // Public APIs
 //-----------------------------------------------------------------------------
+#ifdef ENABLE_MALLOC_DEBUG
+static uint32_t count;
+#endif
 
 void *OICMalloc(size_t size)
 {
@@ -67,7 +68,8 @@ void *OICMalloc(size_t size)
     }
 
     ptr = malloc(size);
-    OIC_LOG_V(INFO, TAG, "malloc: ptr=%p, size=%u", ptr, size);
+    count++;
+    OIC_LOG_V(INFO, TAG, "malloc: ptr=%p, size=%u, count=%u", ptr, size, count);
     return ptr;
 #else
     if (0 == size)
@@ -81,7 +83,7 @@ void *OICMalloc(size_t size)
 void OICFree(void *ptr)
 {
 #ifdef ENABLE_MALLOC_DEBUG
-    OIC_LOG_V(INFO, TAG, "free: ptr=%p", ptr);
+    OIC_LOG_V(INFO, TAG, "free: ptr=%p, count=%u", ptr, --count);
 #endif
 
     free(ptr);
index a618e51..ae6fbc3 100644 (file)
 #include "logger.h"
 #include "oic_malloc.h"
 
-#define TAG PCF("UARRAYLIST")
+#define TAG "UARRAYLIST"
 
 u_arraylist_t *u_arraylist_create()
 {
     u_arraylist_t *list = NULL;
 
-    if (!(list = (u_arraylist_t*) OICMalloc(sizeof(u_arraylist_t))))
+    if (!(list = (u_arraylist_t *) OICMalloc(sizeof(u_arraylist_t))))
     {
         return NULL;
     }
@@ -40,10 +40,10 @@ u_arraylist_t *u_arraylist_create()
 
     if (!(list->data = (void*) OICMalloc(list->size * sizeof(void*))))
     {
+        OIC_LOG_V(DEBUG, TAG, "Out of memory");
         OICFree(list);
         return NULL;
     }
-
     return list;
 }
 
index 6575453..93cfef0 100644 (file)
 #include <glib.h>
 
 #include "logger.h"
+
+/**
+ * @def TAG
+ * @brief Logging tag for module name
+ */
 #define TAG PCF("UMUTEX")
 
 void u_mutex_init(void)
@@ -51,11 +56,11 @@ void u_mutex_lock(u_mutex mutex)
 {
     if (NULL == mutex)
     {
-        OIC_LOG_V(ERROR, TAG ,"Invalid mutex !");
+        OIC_LOG_V(ERROR, TAG ,"u_mutex_lock, Invalid mutex !");
         return;
     }
 
-    GMutex *mutexLock = (GMutex*) mutex;
+    GMutex *mutexLock = (GMutex *) mutex;
     g_mutex_lock(mutexLock);
 }
 
@@ -63,11 +68,11 @@ CABool_t u_mutex_trylock(u_mutex mutex)
 {
     if (NULL == mutex)
     {
-        OIC_LOG_V(ERROR, TAG,"Invalid mutex !");
+        OIC_LOG_V(ERROR, TAG,"u_mutex_trylock, Invalid mutex !");
         return CA_FALSE;
     }
 
-    GMutex *mutexLock = (GMutex*) mutex;
+    GMutex *mutexLock = (GMutex *) mutex;
     gboolean ret = g_mutex_trylock(mutexLock);
     if (TRUE == ret)
     {
@@ -81,11 +86,11 @@ void u_mutex_unlock(u_mutex mutex)
 {
     if (NULL == mutex)
     {
-        OIC_LOG_V(ERROR, TAG,"Invalid mutex !");
+        OIC_LOG_V(ERROR, TAG,"u_mutex_unlock, Invalid mutex !");
         return;
     }
 
-    GMutex *mutexLock = (GMutex*) mutex;
+    GMutex *mutexLock = (GMutex *) mutex;
     g_mutex_unlock(mutexLock);
 }
 
@@ -93,11 +98,11 @@ void u_mutex_free(u_mutex mutex)
 {
     if (NULL == mutex)
     {
-        OIC_LOG_V(ERROR, TAG,"Invalid mutex !");
+        OIC_LOG_V(ERROR, TAG,"u_mutex_free, Invalid mutex !");
         return;
     }
 
-    GMutex *mutexLock = (GMutex*) mutex;
+    GMutex *mutexLock = (GMutex *) mutex;
     g_mutex_free(mutexLock);
 }
 
@@ -116,11 +121,11 @@ void u_cond_signal(u_cond cond)
 {
     if (NULL == cond)
     {
-        OIC_LOG_V(ERROR, TAG,"Invalid condition !");
+        OIC_LOG_V(ERROR, TAG,"u_cond_signal, Invalid condition !");
         return;
     }
 
-    GCond *condition = (GCond*) cond;
+    GCond *condition = (GCond *) cond;
     g_cond_signal(condition);
 }
 
@@ -128,11 +133,11 @@ void u_cond_broadcast(u_cond cond)
 {
     if (NULL == cond)
     {
-        OIC_LOG_V(ERROR, TAG,"Invalid condition !");
+        OIC_LOG_V(ERROR, TAG,"u_cond_broadcast, Invalid condition !");
         return;
     }
 
-    GCond *condition = (GCond*) cond;
+    GCond *condition = (GCond *) cond;
     g_cond_broadcast(condition);
 }
 
@@ -140,18 +145,18 @@ void u_cond_wait(u_cond cond, u_mutex mutex)
 {
     if (NULL == mutex)
     {
-        OIC_LOG_V(ERROR, TAG,"Invalid mutex !");
+        OIC_LOG_V(ERROR, TAG,"u_cond_wait, Invalid mutex !");
         return;
     }
 
     if (NULL == cond)
     {
-        OIC_LOG_V(ERROR, TAG,"Invalid condition !");
+        OIC_LOG_V(ERROR, TAG,"u_cond_wait, Invalid condition !");
         return;
     }
 
-    GMutex *mutexLock = (GMutex*) mutex;
-    GCond *condition = (GCond*) cond;
+    GMutex *mutexLock = (GMutex *) mutex;
+    GCond *condition = (GCond *) cond;
     g_cond_wait(condition, mutexLock);
 }
 
@@ -159,11 +164,11 @@ void u_cond_free(u_cond cond)
 {
     if (NULL == cond)
     {
-        OIC_LOG_V(ERROR, TAG,"Invalid condition !");
+        OIC_LOG_V(ERROR, TAG,"u_cond_free, Invalid condition !");
         return;
     }
 
-    GCond *condition = (GCond*) cond;
+    GCond *condition = (GCond *) cond;
     g_cond_free(condition);
 }
 
index 8454c10..f7c6c52 100644 (file)
  * limitations under the License.
  *
  ******************************************************************/
+#include "uqueue.h"
 
 #include <stddef.h>
 #include <stdlib.h>
 #include <stdio.h>
-
 #include "logger.h"
-#include "uqueue.h"
 #include "oic_malloc.h"
 
+/**
+ * @def NO_MESSAGES
+ * @brief Number of messages in the queue
+ */
 #define NO_MESSAGES 0
+
+/**
+ * @def TAG
+ * @brief Logging tag for module name
+ */
 #define TAG PCF("UQUEUE")
 
-u_queue_tu_queue_create()
+u_queue_t *u_queue_create()
 {
-    u_queue_t* queuePtr = (u_queue_t*) OICMalloc(sizeof(u_queue_t));
+    u_queue_t *queuePtr = (u_queue_t *) OICMalloc(sizeof(u_queue_t));
     if (NULL == queuePtr)
     {
         OIC_LOG(DEBUG, TAG, "QueueCreate FAIL");
@@ -44,10 +52,10 @@ u_queue_t* u_queue_create()
     return queuePtr;
 }
 
-CAResult_t u_queue_add_element(u_queue_tqueue, u_queue_message_t *message)
+CAResult_t u_queue_add_element(u_queue_t *queue, u_queue_message_t *message)
 {
-    u_queue_elementelement = NULL;
-    u_queue_elementptr = NULL;
+    u_queue_element *element = NULL;
+    u_queue_element *ptr = NULL;
 
     if (NULL == queue)
     {
@@ -61,7 +69,7 @@ CAResult_t u_queue_add_element(u_queue_t* queue, u_queue_message_t *message)
         return CA_STATUS_FAILED;
     }
 
-    element = (u_queue_element*) OICMalloc(sizeof(u_queue_element));
+    element = (u_queue_element *) OICMalloc(sizeof(u_queue_element));
     if (NULL == element)
     {
         OIC_LOG(DEBUG, TAG, "QueueAddElement FAIL, memory allocation failed");
@@ -106,11 +114,11 @@ CAResult_t u_queue_add_element(u_queue_t* queue, u_queue_message_t *message)
     return CA_STATUS_OK;
 }
 
-u_queue_message_t* u_queue_get_element(u_queue_t* queue)
+u_queue_message_t *u_queue_get_element(u_queue_t *queue)
 {
-    u_queue_elementnext = NULL;
-    u_queue_elementelement = NULL;
-    u_queue_message_tmessage = NULL;
+    u_queue_element *next = NULL;
+    u_queue_element *element = NULL;
+    u_queue_message_t *message = NULL;
 
     if (NULL == queue)
     {
@@ -135,10 +143,10 @@ u_queue_message_t* u_queue_get_element(u_queue_t* queue)
     return message;
 }
 
-CAResult_t u_queue_remove_element(u_queue_tqueue)
+CAResult_t u_queue_remove_element(u_queue_t *queue)
 {
-    u_queue_elementnext = NULL;
-    u_queue_elementremove = NULL;
+    u_queue_element *next = NULL;
+    u_queue_element *remove = NULL;
 
     if (NULL == queue)
     {
@@ -165,7 +173,7 @@ CAResult_t u_queue_remove_element(u_queue_t* queue)
     return CA_STATUS_OK;
 }
 
-uint32_t u_queue_get_size(u_queue_tqueue)
+uint32_t u_queue_get_size(u_queue_t *queue)
 {
     if (NULL == queue)
     {
@@ -176,7 +184,7 @@ uint32_t u_queue_get_size(u_queue_t* queue)
     return queue->count;
 }
 
-CAResult_t u_queue_reset(u_queue_tqueue)
+CAResult_t u_queue_reset(u_queue_t *queue)
 {
     CAResult_t error = CA_STATUS_FAILED;
 
@@ -209,7 +217,7 @@ CAResult_t u_queue_reset(u_queue_t* queue)
 
 }
 
-CAResult_t u_queue_delete(u_queue_tqueue)
+CAResult_t u_queue_delete(u_queue_t *queue)
 {
     CAResult_t error = CA_STATUS_FAILED;
 
@@ -230,7 +238,7 @@ CAResult_t u_queue_delete(u_queue_t* queue)
     return (CA_STATUS_OK);
 }
 
-u_queue_message_t* u_queue_get_head(u_queue_t* queue)
+u_queue_message_t *u_queue_get_head(u_queue_t *queue)
 {
     if (NULL == queue)
     {
index 0ac5a3f..93d0ee1 100644 (file)
@@ -43,7 +43,8 @@ CAResult_t u_thread_pool_init(uint32_t num_of_threads, u_thread_pool_t *thread_p
     OIC_LOG_V(DEBUG, TAG, "IN");
 
     GError *error = NULL;
-    gThreadpool = g_thread_pool_new(run, NULL, num_of_threads, FALSE, &error);
+
+    gThreadpool = g_thread_pool_new(run, NULL, num_of_threads, TRUE, &error);
     if (NULL == gThreadpool)
     {
         OIC_LOG_V(ERROR, TAG, "g_thread_pool_new failed!");
@@ -64,7 +65,6 @@ CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(v
 {
     OIC_LOG_V(DEBUG, TAG, "IN");
 
-    gboolean result = FALSE;
     if (NULL == routine)
     {
         OIC_LOG_V(ERROR, TAG, "routine is NULL!");
@@ -80,12 +80,8 @@ CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(v
 
     message->data = data;
     message->func = routine;
-    result = g_thread_pool_push((GThreadPool *) thread_pool, (void *) message, NULL);
-    if (FALSE == result)
-    {
-        OIC_LOG_V(ERROR, TAG, "Failed to push the task to threadpool!");
-        return CA_STATUS_FAILED;
-    }
+
+    g_thread_pool_push((GThreadPool *) thread_pool, (void *) message, NULL);
 
     OIC_LOG_V(DEBUG, TAG, "OUT");
     return CA_STATUS_OK;
index 5acae9a..4a9dbf8 100644 (file)
@@ -87,24 +87,6 @@ typedef uint32_t (*CAAdapterSendUnitcastData)(const CARemoteEndpoint_t *endpoint
 typedef uint32_t (*CAAdapterSendMulticastData)(void *data, uint32_t dataLen);
 
 /**
- * @brief Starts notification server on adapters.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-typedef CAResult_t (*CAAdapterStartNotificationRecvServer)();
-
-/**
- * @brief Send notification information to the given endpoint.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
- */
-typedef uint32_t (*CAAdapterSendNotification)(const CARemoteEndpoint_t *endpoint, void *data,
-        uint32_t dataLen);
-
-/**
  * @brief Get Network Information
  * @param   info        [OUT]   Local connectivity information structures
  * @param   size        [OUT]   Number of local connectivity structures.
@@ -149,10 +131,6 @@ typedef struct
     CAAdapterSendUnitcastData sendData;
     /** Multicast data function address**/
     CAAdapterSendMulticastData sendDataToAll;
-    /** Notify server function address**/
-    CAAdapterStartNotificationRecvServer startNotifyServer;
-    /** Send Notification function address**/
-    CAAdapterSendNotification sendNotification;
     /** Get Networking information  **/
     CAAdapterGetNetworkInfo GetnetInfo;
     /** Read Data function address**/
index 3474442..043e440 100644 (file)
@@ -29,6 +29,7 @@
 #include "cacommon.h"
 #include "logger.h"
 #include "oic_malloc.h"
+#include "oic_string.h"
 
 /**
  * @def VERIFY_NON_NULL
@@ -36,7 +37,7 @@
  */
 #define VERIFY_NON_NULL(arg, log_tag, log_message) \
     if (NULL == arg ){ \
-        OIC_LOG_V(ERROR, log_tag, "Invalid input: %s!", log_message); \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
         return CA_STATUS_INVALID_PARAM; \
     } \
 
@@ -46,7 +47,7 @@
  */
 #define VERIFY_NON_NULL_RET(arg, log_tag, log_message,ret) \
     if (NULL == arg ){ \
-        OIC_LOG_V(ERROR, log_tag, "Invalid input: %s!", log_message); \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
         return ret; \
     } \
 
@@ -56,7 +57,7 @@
  */
 #define VERIFY_NON_NULL_VOID(arg, log_tag, log_message) \
     if (NULL == arg ){ \
-        OIC_LOG_V(ERROR, log_tag, "Invalid input: %s!", log_message); \
+        OIC_LOG_V(ERROR, log_tag, "Invalid input:%s", log_message); \
         return; \
     } \
 
@@ -90,7 +91,7 @@ CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CAConnectivityType_t type, con
  * @fn CAAdapterCopyRemoteEndpoint
  * @brief Create CARemoteEndpoint_t duplicate instance.
  */
-CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(CARemoteEndpoint_t *remoteEndpoint);
+CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(const CARemoteEndpoint_t *remoteEndpoint);
 
 /**
  * @fn CAAdapterFreeRemoteEndpoint
index 4e64b09..f454611 100644 (file)
@@ -37,99 +37,146 @@ extern "C"
 #endif
 
 /**
- * @brief Initialize EDR connectivity interface.
- * @param registerCallback [IN] To register EDR interfaces to Connectivity Abstraction Layer
- * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
- * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @fn  CAInitializeEDR
+ * @brief  Initialize EDR connectivity interface.
+ *
+ * @param[in]  registerCallback  To register EDR interfaces to Connectivity Abstraction Layer
+ * @param[in]  reqRespCallback  Callback to be notified on receival of request/responses from
+ *                                          peer bluetooth devices.
+ * @param[in]  netCallback  Callback to be notified when network adapter state changes.
+ * @param[in]  threadPool  Thread pool for handling asynchronous tasks.
+ *
+ * @return  #CA_STATUS_OK or #CA_ADAPTER_NOT_ENABLED on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM  Invalid input parameters
+ * @retval  #CA_ADAPTER_NOT_ENABLED Initialization is successful, but bluetooth adapter is
+ *                                                      not enabled
+ * @retval  #CA_STATUS_FAILED Operation failed
  */
 CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
-                           CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback,
+                           CANetworkPacketReceivedCallback reqRespCallback,
+                           CANetworkChangeCallback netCallback,
                            u_thread_pool_t handle);
 
 /**
- * @brief Starting EDR connectivity adapters .As its peer to peer it doesnot require to start any servers
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @fn  CAStartEDR
+ * @brief  Starting EDR connectivity adapters. As its peer to peer it doesnot require to start
+ *           any servers.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_ADAPTER_NOT_ENABLED Bluetooth adapter is not enabled
+ * @retval  #CA_STATUS_FAILED Operation failed
+ *
  */
 CAResult_t CAStartEDR();
 
 /**
- * @brief Starting listening server for receiving multicast search requests
- * Transport Specific Behavior:
- *   EDR  Starts RFCOMM Server with prefixed UUID as per specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @fn  CAStartEDRListeningServer
+ * @brief  Starting listening server for receiving multicast search requests.
+ *            Starts RFCOMM Server with prefixed UUID as per OIC specification.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_SERVER_STARTED_ALREADY  Server is already started and running for the predefined
+ *                                                            service UUID
+ * @retval  #CA_STATUS_FAILED Operation failed
+ *
  */
 CAResult_t CAStartEDRListeningServer();
 
 /**
- * @brief for starting discovery servers for receiving multicast advertisements
- * Transport Specific Behavior:
- *   EDR Starts RFCOMM server with prefixed UUID as per OIC Specification.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @fn  CAStartEDRDiscoveryServer
+ * @brief  Starting discovery server for receiving multicast advertisements.
+ *            Starts RFCOMM Server with prefixed UUID as per OIC specification.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_SERVER_STARTED_ALREADY  Server is already started and running for the predefined
+ *                                                            service UUID
+ * @retval  #CA_STATUS_FAILED Operation failed
+ *
  */
 CAResult_t CAStartEDRDiscoveryServer();
 
 /**
- * @brief Sends data to the endpoint using the adapter connectivity.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
- */
-uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
-
-/**
- * @brief Sends Multicast data to the endpoint using the EDR 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.
- */
-uint32_t CASendEDRMulticastData(void *data, uint32_t dataLen);
-
-/**
- * @brief Starts notification server on EDR adapters.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @fn  CASendEDRUnicastData
+ * @brief  Sends data to the peer bluetooth OIC device using the adapter connectivity.
+ *
+ * @param[in]  remoteEndpoint  Information about peer device to which data needs to be send.
+ * @param[in]  data  Data which needs to be send to peer OIC device.
+ * @param[in]  dataLength  Length of data in bytes.
+ *
+ * @return  Number of bytes sent on the network. 0 indicates failed to send data.
+ *
  */
-CAResult_t CAStartEDRNotifyServer();
+uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data, uint32_t dataLength);
 
 /**
- * @brief Send notification information.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ * @fn  CASendEDRMulticastData
+ * @brief  Sends multicast data to all discovered bluetooth OIC devices using the adapter
+ *           connectivity.
+ *
+ * @param[in]  data  Data which needs to be send to all discovered bluetooth OIC device.
+ * @param[in]  dataLength  Length of data in bytes.
+ *
+ * @return  Number of bytes sent on the network. 0 indicates failed to send data.
+ *
  */
-uint32_t CASendEDRNotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
+uint32_t CASendEDRMulticastData(void *data, uint32_t dataLength);
 
 /**
- * @brief Get EDR Connectivity network information
- * @param   info        [OUT]   Local connectivity information structures
- * @param   size        [OUT]   Number of local connectivity structures.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ *            Starts RFCOMM Server with prefixed UUID as per OIC specification.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_SERVER_STARTED_ALREADY  Server is already started and running for the predefined
+ *                                                            service UUID
+ * @retval  #CA_STATUS_FAILED Operation failed
+ *
+ * @return  Number of bytes sent on the network. 0 indicates failed to send data.
+ *
+ * @fn  CAGetEDRInterfaceInformation
+ * @brief  Get EDR Connectivity network information.
+ *
+ * @param[out]  info  Array of local connectivity information structures.
+ * @param[out]  size  Size of the array @info.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM  Invalid input parameters
+ * @retval  #CA_MEMORY_ALLOC_FAILED  Failed to allocate memory
+ * @retval  #CA_STATUS_FAILED Operation failed
+ *
  */
 CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
 
 /**
- * @brief Read Synchronous API callback.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @fn  CAReadEDRData
+ * @brief  Read Synchronous API callback.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
+ *
  */
 CAResult_t CAReadEDRData();
 
 /**
- * @brief Stopping the adapters and close socket connections
- *   EDR Stops all RFCOMM servers and close sockets.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ * @fn  CAStopEDR
+ * @brief  Stopping the adapters and close socket connections
+ *           EDR Stops all RFCOMM servers and close sockets.
+ *
+ * @return  #CA_STATUS_OK on success
+ *
  */
 CAResult_t CAStopEDR();
 
 /**
- * @brief Terminate the EDR connectivity adapter.
- * Configuration information will be deleted from further use
+ * @fn  CATerminateEDR
+ * @brief  Terminate the EDR connectivity adapter.
+ *           Configuration information will be deleted from further use.
+ *
  */
 void CATerminateEDR();
 
diff --git a/resource/csdk/connectivity/inc/caedradapter_singlethread.h b/resource/csdk/connectivity/inc/caedradapter_singlethread.h
new file mode 100644 (file)
index 0000000..71a13cb
--- /dev/null
@@ -0,0 +1,143 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+/**
+ * @file caedradapter_singlethread.h
+ * @brief This file contains the APIs for single threaded EDR adapters.
+ */
+#ifndef __CA_EDRADAPTER_SINGLETHREAD_H_
+#define __CA_EDRADAPTER_SINGLETHREAD_H_
+
+/**
+ * BT Interface AP
+ **/
+#include "cacommon.h"
+#include "caadapterinterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#ifndef BLUETOOTH_ADAPTER_TAG
+#define BLUETOOTH_ADAPTER_TAG "CA_EDR"
+#endif //BLUETOOTH_ADAPTER_TAG
+
+#define OIC_BT_SERVICE_ID "12341234-1C25-481F-9DFB-59193D238280"
+
+/**
+ * @brief Initialize EDR connectivity interface.
+ * @param registerCallback [IN] To register EDR interfaces to Connectivity Abstraction Layer
+ * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
+ * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
+                           CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback);
+/**
+ * @brief Starting EDR connectivity adapters .As its peer to peer it doesnot require to start any servers
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartEDR();
+
+/**
+ * @brief Starting listening server for receiving multicast search requests
+ * Transport Specific Behavior:
+ *   EDR  Starts RFCOMM Server with prefixed UUID as per specification.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartEDRListeningServer();
+
+/**
+ * @brief for starting discovery servers for receiving multicast advertisements
+ * Transport Specific Behavior:
+ *   EDR Starts RFCOMM server with prefixed UUID as per OIC Specification.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartEDRDiscoveryServer();
+
+/**
+ * @brief Sends data to the endpoint using the adapter connectivity.
+ * Note: length must be > 0.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ */
+uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
+
+/**
+ * @brief Sends Multicast data to the endpoint using the EDR 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.
+ */
+uint32_t CASendEDRMulticastData(void *data, uint32_t dataLen);
+
+/**
+ * @brief Starts notification server on EDR adapters.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartEDRNotifyServer();
+
+/**
+ * @brief Send notification information.
+ * Note: length must be > 0.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ */
+uint32_t CASendEDRNotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
+
+/**
+ * @brief Get EDR Connectivity network information
+ * @param   info        [OUT]   Local connectivity information structures
+ * @param   size        [OUT]   Number of local connectivity structures.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief Read Synchronous API callback.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAReadEDRData();
+
+/**
+ * @brief Stopping the adapters and close socket connections
+ *   EDR Stops all RFCOMM servers and close sockets.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStopEDR();
+
+/**
+ * @brief Terminate the EDR connectivity adapter.
+ * Configuration information will be deleted from further use
+ */
+void CATerminateEDR();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  //__CA_EDRADAPTER_H_
diff --git a/resource/csdk/connectivity/inc/caethernetadapter_singlethread.h b/resource/csdk/connectivity/inc/caethernetadapter_singlethread.h
new file mode 100644 (file)
index 0000000..7aefe0d
--- /dev/null
@@ -0,0 +1,137 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file caethernetadapter_singlethread.h
+ * @brief This file contains the APIs for Single threaded Ethernet Adapter.
+ */
+#ifndef __CA_ETHERNET_ADAPTER_SINGLETHREAD_H__
+#define __CA_ETHERNET_ADAPTER_SINGLETHREAD_H__
+
+#include "cacommon.h"
+#include "caadapterinterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief API to initialize Ethernet Interface.
+ * @param registerCallback [IN] To register Ethernet interfaces to Connectivity Abstraction Layer
+ * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
+ * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback,
+                                CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback);
+
+/**
+ * @brief Start Ethernet Interface adapter.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartEthernet();
+
+/**
+ * @brief Starting listening server for receiving multicast search requests
+ * Transport Specific Behavior:
+ *   Ethernet Starts Multicast Server on  all available IPs and prefixed port number and as per OIC Specification.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartEthernetListeningServer();
+
+/**
+ * @brief for starting discovery servers for receiving multicast advertisements
+ * Transport Specific Behavior:
+ *   Ethernet Starts Start multicast server on all available IPs and prefixed port number as per OIC Specification
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartEthernetDiscoveryServer();
+
+/**
+ * @brief Sends data to the endpoint using the adapter connectivity.
+ * Note: length must be > 0.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ */
+uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *endpoint, void *data,
+                                   uint32_t dataLen);
+
+/**
+ * @brief Sends Multicast data to the endpoint using the Ethernet 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.
+ */
+uint32_t CASendEthernetMulticastData(void *data, uint32_t dataLen);
+
+/**
+ * @brief Starts notification server on Ethernet adapters.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartEthernetNotifyRecvServers();
+
+/**
+ * @brief Send notification information.
+ * Note: length must be > 0.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ */
+uint32_t CASendEthernetNotification(const CARemoteEndpoint_t *endpoint, void *data,
+                                    uint32_t dataLen);
+/**
+ * @brief Get Ethernet Connectivity network information
+ * @param   info        [OUT]   Local connectivity information structures
+ * @param   size        [OUT]   Number of local connectivity structures.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief Read Synchronous API callback.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAReadEthernetData();
+
+/**
+ * @brief Stopping the adapters and close socket connections
+ *   Ethernet Stops all multicast and unicast servers and close sockets.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStopEthernet();
+
+/**
+ * @brief Terminate the Ethernet connectivity adapter.
+ * Configuration information will be deleted from further use
+ */
+void CATerminateEthernet();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif//#ifndef __CA_ETHERNET_ADAPTER_H__
index 32d8ec3..4d355a3 100644 (file)
@@ -35,15 +35,15 @@ extern "C"
 {
 #endif
 
-typedef void (*CAPacketReceiveCallback)(const char* address, const char* data);
+typedef void (*CAPacketReceiveCallback)(char* address, const char* data);
 
 void CAEthernetInitialize(u_thread_pool_t handle);
 
 void CAEthernetTerminate();
 
-int32_t CAEthernetSendUnicastMessage(const char* address, const char* data, int32_t length);
+int32_t CAEthernetSendUnicastMessage(const char* address, char* data, int32_t length);
 
-int32_t CAEthernetSendMulticastMessage(const char* m_address, const char* data);
+int32_t CAEthernetSendMulticastMessage(const char* m_address, char* data);
 
 int32_t CAEthernetStartUnicastServer();
 
@@ -55,11 +55,13 @@ int32_t CAEthernetStopMulticastServer();
 
 void CAEthernetSetCallback(CAPacketReceiveCallback callback);
 
-void CAEthernetGetLocalAddress(charaddressBuffer);
+void CAEthernetGetLocalAddress(char *addressBuffer);
 
-int32_t CAEthernetSendUnicastMessageImpl(const char* address, const char* data);
+int32_t CAEthernetSendUnicastMessageImpl(const char *address, const char *data);
 
-int32_t CAEthernetSendMulticastMessageImpl(const char* msg);
+int32_t CAEthernetSendMulticastMessageImpl(const char *msg);
+
+CAResult_t CAGetEthernetInterfaceInfo(CALocalConnectivity_t **info, uint32_t* size);
 
 #ifdef __cplusplus
 } /* extern "C" */
index c61900b..09be6fd 100644 (file)
@@ -38,11 +38,11 @@ void CAStartAdapter(CAConnectivityType_t connectivity);
 
 void CAStopAdapter(CAConnectivityType_t connectivity);
 
-CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_tsize);
+CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size);
 
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t length);
+CAResult_t CASendUnicastData(CARemoteEndpoint_t* endpoint, void* data, uint32_t length);
 
-CAResult_t CASendMulticastData(voiddata, uint32_t length);
+CAResult_t CASendMulticastData(void *data, uint32_t length);
 
 CAResult_t CAStartListeningServerAdapters();
 
diff --git a/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h b/resource/csdk/connectivity/inc/cainterfacecontroller_singlethread.h
new file mode 100644 (file)
index 0000000..0b0d859
--- /dev/null
@@ -0,0 +1,63 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+/**
+ * @file cainterfacecontroller_singlethread.h
+ * @brief This file contains the APIs for the interface controller
+ */
+#ifndef __CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_
+#define __CA_INTERFACE_CONTROLLER_SINGLETHREAD_H_
+
+#include "caadapterinterface.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+void CAInitializeAdapters();
+
+void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback);
+
+void CASetNetworkChangeCallback(CANetworkChangeCallback callback);
+
+void CAStartAdapter(CAConnectivityType_t connectivity);
+
+void CAStopAdapter(CAConnectivityType_t connectivity);
+
+CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size);
+
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t length);
+
+CAResult_t CASendMulticastData(void *data, uint32_t length);
+
+CAResult_t CAStartListeningServerAdapters();
+
+CAResult_t CAStartDiscoveryServerAdapters();
+
+void CATerminateAdapters();
+
+CAResult_t CAReadData();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif //#ifndef __CA_INTERFACE_CONTROLLER_H_
index bb86930..08e45aa 100644 (file)
@@ -27,7 +27,7 @@
 
 #include "cacommon.h"
 #include "caadapterinterface.h"
-#include "uthreadpool.h" /* for thread pool */
+#include "uthreadpool.h"
 
 /**
  * BLE Interface APIs.
diff --git a/resource/csdk/connectivity/inc/caleadapter_singlethread.h b/resource/csdk/connectivity/inc/caleadapter_singlethread.h
new file mode 100644 (file)
index 0000000..90247e6
--- /dev/null
@@ -0,0 +1,139 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file caleadapter_singlethread.h
+ * @brief This file contains the APIs for LE adapters to be implemented
+ */
+#ifndef _CA_LEADAPTER_SINGLETHREAD_H_
+#define _CA_LEADAPTER_SINGLETHREAD_H_
+
+#include "cacommon.h"
+#include "caadapterinterface.h"
+
+/**
+ * BLE Interface APIs.
+ */
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief Initialize LE connectivity interface.
+ * @param registerCallback [IN] To register LE interfaces to Connectivity Abstraction Layer
+ * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
+ * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
+                          CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback);
+
+/**
+ * @brief Starting LE connectivity adapters .As its peer to peer it doesnot require to start any servers
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartLE();
+
+/**
+ * @brief Starting listening server for receiving multicast search requests
+ * Transport Specific Behavior:
+ *   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)
+ */
+CAResult_t CAStartLEListeningServer();
+
+/**
+ * @brief for starting discovery servers for receiving multicast advertisements
+ * Transport Specific Behavior:
+ *   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)
+ */
+CAResult_t CAStartLEDiscoveryServer();
+
+/**
+ * @brief Sends data to the endpoint using the adapter connectivity.
+ * Note: length must be > 0.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ */
+uint32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
+
+/**
+ * @brief Sends Multicast data to the endpoint using the LE 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.
+ */
+uint32_t CASendLEMulticastData(void *data, uint32_t dataLen);
+
+/**
+ * @brief Starts notification server on EDR adapters.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartLENotifyServer();
+
+/**
+ * @brief Send notification information.
+ * Note: length must be > 0.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ */
+uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
+
+/**
+ * @brief Get LE Connectivity network information
+ * @param   info        [OUT]   Local connectivity information structures
+ * @param   size        [OUT]   Number of local connectivity structures.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief Read Synchronous API callback.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAReadLEData();
+
+/**
+ * @brief Stopping the adapters and close socket connections
+ *   LE Stops all GATT servers and close sockets.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStopLE();
+
+/**
+ * @brief Terminate the LE connectivity adapter.
+ * Configuration information will be deleted from further use
+ */
+void CATerminateLE();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif //#ifndef _CA_LEADAPTER_H_
diff --git a/resource/csdk/connectivity/inc/calecore.h b/resource/csdk/connectivity/inc/calecore.h
new file mode 100644 (file)
index 0000000..23e14f3
--- /dev/null
@@ -0,0 +1,92 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file cawificore.h
+ * @brief This file contains the APIs for Wi-Fi communications.
+ */
+#ifndef __CA_LECORE_H_
+#define __CA_LECORE_H_
+
+#include "cacommon.h"
+#include "uthreadpool.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+typedef void (*CAPacketReceiveCallback)(const char* address, const char* data);
+
+void CALEInitialize(u_thread_pool_t handle);
+
+void CALETerminate();
+
+int32_t CALESendUnicastMessage(const char* address, const char* data, int32_t length);
+
+int32_t CALESendMulticastMessage(const char* m_address, const char* data);
+
+int32_t CALEStartUnicastServer(const char* address, int32_t port);
+
+int32_t CALEStartMulticastServer(const char* m_address, int32_t port);
+
+int32_t CALEStopUnicastServer(int32_t server_id);
+
+int32_t CALEStopMulticastServer(int32_t server_id);
+
+void CALESetCallback(CAPacketReceiveCallback callback);
+
+void CAGetLocalAddress(char* addressBuffer);
+
+int32_t CASendUnicastMessageImpl(const char* address, const char* data);
+
+int32_t CASendMulticastMessageImpl(const char* msg);
+
+/**
+ * BT Common Method : JNI
+ */
+jstring CANativeGetLocalDeviceAddress(JNIEnv* env);
+
+jobjectArray CANativeGetBondedDevices(JNIEnv *env);
+
+jint CANativeGetBTStateOnInfo(JNIEnv *env);
+
+jstring CANativeGetRemoteAddress(JNIEnv *env, jobject bluetoothSocketObj);
+
+void CANativeGattClose(JNIEnv *env, jobject bluetoothGatt);
+
+void CANativeLEStartScan(JNIEnv *env, jobject callback);
+
+void CANativeLEScanService(JNIEnv *env, jobjectArray uuids, jobject callback);
+
+void CANativeLEStopScan(JNIEnv *env, jobject callback);
+
+void CANativeLEConnect(JNIEnv *env, jstring address, jobject context, jboolean autoConnect, jobject callback);
+
+void CANativeLEDisconnect(JNIEnv *env, jobject bluetoothGatt);
+
+void CANativeLEDiscoverServices(JNIEnv *env, jobject bluetoothGatt);
+
+void CANativeLESendData(JNIEnv *env, jobject bluetoothGatt, jobject gattCharacteristic);
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif
index 0185702..df17e6c 100644 (file)
@@ -28,13 +28,13 @@ extern "C"
 {
 #endif
 
-CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequestInfo_t* request);
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request);
 
-CAResult_t CADetachResponseMessage(const CARemoteEndpoint_tobject,
-        const CAResponseInfo_t* response);
+CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
+                                   const CAResponseInfo_t *response);
 
-CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAHeaderOption_t* options,
-        uint8_t numOptions);
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token, const CAHeaderOption_t* options,
+                                      uint8_t numOptions);
 
 void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler);
 
diff --git a/resource/csdk/connectivity/inc/camessagehandler_singlethread.h b/resource/csdk/connectivity/inc/camessagehandler_singlethread.h
new file mode 100644 (file)
index 0000000..02e7a07
--- /dev/null
@@ -0,0 +1,56 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+#ifndef __CA_MESSAGE_HANDLER_H_
+#define __CA_MESSAGE_HANDLER_H_
+
+#include <stdint.h>
+#include "cacommon.h"
+#include "cainterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+typedef void (*CAMessageHandlerCallback)(CAToken_t token, CAResult_t res);
+
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request);
+
+CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
+                                   const CAResponseInfo_t *response);
+
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token, const CAHeaderOption_t *options,
+                                      uint8_t numOptions);
+
+void CASetMessageHandlerCallback(CAMessageHandlerCallback callback);
+
+void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler);
+
+CAResult_t CAInitializeMessageHandler();
+
+void CATerminateMessageHandler();
+
+void CAHandleRequestResponseCallbacks();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif //#ifndef __CA_MESSAGE_HANDLER_H_
index 7eb372c..56fce4f 100644 (file)
@@ -23,6 +23,7 @@
 
 #include "umutex.h"
 #include "cacommon.h"
+#include "uqueue.h"
 
 /**
  @brief Adapter message information
@@ -32,7 +33,6 @@ typedef struct CAAdapterMessage_t
     CARemoteEndpoint_t *remoteEndpoint;
     void *data;
     uint32_t dataLen;
-    struct CAAdapterMessage_t *next;
 } CAAdapterMessage_t;
 
 /**
@@ -41,8 +41,7 @@ typedef struct CAAdapterMessage_t
 typedef struct
 {
     u_mutex queueMutex;
-    CAAdapterMessage_t *begin;
-    CAAdapterMessage_t *end;
+    u_queue_t *queue;
 } CAAdapterMessageQueue_t;
 
 /**
@@ -72,7 +71,7 @@ void CAAdapterTerminateMessageQueue(CAAdapterMessageQueue_t *queueHandle);
  * @return Error Code
  */
 CAResult_t CAAdapterEnqueueMessage(CAAdapterMessageQueue_t *queueHandle,
-                                   CARemoteEndpoint_t *remoteEndpoint,
+                                   const CARemoteEndpoint_t *remoteEndpoint,
                                    void *data, uint32_t dataLen);
 
 /**
@@ -92,3 +91,4 @@ void CAAdapterFreeMessage(CAAdapterMessage_t *message);
 
 #endif //#ifndef _CA_MESSAGE_QUEUE_H_
 
+
index 38eea6c..4e93bf6 100644 (file)
@@ -28,18 +28,14 @@ extern "C"
 {
 #endif
 
-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 CAConnectivityType);
 
 CAResult_t CARemoveNetworkType(uint32_t CAConnectivityType);
 
-u_arraylist_tCAGetSelectedNetworkList();
+u_arraylist_t *CAGetSelectedNetworkList();
 
-CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_tsize);
+CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size);
 
 #ifdef __cplusplus
 } /* extern "C" */
index e2ec963..42ccd47 100644 (file)
@@ -23,6 +23,7 @@
 #include "cacommon.h"
 #include "config.h"
 #include "coap.h"
+#include "debug.h"
 
 #ifdef __cplusplus
 extern "C"
@@ -34,58 +35,61 @@ typedef uint32_t code_t;
 /**
  * function for generating
  */
-coap_pdu_t* CAGeneratePdu(const char* uri, const uint32_t code, const CAInfo_t info);
+coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info);
 
 /**
  * function for generating
  */
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t* outReqInfo, char* outUri);
+uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo, char *outUri);
 
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_toutResInfo,
-        char* outUri);
+uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
+                                  char *outUri);
 
-coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options);
+coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options, const CAInfo_t info);
 
-coap_pdu_tCACreatePDUforRequestWithPayload(const code_t code, coap_list_t *optlist,
-        const char* payload);
+coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *optlist,
+        const char* payload, const CAInfo_t info);
 
 /**
  * funtion for parsing
  */
-void CAParseURI(const charuriInfo, coap_list_t **options);
+void CAParseURI(const char *uriInfo, coap_list_t **options);
 
 /**
  * funtion for parsing
  */
 void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist);
 
-coap_list_tCACreateNewOptionNode(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);
 
-int32_t CAOrderOpts(void *a, void *b);
+int CAOrderOpts(void *a, void *b);
 
-uint32_t getOptionCount(coap_opt_iterator_t opt_iter);
+uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter);
+
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result,
+        uint32_t buflen, uint32_t encode_always);
 
 /**
  * funtion for get PDU information
  */
-void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t* outCode, CAInfo_t* outInfo, char* outUri);
+void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo, char *outUri);
 
 /**
  * funtion for parsing
  */
-coap_pdu_t* CAParsePDU(const char* data, uint32_t* outCode);
+coap_pdu_t *CAParsePDU(const char *data, uint32_t *outCode);
 
 /**
  * function for token
  */
-CAResult_t CAGenerateTokenInternal(CAToken_ttoken);
+CAResult_t CAGenerateTokenInternal(CAToken_t *token);
 
 void CADestroyTokenInternal(CAToken_t token);
 
 /**
  * Deinitialize
  */
-void CADeinitialize(CAInfo_tinfo);
+void CADeinitialize(CAInfo_t *info);
 
 #ifdef __cplusplus
 } /* extern "C" */
index 674514c..02b3a14 100644 (file)
@@ -91,22 +91,6 @@ uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *endpoint, void *data, u
 uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLen);
 
 /**
- * @brief Starts notification server on WIFI adapters.
- * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
- */
-CAResult_t CAStartWIFINotifyRecvServers();
-
-/**
- * @brief Send notification information.
- * Note: length must be > 0.
- * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port,
- * 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.
- */
-uint32_t CASendWIFINotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
-/**
  * @brief Get WIFI Connectivity network information
  * @param   info        [OUT]   Local connectivity information structures
  * @param   size        [OUT]   Number of local connectivity structures.
diff --git a/resource/csdk/connectivity/inc/cawifiadapter_singlethread.h b/resource/csdk/connectivity/inc/cawifiadapter_singlethread.h
new file mode 100644 (file)
index 0000000..6642b3e
--- /dev/null
@@ -0,0 +1,135 @@
+/******************************************************************
+ *
+ * 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file cawifiadapter.h
+ * @brief This file contains the APIs for WiFi Adapter.
+ */
+#ifndef __CA_WIFI_ADAPTER_H__
+#define __CA_WIFI_ADAPTER_H__
+
+#include "cacommon.h"
+#include "caadapterinterface.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @brief API to initialize WiFi Interface.
+ * @param registerCallback [IN] To register WIFI interfaces to Connectivity Abstraction Layer
+ * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers
+ * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
+                            CANetworkPacketReceivedCallback networkPacketCallback, CANetworkChangeCallback netCallback);
+
+/**
+ * @brief Start WiFi Interface adapter.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartWIFI();
+
+/**
+ * @brief Starting listening server for receiving multicast search requests
+ * Transport Specific Behavior:
+ *   WIFI Starts Multicast Server on  all available IPs and prefixed port number and as per OIC Specification.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartWIFIListeningServer();
+
+/**
+ * @brief for starting discovery servers for receiving multicast advertisements
+ * Transport Specific Behavior:
+ *   WIFI Starts Start multicast server on all available IPs and prefixed port number as per OIC Specification
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartWIFIDiscoveryServer();
+
+/**
+ * @brief Sends data to the endpoint using the adapter connectivity.
+ * Note: length must be > 0.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ */
+uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
+
+/**
+ * @brief Sends Multicast data to the endpoint using the WIFI 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.
+ */
+uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLen);
+
+/**
+ * @brief Starts notification server on WIFI adapters.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStartWIFINotifyRecvServers();
+
+/**
+ * @brief Send notification information.
+ * Note: length must be > 0.
+ * @param   endpoint    [IN]    Remote Endpoint information (like ipaddress , port, 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.
+ */
+uint32_t CASendWIFINotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen);
+/**
+ * @brief Get WIFI Connectivity network information
+ * @param   info        [OUT]   Local connectivity information structures
+ * @param   size        [OUT]   Number of local connectivity structures.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size);
+
+/**
+ * @brief Read Synchronous API callback.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAReadWIFIData();
+
+/**
+ * @brief Stopping the adapters and close socket connections
+ *   WIFI Stops all multicast and unicast servers and close sockets.
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStopWIFI();
+
+/**
+ * @brief Terminate the WIFI connectivity adapter.
+ * Configuration information will be deleted from further use
+ */
+void CATerminateWIfI();
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif  // #ifndef __CA_WIFI_ADAPTER_H__
index 4c75397..1ca61fb 100644 (file)
@@ -35,15 +35,21 @@ extern "C"
 {
 #endif
 
-typedef void (*CAPacketReceiveCallback)(const char* address, const char* data);
+typedef void (*CAPacketReceiveCallback)(char* address, const int port, const char* data);
+
+void CAWiFiSetCallback(CAPacketReceiveCallback callback);
+
+void CAWiFiInitMutex();
 
 void CAWiFiInitialize(u_thread_pool_t handle);
 
+int32_t CABindUnicastSocket();
+
 void CAWiFiTerminate();
 
-int32_t CAWiFiSendUnicastMessage(const char* address, const char* data, int32_t length);
+int32_t CAWiFiSendUnicastMessage(const char* address, const int port, char* data, int32_t length);
 
-int32_t CAWiFiSendMulticastMessage(const char* m_address, const char* data);
+int32_t CAWiFiSendMulticastMessage(const char* m_address, char* data);
 
 int32_t CAWiFiStartUnicastServer();
 
@@ -53,13 +59,13 @@ int32_t CAWiFiStopUnicastServer();
 
 int32_t CAWiFiStopMulticastServer();
 
-void CAWiFiSetCallback(CAPacketReceiveCallback callback);
+void CAGetLocalAddress(char *addressBuffer);
 
-void CAGetLocalAddress(char* addressBuffer);
+int32_t CASendUnicastMessageImpl(const char *address, const int port, const char *data);
 
-int32_t CASendUnicastMessageImpl(const char* address, const char* data);
+int32_t CASendMulticastMessageImpl(const char *msg);
 
-int32_t CASendMulticastMessageImpl(const char* msg);
+CAResult_t CAGetWIFIInterfaceInfo(CALocalConnectivity_t **info, uint32_t* size);
 
 #ifdef __cplusplus
 } /* extern "C" */
diff --git a/resource/csdk/connectivity/lib/arduinomega.properties b/resource/csdk/connectivity/lib/arduinomega.properties
new file mode 100644 (file)
index 0000000..bf050d1
--- /dev/null
@@ -0,0 +1,32 @@
+#Source directories
+SDIR_ARD_CORE1 = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+#SDIR_ARD_CORE2 = $(ARDUINO_DIR)/hardware/arduino/sam/cores/arduino/avr
+SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
+SDIR_ARD_TIMED_ACTION = $(ARDUINO_DIR)/libraries/TimedAction
+SDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+
+SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE1):$(SDIR_ARD_TIME):$(SDIR_ARD_TIMED_ACTION):$(SDIR_ARD_SPI)
+
+#include directories
+IDIR_ARD_CORE1 = $(ARDUINO_DIR)/hardware/arduino/avr/cores/arduino
+IDIR_ARD_CORE2 = $(ARDUINO_DIR)/hardware/tools/avr/avr/include/
+IDIR_ARD_CORE3 = $(ARDUINO_DIR)/hardware/arduino/avr/variants/mega
+INCD_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time
+INCD_ARD_TIMED_ACTION = $(ARDUINO_DIR)/libraries/TimedAction
+IDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/avr/libraries/SPI
+IDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility
+
+
+INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE1) -I$(IDIR_ARD_CORE2) -I$(IDIR_ARD_CORE3) -I$(INCD_ARD_TIME) -I$(INCD_ARD_TIMED_ACTION) \
+                    -I$(IDIR_ARD_SPI) -I$(IDIR_ARD_ETH_UTIL)
+
+#Compiler/Linker flags
+CFLAGS_PLATFORM = -mmcu=atmega2560 -DF_CPU=16000000L -fno-exceptions -ffunction-sections -fdata-sections -MMD \
+                                       -DARDUINO=157 -DARDUINO_ARCH_AVR -DARDUINO_AVR_ADK -DWITH_ARDUINO -D__AVR__
+                                        
+#Compilers
+$(info ************ arduinodue file*****************)
+CCPLUS=$(ARDUINO_TOOLS_DIR)/avr-g++
+CC=$(ARDUINO_TOOLS_DIR)/avr-gcc
+AR=$(ARDUINO_TOOLS_DIR)/avr-ar
+RANLIB=$(ARDUINO_TOOLS_DIR)/avr-ranlib
index ccfb490..bb44a99 100644 (file)
 #include <sys/socket.h>
 #endif
 
+#ifdef WITH_ARDUINO
+#define DEV_ADDR_SIZE_MAX (16)
+#endif
+
 #ifdef WITH_LWIP
 #include <lwip/ip_addr.h>
 
@@ -132,6 +136,45 @@ _coap_is_mcast_impl(const coap_address_t *a)
 }
 #endif /* WITH_POSIX */
 
+#ifdef WITH_ARDUINO
+typedef struct coap_address_t
+{
+    uint32_t     size;                    /**< length of the address stored in addr field. */
+    uint8_t      addr[DEV_ADDR_SIZE_MAX]; /**< device address. */
+} coap_address_t;
+
+static inline int
+_coap_address_equals_impl(const coap_address_t *a,
+                          const coap_address_t *b)
+{
+    uint32_t i;
+
+    if ((a == NULL) || (b == NULL))
+        return 0;
+
+    if (a->size != b->size)
+        return 0;
+
+    for (i = 0; i < a->size; i++)
+    {
+        if (a->addr[i] != b->addr[i])
+            return 0;
+    }
+    return 1;
+}
+
+static inline int
+_coap_is_mcast_impl(const coap_address_t *a)
+{
+    if (!a)
+        return 0;
+
+    /* TODO */
+    return 0;
+}
+
+#endif /* WITH_ARDUINO */
+
 /**
  * Resets the given coap_address_t object @p addr to its default
  * values.  In particular, the member size must be initialized to the
index 0e121ab..20281a0 100644 (file)
@@ -15,7 +15,9 @@
 #ifndef _BITS_H_
 #define _BITS_H_
 
+#ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
+#endif
 #include <stdint.h>
 
 /**
index 709f57c..c0373f7 100644 (file)
 # include <assert.h>
 #endif
 
+#ifdef WITH_ARDUINO
+/* On Arduino the abort function, needed for assert, is defined in std lib */
+#include <stdlib.h>
+#endif
+
 #include "debug.h"
 #include "block.h"
 
index 91de631..2d5ef07 100644 (file)
  */
 typedef struct
 {
-    unsigned int num :20; /**< block number */
-    unsigned int m :1; /**< 1 if more blocks follow, 0 otherwise */
-    unsigned int szx :3; /**< block size */
+#ifdef WITH_ARDUINO
+    unsigned long int num : 20;
+#else
+    unsigned int num : 20;
+#endif
+    unsigned int m : 1; /**< 1 if more blocks follow, 0 otherwise */
+    unsigned int szx : 3; /**< block size */
 } coap_block_t;
 
 /**
index a68b5af..deadd0b 100644 (file)
@@ -106,20 +106,50 @@ extern "C"
     extern time_t clock_offset;
 #endif /* WITH_POSIX */
 
+#ifdef WITH_ARDUINO
+#include "Time.h"
+#ifdef __AVR__
+typedef unsigned long time_t; //AVR compiler doesnt define time_t
+#endif
+typedef time_t coap_tick_t;
+
+/**
+ * This data type is used to represent the difference between two
+ * clock_tick_t values. This data type must have the same size in
+ * memory as coap_tick_t to allow wrapping.
+ */
+typedef int coap_tick_diff_t;
+
+/* TODO: Ticks per second value for Arduino needs verification from
+ * documentation */
+#define COAP_TICKS_PER_SECOND 1000
+
+extern time_t clock_offset;
+
+#endif /* WITH_ARDUINO */
+
 #ifndef coap_clock_init
     static inline void coap_clock_init_impl(void)
     {
 #ifdef HAVE_TIME_H
         clock_offset = time(NULL);
 #else
-#  ifdef __GNUC__
-        /* Issue a warning when using gcc. Other prepropressors do
-         *  not seem to have a similar feature. */
-#   warning "cannot initialize clock"
-#  endif
-        clock_offset = 0;
+#  ifdef WITH_ARDUINO
+#ifdef __AVR__
+    clock_offset = 1; //now();
+#else
+    clock_offset = now();
 #endif
-    }
+#  else
+#    ifdef __GNUC__
+    /* Issue a warning when using gcc. Other prepropressors do
+     *  not seem to have a similar feature. */
+#     warning "cannot initialize clock"
+#    endif
+    clock_offset = 0;
+#  endif /* WITH_ARDUINO */
+#endif /* HAVE_TIME */
+}
 #define coap_clock_init coap_clock_init_impl
 #endif /* coap_clock_init */
 
@@ -132,9 +162,19 @@ extern "C"
         *t = (tv.tv_sec - clock_offset) * COAP_TICKS_PER_SECOND
                 + (tv.tv_usec * COAP_TICKS_PER_SECOND / 1000000);
 #else
-#error "clock not implemented"
+#  ifdef WITH_ARDUINO
+    coap_tick_t tv;
+#ifdef __AVR__
+    tv = 1; //now();
+#else
+    tv = now();
 #endif
-    }
+    *t = (tv - clock_offset) * COAP_TICKS_PER_SECOND;
+#  else
+#    error "clock not implemented"
+#  endif /* WITH_ARDUINO */
+#endif /* HAVE_SYS_TIME_H */
+}
 #define coap_ticks coap_ticks_impl
 #endif /* coap_ticks */
 
index 654c4ea..6d2beb6 100644 (file)
@@ -5,7 +5,9 @@
 /* #undef AC_APPLE_UNIVERSAL_BUILD */
 
 /* Define to 1 if you have the <arpa/inet.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_ARPA_INET_H 1
+#endif
 
 /* Define to 1 if you have the <assert.h> header file. */
 #define HAVE_ASSERT_H 1
@@ -36,7 +38,9 @@
 #define HAVE_NETDB_H 1
 
 /* Define to 1 if you have the <netinet/in.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_NETINET_IN_H 1
+#endif
 
 /* Define to 1 if you have the `select' function. */
 #define HAVE_SELECT 1
 #define HAVE_STRRCHR 1
 
 /* Define to 1 if you have the <syslog.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYSLOG_H 1
+#endif
 
 /* Define to 1 if you have the <sys/socket.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYS_SOCKET_H 1
+#endif
 
 /* Define to 1 if you have the <sys/stat.h> header file. */
 #define HAVE_SYS_STAT_H 1
 
 /* Define to 1 if you have the <sys/time.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYS_TIME_H 1
+#endif
 
 /* Define to 1 if you have the <sys/types.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYS_TYPES_H 1
+#endif
 
 /* Define to 1 if you have the <sys/unistd.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_SYS_UNISTD_H 1
+#endif
 
 /* Define to 1 if you have the <time.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_TIME_H 1
+#endif
 
 /* Define to 1 if you have the <unistd.h> header file. */
+#ifndef WITH_ARDUINO
 #define HAVE_UNISTD_H 1
+#endif
 
 /* Define to the address where bug reports for this package should be sent. */
 #define PACKAGE_BUGREPORT ""
index cb9a852..4afe4f9 100644 (file)
@@ -341,6 +341,14 @@ coap_show_pdu(const coap_pdu_t *pdu)
 
 #endif /* NDEBUG */
 
+#ifdef WITH_ARDUINO
+void coap_log_impl(coap_log_t level, const char *format, ...)
+{
+    //TODO: Implement logging functionalities for Arduino
+}
+#endif
+
+#ifndef WITH_ARDUINO
 #ifndef WITH_CONTIKI
 void coap_log_impl(coap_log_t level, const char *format, ...)
 {
@@ -389,3 +397,4 @@ coap_log_impl(coap_log_t level, const char *format, ...)
     va_end(ap);
 }
 #endif /* WITH_CONTIKI */
+#endif
index cde69f7..b9b304e 100644 (file)
 #if (BSD >= 199103) || defined(WITH_CONTIKI)
 # include <string.h>
 #else
+#ifndef WITH_ARDUINO
 # include <strings.h>
 #endif
+#endif
 
 #define Nn 8  /* duplicate definition of N if built on sky motes */
 #define E 4
diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/makefile_arduino.mak b/resource/csdk/connectivity/lib/libcoap-4.1.1/makefile_arduino.mak
new file mode 100644 (file)
index 0000000..2869b40
--- /dev/null
@@ -0,0 +1,74 @@
+# override with `make BUILD=debug`
+# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue`
+# default to release build
+# default to build for linux
+BUILD   := release
+#other options are android, arduino
+PLATFORM=linux
+# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield
+ARDUINOWIFI := 0
+
+OUT_DIR          := ./$(BUILD)
+OBJ_DIR          := $(OUT_DIR)/obj
+
+ROOT_DIR = ..
+
+# Note for Arduino: The CC flag is set to the C++ compiler since Arduino build 
+# includes Time.h header file which has C++ style definitions.
+ifeq ($(PLATFORM),arduinomega)
+    include $(ROOT_DIR)/local.properties
+    include $(ROOT_DIR)/$(PLATFORM).properties
+       CC=$(ARDUINO_TOOLS_DIR)/avr-gcc
+else ifeq ($(PLATFORM),arduinodue)
+    include $(ROOT_DIR)/local.properties
+    include $(ROOT_DIR)/$(PLATFORM).properties
+       CC=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-g++
+else
+   $(error Wrong value for PLATFORM !!)
+endif
+
+CC_FLAGS.debug := -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions -pedantic \
+-DTB_LOG
+CC_FLAGS.release := -Os -Wall -ffunction-sections -fdata-sections -fno-exceptions
+
+SOURCES:= pdu.c net.c debug.c encode.c uri.c coap_list.c resource.c hashkey.c \
+          str.c option.c async.c subscribe.c block.c
+#VPATH := $(OCSOCK_DIR)/src:$(LOGGER_DIR)/src:$(RANDOM_DIR)/src
+ifeq (arduino, $(findstring arduino,$(PLATFORM)))
+       SOURCESCPP:= Time.cpp
+       OBJECTSCPP:= $(patsubst %.cpp, %.o, $(SOURCESCPP))
+       VPATH += $(SDIR_ARD_TIME)
+else
+       #SOURCES += ocsocket.c
+endif
+
+OBJECTS:= $(patsubst %.c, %.o, $(SOURCES))
+
+all: prep_dirs libcoap.a
+
+prep_dirs:
+       -mkdir $(OUT_DIR)
+       -mkdir $(OBJ_DIR)
+
+%.o: %.c
+       $(CC) -c $(CC_FLAGS.$(BUILD)) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+
+%.o: %.cpp
+       $(CCPLUS) -c $(CC_FLAGS.$(BUILD)) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+
+libcoap.a: $(OBJECTS) $(OBJECTSCPP)
+       $(AR) rcs $(OUT_DIR)/$@ $(addprefix $(OBJ_DIR)/,$^)
+       $(RANLIB) $(OUT_DIR)/$@
+
+.PHONY: clean
+
+clean: legacy_clean
+       -rm -rf release
+       -rm -rf debug
+       
+#There is no installation in LibCoap.
+install: all
+       
+legacy_clean:
+       rm -f *.o libcoap.a
+
index 9e533df..6c6fe54 100644 (file)
@@ -18,7 +18,9 @@
 #elif HAVE_SYS_UNISTD_H
 #include <sys/unistd.h>
 #endif
+#ifdef HAVE_SYS_TYPES_H
 #include <sys/types.h>
+#endif
 #ifdef HAVE_SYS_SOCKET_H
 #include <sys/socket.h>
 #endif
@@ -45,7 +47,7 @@
 #include "block.h"
 #include "net.h"
 
-#if defined(WITH_POSIX)
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
 
 time_t clock_offset;
 
@@ -60,7 +62,7 @@ coap_free_node(coap_queue_t *node)
 {
     coap_free(node);
 }
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_LWIP
 
 #include <lwip/memp.h>
@@ -314,10 +316,12 @@ is_wkc(coap_key_t k)
 }
 #endif
 
+
+#ifndef WITH_ARDUINO
 coap_context_t *
 coap_new_context(const coap_address_t *listen_addr)
 {
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX)
     coap_context_t *c = coap_malloc( sizeof( coap_context_t ) );
     int reuse = 1;
 #endif /* WITH_POSIX */
@@ -379,7 +383,7 @@ coap_new_context(const coap_address_t *listen_addr)
     coap_register_option(c, COAP_OPTION_BLOCK2);
     coap_register_option(c, COAP_OPTION_BLOCK1);
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0);
     if ( c->sockfd < 0 )
     {
@@ -412,7 +416,7 @@ coap_new_context(const coap_address_t *listen_addr)
     coap_free( c );
     return NULL;
 
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
     c->conn = udp_new(NULL, 0, NULL);
     udp_bind(c->conn, listen_addr->port);
@@ -461,7 +465,7 @@ void coap_free_context(coap_context_t *context)
     coap_retransmittimer_restart(context);
 #endif
 
-#if defined(WITH_POSIX) || defined(WITH_LWIP)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
 #ifdef COAP_RESOURCES_NOHASH
     LL_FOREACH(context->resources, res)
     {
@@ -487,7 +491,7 @@ void coap_free_context(coap_context_t *context)
     initialized = 0;
 #endif /* WITH_CONTIKI */
 }
-
+#endif //ifndef WITH_ARDUINO
 int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu, coap_opt_filter_t unknown)
 {
 
@@ -547,6 +551,11 @@ void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap
         return;
     }
 #endif
+
+#ifdef WITH_ARDUINO
+    coap_hash((const unsigned char *)peer->addr, peer->size, h);
+#endif /* WITH_ARDUINO */
+
 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
     /* FIXME: with lwip, we can do better */
     coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h);
@@ -575,7 +584,17 @@ coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst, coa
     return result;
 }
 
-#ifdef WITH_POSIX
+#if defined(WITH_ARDUINO)
+coap_tid_t
+coap_send_impl(coap_context_t *context,
+               const coap_address_t *dst,
+               coap_pdu_t *pdu)
+{
+    return 0;
+}
+#endif
+
+#if defined(WITH_POSIX)
 /* releases space allocated by PDU if free_pdu is set */
 coap_tid_t
 coap_send_impl(coap_context_t *context,
@@ -602,7 +621,7 @@ coap_send_impl(coap_context_t *context,
 
     return id;
 }
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
 /* releases space allocated by PDU if free_pdu is set */
 coap_tid_t
@@ -684,7 +703,9 @@ coap_send_impl(coap_context_t *context,
 
 coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *pdu)
 {
+#ifndef WITH_ARDUINO
     return coap_send_impl(context, dst, pdu);
+#endif
 }
 
 coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request, const coap_address_t *dst,
@@ -822,7 +843,7 @@ coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node)
 
     /* no more retransmissions, remove node from system */
 
-#ifndef WITH_CONTIKI
+#if !defined(WITH_CONTIKI) && !defined(WITH_ARDUINO)
     debug("** removed transaction %d\n", ntohs(node->id));
 #endif
 
@@ -861,9 +882,10 @@ static inline int check_opt_size(coap_opt_t *opt, unsigned char *maxpos)
     return 0;
 }
 
+#ifndef WITH_ARDUINO
 int coap_read(coap_context_t *ctx)
 {
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX)
     static char buf[COAP_MAX_PDU_SIZE];
 #endif
 #if defined(WITH_LWIP) || defined(WITH_CONTIKI)
@@ -887,10 +909,10 @@ int coap_read(coap_context_t *ctx)
 
     coap_address_init(&src);
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX)
     bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0, &src.addr.sa, &src.size);
 
-#endif /* WITH_POSIX */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
     if(uip_newdata())
     {
@@ -987,6 +1009,7 @@ int coap_read(coap_context_t *ctx)
 #endif
     return -1;
 }
+#endif //#ifndef WITH_ARDUINO
 
 int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **node)
 {
index 37057bf..725bbc4 100644 (file)
@@ -9,6 +9,10 @@
 #ifndef _COAP_NET_H_
 #define _COAP_NET_H_
 
+#ifdef WITH_ARDUINO
+#include "Time.h"
+#endif /* WITH_ARDUINO */
+
 #ifdef __cplusplus
 extern "C"
 {
@@ -104,14 +108,14 @@ extern "C"
         /** list of asynchronous transactions */
         struct coap_async_state_t *async_state;
 #endif /* WITHOUT_ASYNC */
-        /**
-         * The time stamp in the first element of the sendqeue is relative
-         * to sendqueue_basetime. */
-        coap_tick_t sendqueue_basetime;
-        coap_queue_t *sendqueue, *recvqueue;
-#if WITH_POSIX
-        int sockfd; /**< send/receive socket */
-#endif /* WITH_POSIX */
+    /**
+     * The time stamp in the first element of the sendqeue is relative
+     * to sendqueue_basetime. */
+    coap_tick_t sendqueue_basetime;
+    coap_queue_t *sendqueue, *recvqueue;
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
+    int sockfd; /**< send/receive socket */
+#endif /* WITH_POSIX || WITH_ARDUINO */
 #ifdef WITH_CONTIKI
         struct uip_udp_conn *conn; /**< uIP connection object */
 
@@ -185,20 +189,23 @@ extern "C"
     /** Creates a new coap_context_t object that will hold the CoAP stack status.  */
     coap_context_t *coap_new_context(const coap_address_t *listen_addr);
 
-    /**
-     * Returns a new message id and updates @p context->message_id
-     * accordingly. The message id is returned in network byte order
-     * to make it easier to read in tracing tools.
-     *
-     * @param context the current coap_context_t object
-     * @return incremented message id in network byte order
-     */
-    static inline unsigned short coap_new_message_id(coap_context_t *context)
-    {
-#ifndef WITH_CONTIKI
-        return htons(++(context->message_id));
+/**
+ * Returns a new message id and updates @p context->message_id
+ * accordingly. The message id is returned in network byte order
+ * to make it easier to read in tracing tools.
+ *
+ * @param context the current coap_context_t object
+ * @return incremented message id in network byte order
+ */
+static inline unsigned short coap_new_message_id(coap_context_t *context)
+{
+    ++(context->message_id);
+#if defined(WITH_ARDUINO)
+    return ((context->message_id << 8) | ((context->message_id >> 8) & (0xFF)));
+#elif defined(WITH_CONTIKI)
+    return uip_htons(context->message_id);
 #else /* WITH_CONTIKI */
-        return uip_htons(++context->message_id);
+    return htons(context->message_id);
 #endif
     }
 
index 9a621f1..9262503 100644 (file)
 #include "option.h"
 #include "encode.h"
 
+#ifdef WITH_ARDUINO
+#include "util.h"
+#endif
+
 #ifdef WITH_CONTIKI
 #include "memb.h"
 
@@ -93,7 +97,7 @@ coap_pdu_init(unsigned char type, unsigned char code, unsigned short id, size_t
         return NULL;
 
     /* size must be large enough for hdr */
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     pdu = coap_malloc(sizeof(coap_pdu_t) + size);
 #endif
 #ifdef WITH_CONTIKI
@@ -147,12 +151,12 @@ coap_new_pdu()
 
 void coap_delete_pdu(coap_pdu_t *pdu)
 {
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     coap_free( pdu );
 #endif
 #ifdef WITH_LWIP
     if (pdu != NULL) /* accepting double free as the other implementation accept that too */
-    pbuf_free(pdu->pbuf);
+        pbuf_free(pdu->pbuf);
 #endif
 #ifdef WITH_CONTIKI
     memb_free(&pdu_storage, pdu);
index c2dfdf0..c469b24 100644 (file)
 #define COAP_DEFAULT_PORT           5683 /* CoAP default UDP port */
 #define COAP_DEFAULT_MAX_AGE          60 /* default maximum object lifetime in seconds */
 #ifndef COAP_MAX_PDU_SIZE
-#define COAP_MAX_PDU_SIZE           1400 /* maximum size of a CoAP PDU */
+#ifdef WITH_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
 #endif /* COAP_MAX_PDU_SIZE */
 
 #define COAP_DEFAULT_VERSION           1 /* version of CoAP supported */
@@ -216,7 +220,8 @@ typedef struct
     unsigned char *data; /**< payload */
 
 #ifdef WITH_LWIP
-    struct pbuf *pbuf; /**< lwIP PBUF. The allocated coap_pdu_t will always reside inside the pbuf's payload, but the pointer has to be kept because no exact offset can be given. This field must not be accessed from outside, because the pbuf's reference count is checked to be 1 when the pbuf is assigned to the pdu, and the pbuf stays exclusive to this pdu. */
+    struct pbuf
+            *pbuf; /**< lwIP PBUF. The allocated coap_pdu_t will always reside inside the pbuf's payload, but the pointer has to be kept because no exact offset can be given. This field must not be accessed from outside, because the pbuf's reference count is checked to be 1 when the pbuf is assigned to the pdu, and the pbuf stays exclusive to this pdu. */
 #endif
 
 } coap_pdu_t;
index 624ea4f..fd78268 100644 (file)
@@ -27,7 +27,7 @@
 #define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object)
 
 #endif
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
 #include "utlist.h"
 #include "mem.h"
 
@@ -339,7 +339,7 @@ coap_resource_init(const unsigned char *uri, size_t len, int flags)
 {
     coap_resource_t *r;
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t));
 #endif
 #ifdef WITH_LWIP
@@ -381,7 +381,7 @@ coap_add_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen,
     if (!resource || !name)
         return NULL;
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t));
 #endif
 #ifdef WITH_LWIP
@@ -501,7 +501,7 @@ int coap_delete_resource(coap_context_t *context, coap_key_t key)
     if (!resource)
         return 0;
 
-#if defined(WITH_POSIX) || defined(WITH_LWIP)
+#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO)
 #ifdef COAP_RESOURCES_NOHASH
     LL_DELETE(context->resources, resource);
 #else
@@ -512,15 +512,15 @@ int coap_delete_resource(coap_context_t *context, coap_key_t key)
     LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr);
 
     if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI)
-    coap_free(resource->uri.s);
+        coap_free(resource->uri.s);
 
-#ifdef WITH_POSIX
+#if defined(WITH_POSIX) || defined(WITH_ARDUINO)
     coap_free(resource);
 #endif
 #ifdef WITH_LWIP
     memp_free(MEMP_COAP_RESOURCE, resource);
 #endif
-#else /* not (WITH_POSIX || WITH_LWIP) */
+#else /* not (WITH_POSIX || WITH_LWIP || WITH_ARDUINO) */
     /* delete registered attributes */
     while ((attr = list_pop(resource->link_attr)))
         memb_free(&attribute_storage, attr);
diff --git a/resource/csdk/connectivity/lib/local.properties b/resource/csdk/connectivity/lib/local.properties
new file mode 100644 (file)
index 0000000..62598c8
--- /dev/null
@@ -0,0 +1,2 @@
+ARDUINO_DIR = /usr/share/arduino
+ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
\ No newline at end of file
diff --git a/resource/csdk/connectivity/samples/arduino/casample.cpp b/resource/csdk/connectivity/samples/arduino/casample.cpp
new file mode 100644 (file)
index 0000000..03b0a1a
--- /dev/null
@@ -0,0 +1,564 @@
+/******************************************************************
+ *
+ * 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 <ctype.h>
+#include <errno.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "cacommon.h"
+#include "cainterface.h"
+#include <TimedAction.h>
+#include "Arduino.h"
+
+#include "oic_malloc.h"
+
+#define MAX_BUF_LEN 100 //1024
+#define MAX_OPT_LEN 100
+
+#define printf Serial.println
+//#define printf
+
+void print_menu();
+void process();
+
+void initialize();
+void start_listening_server();
+void start_discovery_server();
+void find_resource();
+void send_request();
+void send_response(CARemoteEndpoint_t *endpoint, CAToken_t request_token);
+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, int bufferLength, int *dataLength)
+{
+    while (!Serial.available());
+    int len = 0;
+    while (Serial.available())
+    {
+        delay(100);
+        char c = Serial.read();
+        if ('\n' != c && '\r' != c && len < bufferLength - 1)
+        {
+            readInput[len++] = c;
+        }
+        else
+        {
+            break;
+        }
+    }
+
+    readInput[len] = '\0';
+    Serial.flush();
+    Serial.print("PD:");
+    Serial.println(readInput);
+    (*dataLength) = len;
+}
+
+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)
+    {
+        case 0:
+            return CA_ETHERNET;
+        case 1:
+            return CA_WIFI;
+        case 2:
+            return CA_EDR;
+        case 3:
+            return CA_LE;
+    }
+}
+void setup()
+{
+    Serial.begin (115200);
+
+    printf("============");
+    printf("CA SAMPLE");
+    printf("============");
+    print_menu();
+}
+
+void loop()
+{
+    char buffer[5];
+    memset(buffer, 0, sizeof(buffer));
+    int16_t len;
+    if (Serial.available() > 0)
+    {
+        getData(buffer, sizeof(buffer), &len);
+        switch (toupper(buffer[0]))
+        {
+            case 'M': // menu
+                print_menu();
+                break;
+
+            case 'Q': // quit
+                printf("quit");
+                return;
+
+            case 'I': // Initialize interface
+                initialize();
+                break;
+
+            case 'S': // start listening server
+                start_listening_server();
+                break;
+
+            case 'D': // start discovery server
+                start_discovery_server();
+                break;
+
+            case 'F': // find resource
+                find_resource();
+                break;
+
+            case 'R': // send request
+                send_request();
+                break;
+
+            case 'A': // advertise resource
+                advertise_resource();
+                break;
+
+            case 'B': // send notification
+                send_notification();
+                break;
+
+            case 'N': // select network
+                select_network();
+                break;
+
+            case 'X': // unselect network
+                unselect_network();
+                break;
+
+            case 'H': // handle request response
+                handle_request_response();
+                break;
+
+            case 'T': // handle request response
+                terminate();
+                break;
+
+            default:
+                printf("wrong menu");
+                break;
+        }
+    }
+}
+
+void initialize()
+{
+    CAInitialize();
+    select_network();
+    // set handler.
+    CARegisterHandler(request_handler, response_handler);
+}
+
+void start_listening_server()
+{
+    printf("start server");
+    CAStartListeningServer();
+}
+
+void start_discovery_server()
+{
+    printf("start server");
+    CAStartDiscoveryServer();
+}
+
+void find_resource()
+{
+    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);
+
+    // create token
+    CAToken_t token = NULL;
+    CAResult_t res = CAGenerateToken(&token);
+    if (res != CA_STATUS_OK)
+    {
+        printf("token generate error!!");
+        token = NULL;
+    }
+
+    printf("token");
+    printf((token != NULL) ? token : "");
+
+    res = CAFindResource(buf, token);
+    if (res != CA_STATUS_OK)
+    {
+        printf("find error");
+    }
+    else
+    {
+        printf("success: ");
+        printf(buf);
+    }
+    CADestroyToken(token);
+}
+
+void send_request()
+{
+    char buf[MAX_BUF_LEN];
+    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+
+    printf("============");
+    printf("10.11.12.13:4545/res_uri (for IP)");
+    printf("10:11:12:13:45:45/res_uri (for BT)");
+    printf("uri: ");
+
+    int16_t len = 0;
+    getData(buf, sizeof(buf), &len);
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    CAResult_t res = CACreateRemoteEndpoint(buf, &endpoint);
+    if (res != CA_STATUS_OK)
+    {
+        printf("Out of memory");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+    endpoint->connectivityType = getConnectivityType();
+    // create token
+    CAToken_t token = NULL;
+    res = CAGenerateToken(&token);
+    if (res != CA_STATUS_OK)
+    {
+        printf("token error");
+        token = NULL;
+    }
+
+    printf((token != NULL) ? token : "");
+
+    CAInfo_t requestData;
+    memset(&requestData, 0, sizeof(CAInfo_t));
+    requestData.token = token;
+    requestData.payload = "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("============");
+}
+
+void advertise_resource()
+{
+    char buf[MAX_BUF_LEN];
+    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+
+    printf("============");
+    printf("uri: ");
+
+    int16_t len = 0;
+    getData(buf, sizeof(buf), &len);
+
+    int16_t optionNum = 0;
+    char optionData[MAX_OPT_LEN];
+    char optionNumBuf[2];
+
+    printf("Option Num: ");
+    getData(optionNumBuf, sizeof(optionNumBuf), &len);
+    optionNum = optionNumBuf[0]  - '0';
+    printf(optionNum);
+
+
+    CAHeaderOption_t *headerOpt = NULL;
+    if (optionNum > 0)
+    {
+        headerOpt = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * optionNum);
+        if (NULL == headerOpt)
+        {
+            printf("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, sizeof(getOptionID), &len);
+        printf("Option Num: ");
+        printf(i + 1);
+        optionID = getOptionID[0];
+        printf(optionID);
+
+        headerOpt[i].optionID = optionID;
+        memset(optionData, 0, sizeof(char) * MAX_OPT_LEN);
+        printf("Option Data itr");
+        printf(i + 1);
+
+        int len = 0;
+        getData(optionData, sizeof(optionData), &len);
+        memcpy(headerOpt[i].optionData, optionData, strlen(optionData));
+        printf(i + 1);
+        printf("data");
+        printf(optionData);
+
+        headerOpt[i].optionLength = (uint16_t)strlen(optionData);
+    }
+
+    printf("============");
+    // create token
+    CAToken_t token = NULL;
+    CAResult_t res = CAGenerateToken(&token);
+    if (res != CA_STATUS_OK)
+    {
+        printf("token generate error!!");
+        token = NULL;
+    }
+
+    printf("token");
+    printf((token != NULL) ? token : "");
+
+    CAAdvertiseResource(buf, token, headerOpt, (uint8_t)optionNum);
+    if (NULL != headerOpt)
+    {
+        OICFree(headerOpt);
+    }
+    CADestroyToken(token);
+}
+
+void send_notification()
+{
+    char buf[MAX_BUF_LEN];
+    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+
+    printf("============");
+    printf("10.11.12.13:4545/res_uri (for IP)");
+    printf("10:11:12:13:45:45/res_uri (for BT)");
+    printf("uri: ");
+
+    int len = 0;
+    getData(buf, sizeof(buf), &len);
+
+    // create remote endpoint
+    CARemoteEndpoint_t *endpoint = NULL;
+    CAResult_t res = CACreateRemoteEndpoint(buf, &endpoint);
+    if (CA_STATUS_OK != res)
+    {
+        printf("Out of memory");
+        CADestroyRemoteEndpoint(endpoint);
+        return;
+    }
+    endpoint->connectivityType = getConnectivityType();
+    CAInfo_t respondeData;
+    memset(&respondeData, 0, sizeof(CAInfo_t));
+    respondeData.token = "token";
+    respondeData.payload = "Notification Data";
+
+    CAResponseInfo_t responseInfo;
+    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+    responseInfo.result = CA_CONTENT;
+    responseInfo.info = respondeData;
+
+    // send request
+    CASendNotification(endpoint, &responseInfo);
+    // destroy remote endpoint
+    if (NULL != endpoint)
+    {
+        CADestroyRemoteEndpoint(endpoint);
+    }
+    printf("============");
+}
+
+void select_network()
+{
+    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");
+
+    int len = 0;
+    getData(buf, sizeof(buf), &len);
+    int number = buf[0] - '0';
+    number = (number < 0 || number > 3) ? 1 : number;
+    CASelectNetwork(1 << number);
+    printf("============");
+}
+
+void unselect_network()
+{
+    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");
+
+    int len = 0;
+    getData(buf, sizeof(buf), &len);
+    int number = buf[0] - '0';
+    printf(number);
+    number = (number < 0 || number > 3) ? 1 : number;
+    CAUnSelectNetwork(1 << number);
+    printf("Terminate");
+    CATerminate();
+    printf("============");
+}
+
+void print_menu()
+{
+
+    printf("============");
+    printf("i: Initialize");
+    printf("s: start listening server");
+    printf("d: start discovery server");
+    printf("f: find resource");
+    printf("r: send request");
+    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("============");
+}
+
+void handle_request_response()
+{
+    CAHandleRequestResponse();
+}
+
+void request_handler(const CARemoteEndpoint_t *object, const CARequestInfo_t *requestInfo)
+{
+    printf("uri: ");
+    printf((object != NULL) ? object->resourceUri : "");
+    printf("data: ");
+    printf((requestInfo != NULL) ? requestInfo->info.payload : "");
+
+    printf("send response");
+    send_response((CARemoteEndpoint_t *)object, requestInfo->info.token);
+}
+
+void response_handler(const CARemoteEndpoint_t *object, const CAResponseInfo_t *responseInfo)
+{
+    printf("uri: ");
+    printf((object != NULL) ? object->resourceUri : "");
+    printf("data: ");
+    printf((responseInfo != NULL) ? responseInfo->info.payload : "");
+}
+
+void send_response(CARemoteEndpoint_t *endpoint, CAToken_t request_token)
+{
+
+    printf("============");
+
+    CAInfo_t responseData;
+    memset(&responseData, 0, sizeof(CAInfo_t));
+    responseData.token = request_token;
+    responseData.payload = "response payload";
+
+    CAResponseInfo_t responseInfo;
+    memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
+    responseInfo.result = (CAResponseResult_t)203;
+    responseInfo.info = responseData;
+
+    // send request (connectivityType from remoteEndpoint of request Info)
+    CASendResponse(endpoint, &responseInfo);
+
+    printf("============");
+
+}
+
+void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token)
+{
+
+    printf("============");
+
+    CAInfo_t requestData;
+    memset(&requestData, 0, sizeof(CAInfo_t));
+    requestData.token = token;
+    requestData.payload = "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("============");
+
+}
+
+void terminate()
+{
+    unselect_network();
+}
diff --git a/resource/csdk/connectivity/samples/arduino/sample_main.cpp b/resource/csdk/connectivity/samples/arduino/sample_main.cpp
new file mode 100644 (file)
index 0000000..337d931
--- /dev/null
@@ -0,0 +1,589 @@
+/*
+
+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.
+ *
+ */
+
+#ifdef __ARDUINO_BLE__
+//"services.h/spi.h/boards.h" is needed in every new project
+#include <SPI.h>
+#include <boards.h>
+#include <RBL_nRF8001.h>
+#include <services.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"
+#include <TimedAction.h>
+#include <logger.h>
+
+char localBTAddress[20] = "DB:F7:EB:B5:0F:07"; //BT Address is not used internally by OIC API.
+int number = 0;
+char coapData[7] = "hello";
+
+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;
+        }
+
+    }
+    //Serial.println("zz");
+    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()
+{
+    Serial.println("Loop");
+    if ((number % 2) == 0)
+        coapData[5] = 'a';
+    else
+        coapData[6] = 'b';
+    coapData[6] = '\0';
+    number++;
+    if (number == 10)
+    {
+        number = 0;
+    }
+    if ( ble_connected() )
+    {
+        Serial.println(PCF("Sending Data"));
+        gConnectivityHandlers->sendData(&remoteEndpoint[1], coapData, strlen(coapData));
+        Serial.println("Sent Data");
+    }
+    gConnectivityHandlers->readData();
+    delay(2000);
+}
+#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"
+#include <TimedAction.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 = 5283; /* 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 = 5283;
+            OIC_LOG(DEBUG, MOD_NAME, "LocalWiFiEndPoint Port is 5283");
+            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 = 5283;
+
+    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__
index 0af36f2..b2da299 100644 (file)
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <unistd.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();
@@ -40,10 +43,15 @@ 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);
+int received = FALSE;
+
+static CAToken_t gLastRequestToken = NULL;
 
 int main()
 {
@@ -53,15 +61,30 @@ int main()
     printf("\t\tsample main\n");
     printf("=============================================\n");
 
-    CAInitialize();
+    CAResult_t res = CAInitialize();
+    if (res != CA_STATUS_OK)
+    {
+        printf("CAInitialize fail\n");
+        return 0;
+    }
 
     // network enable
     // default
     printf("select default network(WIFI)\n");
-    CASelectNetwork(CA_WIFI);
+    res = CASelectNetwork(CA_WIFI);
+    if (res != CA_STATUS_OK)
+    {
+        printf("CASelectNetwork fail\n");
+        return 0;
+    }
 
     // set handler.
-    CARegisterHandler(request_handler, response_handler);
+    res = CARegisterHandler(request_handler, response_handler);
+    if (res != CA_STATUS_OK)
+    {
+        printf("CARegisterHandler fail\n");
+        return 0;
+    }
 
     process();
 
@@ -131,6 +154,34 @@ void process()
             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;
+
+            case 'g': // get network information
+            case 'G':
+                get_network_info();
+                break;
 
             default:
                 printf("not supported menu!!\n");
@@ -144,14 +195,70 @@ void start_listening_server()
 {
     printf("start listening server!!\n");
 
-    CAStartListeningServer();
+    CAResult_t res = CAStartListeningServer();
+    if (res != CA_STATUS_OK)
+    {
+        printf("start listening server fail\n");
+    }
+    else
+    {
+        printf("start listening server success\n");
+    }
 }
 
 void start_discovery_server()
 {
     printf("start discovery client!!\n");
 
-    CAStartDiscoveryServer();
+    CAResult_t res = CAStartDiscoveryServer();
+    if (res != CA_STATUS_OK)
+    {
+        printf("start discovery client fail\n");
+    }
+    else
+    {
+        printf("start discovery client success\n");
+    }
+}
+
+void find_fixed_resource()
+{
+    char buf[MAX_BUF_LEN] =
+    { 0, };
+    strcpy(buf, "a/light");
+
+
+
+    // create token
+    CAToken_t token = NULL;
+    CAResult_t res = CAGenerateToken(&token);
+    if (res != CA_STATUS_OK)
+    {
+        printf("token generate error!!");
+        token = NULL;
+    }
+
+    printf("generated token %s\n", (token != NULL) ? token : "");
+
+    res = CAFindResource(buf, token);
+    if (res != CA_STATUS_OK)
+    {
+        printf("find resource error!!\n");
+    }
+    else
+    {
+        printf("find resource to %s URI\n", buf);
+    }
+
+    // delete token
+    /*
+    if (token != NULL)
+    {
+        CADestroyToken(token);
+    }
+    */
+
+    printf("=============================================\n");
 }
 
 void find_resource()
@@ -166,8 +273,18 @@ void find_resource()
 
     gets(buf);
 
-    CAResult_t res = CAFindResource(buf);
+    // create token
+    CAToken_t token = NULL;
+    CAResult_t res = CAGenerateToken(&token);
+    if (res != CA_STATUS_OK)
+    {
+        printf("token generate error!!\n");
+        token = NULL;
+    }
+
+    printf("generated token %s\n", (token != NULL) ? token : "");
 
+    res = CAFindResource(buf, token);
     if (res != CA_STATUS_OK)
     {
         printf("find resource error!!\n");
@@ -175,8 +292,18 @@ void find_resource()
     else
     {
         printf("find resource to %s URI\n", buf);
+
+        gLastRequestToken = token;
     }
 
+    // delete token
+    /*
+    if (token != NULL)
+    {
+        CADestroyToken(token);
+    }
+    */
+
     printf("=============================================\n");
 }
 
@@ -199,7 +326,7 @@ void send_request()
 
     if (res != CA_STATUS_OK)
     {
-        printf("create remote endpoint error!!");
+        printf("create remote endpoint error!!\n");
         CADestroyRemoteEndpoint(endpoint);
         return;
     }
@@ -210,7 +337,7 @@ void send_request()
 
     if (res != CA_STATUS_OK)
     {
-        printf("token generate error!!");
+        printf("token generate error!!\n");
         token = NULL;
     }
 
@@ -269,7 +396,7 @@ void advertise_resource()
     memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
 
     int i;
-    for(i = 0 ; i < optionNum ; i++)
+    for (i = 0; i < optionNum; i++)
     {
         int optionID = 0;
         printf("[%d] Option ID : ", i + 1);
@@ -280,13 +407,32 @@ void advertise_resource()
         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 );
+        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) strlen(optionData);
     }
     printf("\n=============================================\n");
 
-    CAAdvertiseResource(buf, headerOpt, (uint8_t)optionNum);
+    // create token
+    CAToken_t token = NULL;
+    CAResult_t res = CAGenerateToken(&token);
+    if (res != CA_STATUS_OK)
+    {
+        printf("token generate error!!\n");
+        token = NULL;
+    }
+
+    printf("generated token %s\n", (token != NULL) ? token : "");
+
+    CAAdvertiseResource(buf, token, headerOpt, (uint8_t) optionNum);
+
+    // delete token
+    /*
+    if (token != NULL)
+    {
+        CADestroyToken(token);
+    }
+    */
 
     free(headerOpt);
 
@@ -311,7 +457,7 @@ void send_notification()
 
     if (res != CA_STATUS_OK)
     {
-        printf("create remote endpoint error!!");
+        printf("create remote endpoint error!!\n");
         CADestroyRemoteEndpoint(endpoint);
         return;
     }
@@ -327,13 +473,22 @@ void send_notification()
     responseInfo.info = respondeData;
 
     // send request
-    CASendNotification(endpoint, &responseInfo);
+    res = CASendNotification(endpoint, &responseInfo);
+    if (res != CA_STATUS_OK)
+    {
+        printf("send notification error\n");
+    }
+    else
+    {
+        printf("send notification success\n");
+    }
 
     // destroy remote endpoint
     if (endpoint != NULL)
     {
         CADestroyRemoteEndpoint(endpoint);
     }
+
     printf("\n=============================================\n");
 }
 
@@ -356,7 +511,15 @@ void select_network()
 
     number = (number < 0 || number > 3) ? 1 : number;
 
-    CASelectNetwork(1 << number);
+    CAResult_t res = CASelectNetwork(1 << number);
+    if (res != CA_STATUS_OK)
+    {
+        printf("select network error\n");
+    }
+    else
+    {
+        printf("select network success\n");
+    }
 
     printf("=============================================\n");
 }
@@ -380,7 +543,15 @@ void unselect_network()
 
     number = (number < 0 || number > 3) ? 1 : number;
 
-    CAUnSelectNetwork(1 << number);
+    CAResult_t res = CAUnSelectNetwork(1 << number);
+    if (res != CA_STATUS_OK)
+    {
+        printf("unselect network error\n");
+    }
+    else
+    {
+        printf("unselect network success\n");
+    }
 
     printf("=============================================\n");
 }
@@ -399,7 +570,10 @@ char get_menu()
     printf("\tb : send notification\n");
     printf("\tn : select network\n");
     printf("\tx : unselect network\n");
+    printf("\tg : get network information\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 : ");
@@ -414,53 +588,122 @@ char get_menu()
 void handle_request_response()
 {
     printf("handle_request_response\n");
-    CAHandleRequestResponse();
+
+    CAResult_t res = CAHandleRequestResponse();
+    if (res != CA_STATUS_OK)
+    {
+        printf("handle request error\n");
+    }
+    else
+    {
+        printf("handle request success\n");
+    }
 }
 
-void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo)
+void get_network_info()
 {
+    int index;
+
+    CALocalConnectivity_t* tempInfo;
+    uint32_t tempSize = 0;
+
+    tempInfo = (CALocalConnectivity_t*) malloc(sizeof(CALocalConnectivity_t));
+
+    CAResult_t res = CAGetNetworkInformation(&tempInfo, &tempSize);
+    if (res != CA_STATUS_OK)
+    {
+        printf("get network information error\n");
+        return;
+    }
 
-    printf("[CALLBACK] request_handler, uri : %s, data : %s\n", (object != NULL) ? object->resourceUri : "",
+    printf("network info total size is %d\n", tempSize);
+    for (index = 0; index < tempSize; index++)
+    {
+        if (tempInfo == NULL)
+        {
+            break;
+        }
+
+        printf("type : %d, address : %s\n",
+                tempInfo->type,
+                tempInfo->addressInfo.IP.ipAddress);
+        tempInfo++;
+    }
+
+}
+
+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, uri: %s, data: %s, token: %s \n",
+            (object != NULL) ? object->resourceUri : "",
+            (requestInfo != NULL) ? requestInfo->info.payload : "",
+            (requestInfo->info.token != NULL) ? requestInfo->info.token : "");
+
+    if (gLastRequestToken != NULL && requestInfo->info.token != NULL 
+        && (strcmp((char*)gLastRequestToken, requestInfo->info.token) == 0))
+    {
+        printf("token is same. received request of it's own. skip.. \n");
 
-    printf("[CALLBACK] request_handler, address : %s\n", (object != NULL) ? object->addressInfo.IP.ipAddress : "");
+        return;
+    }
+
+    printf("[CALLBACK] request_handler, address : %s port:%d \n",
+            (object != NULL) ? object->addressInfo.IP.ipAddress : "",
+               (object != NULL) ? object->addressInfo.IP.port : 0);
 
-    if(requestInfo->info.options)
+    if (requestInfo->info.options)
     {
-        uint32_t len =  requestInfo->info.numOptions;
+        uint32_t len = requestInfo->info.numOptions;
         uint32_t i;
-        for(i = 0 ; i < len ; 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("[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 : "",
+    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 : "");
+    printf("[CALLBACK] response_handler, address : %s port :%d\n",
+            (object != NULL) ? object->addressInfo.IP.ipAddress : "",
+            (object != NULL) ? object->addressInfo.IP.port : 0);
 
-    if(responseInfo->info.options)
+    if (responseInfo->info.options)
     {
-        uint32_t len =  responseInfo->info.numOptions;
+        uint32_t len = responseInfo->info.numOptions;
         uint32_t i;
-        for(i = 0 ; i < len ; 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 );
+            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 : "");
@@ -484,7 +727,15 @@ void send_response(CARemoteEndpoint_t* endpoint, CAToken_t request_token)
     responseInfo.info = responseData;
 
     // send request (connectivityType from remoteEndpoint of request Info)
-    CASendResponse(endpoint, &responseInfo);
+    CAResult_t res = CASendResponse(endpoint, &responseInfo);
+    if (res != CA_STATUS_OK)
+    {
+        printf("send response error\n");
+    }
+    else
+    {
+        printf("send response success\n");
+    }
 
     printf("=============================================\n");
 
@@ -507,7 +758,16 @@ void send_request_tmp(CARemoteEndpoint_t* endpoint, CAToken_t token)
 
     // send request
     endpoint->connectivityType = CA_WIFI;
-    CASendRequest(endpoint, &requestInfo);
+
+    CAResult_t res = CASendRequest(endpoint, &requestInfo);
+    if (res != CA_STATUS_OK)
+    {
+        printf("send request error\n");
+    }
+    else
+    {
+        printf("send request success\n");
+    }
 
     printf("=============================================\n");
 
index 22961ff..9ea21a3 100644 (file)
 /******************************************************************
- *
- * 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 <stdlib.h>
+#include <stdio.h>
+#include <string.h>
 #include <ctype.h>
 #include <fcntl.h>
 #include <errno.h>
+#include <wifi.h>
 #include <glib.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <pthread.h>
+
 #include "cacommon.h"
-#include "cainterface.h"
+#include "caadapterinterface.h"
+#include "uthreadpool.h"
+
+#define MOD_NAME "TizenSample"
+
+/**
+ * Enable/disable one or more of the following macros to enable/disable 
+ * functionality of that particular adapter type in the interfacesample.
+ */
+//#define WIFI_ADAPTER_TEST
+#define BT_ADAPTER_TEST
+//#define BLE_ADAPTER_TEST
+
+#if defined(WIFI_ADAPTER_TEST)
+#include "cawifiadapter.h"
+#include "caethernetadapter.h"
+static u_thread_pool_t gWiFiThreadPool = NULL;
+#elif defined(BT_ADAPTER_TEST)
+#include "caedradapter.h"
+static  u_thread_pool_t gBTThreadPool = NULL;
+#elif defined(BLE_ADAPTER_TEST)
+#include "caleadapter.h"
+static u_thread_pool_t gLEThreadPool = NULL;
+#endif
 
 static GMainLoop *mainloop;
 static GIOChannel *channel;
 static guint g_test_io_watch_id;
 static GError *g_err_Sample;
 
-pthread_t thread;
+static CALocalConnectivity_t *localWifiEndpoint = NULL;
+//Hardcoded coap data for Test
+static char coapData[500] =
+    "{\"oc:\[{href\":\"/a/light\",\"ref\":{\"power\":\"20\",\"state\":\"true\"}}]}";
 
-#define MAX_BUF_LEN 1024
-#define MAX_OPT_LEN 16
+void testInitializeBTInterface(void);
+void testTerminateBTInterface(void);
+void testInitializeWIFIInterface(void);
+void testTerminateWIFIInterface(void);
+void testInitializeBLEInterface(void);
+void testTerminateBLEInterface(void);
 
-char get_menu();
-void process();
-
-void initialize();
-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();
+typedef struct ConnectivityHandlerList
+{
+    CAConnectivityType_t type;
+    CAConnectivityHandler_t handler;
+    struct ConnectivityHandlerList *nextHandler;
+} ConnectivityHandlerList;
 
-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();
+static ConnectivityHandlerList *gConnectivityHandlers = NULL;
 
-void pthread_func()
+void initializeThreadPool(CAConnectivityType_t type)
 {
-    g_main_loop_run(mainloop);
+#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 BT adapter!\n");
+            return;
+        }
+    }
+#endif
+#ifdef BLE_ADAPTER_TEST
+    if (CA_LE == type && NULL == gLEThreadPool)
+    {
+        if (CA_STATUS_OK != u_thread_pool_init(3, &gLEThreadPool))
+        {
+            printf("Failed to create thread pool for BT adapter!\n");
+            return;
+        }
+    }
+#endif
 }
 
-int main()
+
+void storeInterfaceCallbacks(ConnectivityHandlerList *newHandler)
 {
-    system("clear");
+    printf("storeInterfaceCallbacks Entry in Sample\n");
+    newHandler->nextHandler = NULL;
+    ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
 
-    printf("=============================================\n");
-    printf("\t\tsample main\n");
-    printf("=============================================\n");
+    if (!tempConnectivityHandlers)
+    {
+        gConnectivityHandlers = newHandler;
+        printf("storeInterfaceCallbacks Exit in Sample\n");
+        return;
+    }
 
-    process();
+    while (tempConnectivityHandlers->nextHandler)
+    {
+        tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+    }
 
-    return 0;
+    tempConnectivityHandlers->nextHandler = newHandler;
+    printf("storeInterfaceCallbacks Exit in Sample\n");
 }
 
-void process()
+void interfaceRegisterCallback(CAConnectivityHandler_t handler,
+                               CAConnectivityType_t connType)
 {
-    while (1)
+    printf("interfaceRegisterCallback Entry in Sample\n");
+    ConnectivityHandlerList *newConnectivityHandler = (ConnectivityHandlerList *) malloc(sizeof(
+                ConnectivityHandlerList));
+    if (NULL == newConnectivityHandler)
     {
-        char menu = toupper(get_menu());
-
-        switch (menu)
-        {
-            case 'Q': // quits the sample program
-                printf("quit..!!\n");
-                g_main_loop_quit(mainloop);
-                return;
-
-            case 'I': // Initialize interface
-                initialize();
+        printf("Memory allocation failed\n");
+        return;
+    }
 
-            case 'S': // start server
-                start_listening_server();
-                break;
+    newConnectivityHandler->type = connType;
+    newConnectivityHandler->handler = handler;
+    storeInterfaceCallbacks(newConnectivityHandler);
+    printf("interfaceRegisterCallback Exit in Sample\n");
+}
 
-            case 'C': // start client
-                start_discovery_server();
-                break;
+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;
+    }
 
-            case 'F': // find resource
-                find_resource();
-                break;
+    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);
+    }
 
-            case 'R': // send request
-                send_request();
-                break;
+    printf("\nReceived Data [Length: %d]: %s\n", dataLength, (char *)data);
+    printf("networkPacketHandler Exit in Sample\n");
+}
 
-            case 'A': // advertise resource
-                advertise_resource();
-                break;
+void networkInterfaceCallback(CALocalConnectivity_t *localEndPoint,
+                              CANetworkStatus_t networkConnectivityState)
+{
+    printf("networkInterfaceCallback Entry in Sample\n");
+    if (localEndPoint == NULL)
+    {
+        printf("NULL Object\n");
+        return;
+    }
 
-            case 'N': // select network
-                select_network();
-                break;
+    if (networkConnectivityState == CA_INTERFACE_UP)
+    {
+        printf("Network Status is UP\n");
+    }
+    else
+    {
+        printf("Network Status is DOWN\n");
+    }
 
-            case 'X': // unselect network
-                unselect_network();
-                break;
+    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);
+    }
 
-            case 'H': // handle request response
-                handle_request_response();
-                break;
+    printf("networkInterfaceCallback Exit in Sample\n");
+}
 
-            case 'T': // Terminate interface
-                terminate();
-                break;
 
-            default:
-                printf("not supported menu!!\n");
-                break;
-        }
+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;
 }
 
-void initialize()
+int16_t interfaceStartAdapter(CAConnectivityType_t connType)
 {
-    mainloop = g_main_loop_new(NULL, FALSE);
-    pthread_create(&thread, NULL, (void *) &pthread_func, NULL);
+    ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf("None of the interface is initialized\n");
+        return 0;
+    }
+
+    while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+    {
+        tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+    }
 
-    CAInitialize();
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf( "No interface handler for type %d", connType);
+        return 0;
+    }
 
-    // network enable
-    // default
-    printf("select default network(WIFI)\n");
-    CASelectNetwork(CA_WIFI);
+    if (CA_STATUS_OK != tempConnectivityHandlers->handler.startAdapter())
+    {
+        printf("Failed to Start adapter\n");
+        return 0;
+    }
 
-    // set handler.
-    CARegisterHandler(request_handler, response_handler);
+    return 1;
 }
 
-void start_listening_server()
+int16_t interfaceMulticastStartServer(CAConnectivityType_t connType, int serverType)
 {
-    printf("start listening server!!\n");
+    printf("interfaceMulticastStartServer Starting...\n");
+    ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf("None of the interface is initialized\n");
+        return 0;
+    }
 
-    CAStartListeningServer();
-}
+    while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+    {
+        tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+    }
 
-void start_discovery_server()
-{
-    printf("start discovery server at client!!\n");
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf( "No interface handler for type %d", connType);
+        return 0;
+    }
 
-    CAStartDiscoveryServer();
+    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();
+    }
 }
 
-void find_resource()
+int16_t interfaceSendUnicastData(CAConnectivityType_t connType)
 {
-    char buf[MAX_BUF_LEN];
-
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-
-    printf("\n=============================================\n");
-    printf("ex) a/light\n");
-    printf("reference uri : ");
+    ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf(" None of the interface is initialized \n");
+        return 0;
+    }
 
-    gets(buf);
+    while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+    {
+        tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+    }
 
-    CAResult_t res = CAFindResource(buf);
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf( "No interface handler for type %d", connType);
+        return 0;
+    }
 
-    if (res != CA_STATUS_OK)
+    if (CA_WIFI == connType)
     {
-        printf("find resource error:%d !!\n", res);
+        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;
+        }
+        endpoint.connectivityType = CA_WIFI;
+        strncpy(endpoint.addressInfo.IP.ipAddress, remoteIPAddress, CA_IPADDR_SIZE);
+        endpoint.addressInfo.IP.port = 5283; /* 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
+    else if (CA_EDR == connType)
     {
-        printf("find resource for %s URI\n", buf);
+        //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;
+        }
+
+        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;
 
-    printf("=============================================\n");
-}
+        //Get the device address from user
+        char deviceaddress[100] = {0};
+        printf("Enter the device address: \n");
+        scanf("%s", deviceaddress);
 
-void send_request()
-{
-    char buf[MAX_BUF_LEN];
+        if (strlen(deviceaddress) == 0)
+        {
+            printf("Invlaid device address\n");
+            return;
+        }
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+        //Get the service uuid from user
+        char uuid[100] = {0};
+        printf("Enter the service uuid: \n");
+        scanf("%s", uuid);
 
-    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 : ");
+        if (strlen(uuid) == 0)
+        {
+            printf("Invlaid service uuid\n");
+            return;
+        }
 
-    gets(buf);
+        endpoint.connectivityType = CA_LE;
+        strncpy(endpoint.addressInfo.BT.btMacAddress, deviceaddress, CA_MACADDR_SIZE - 1);
+        endpoint.addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
+        endpoint.resourceUri = strdup(uuid);
 
-    // create remote endpoint
-    CARemoteEndpoint_t *endpoint = NULL;
-    CAResult_t res = CACreateRemoteEndpoint(buf, &endpoint);
+        tempConnectivityHandlers->handler.sendData(&endpoint, coapData, strlen(coapData));
+        printf("Sent Unicast data \n");
+        free(endpoint.resourceUri);
+    }
 
-    if (res != CA_STATUS_OK)
+    return 1;
+}
+
+int16_t interfaceSendMulticastData(CAConnectivityType_t connType)
+{
+    ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
+    if (NULL == tempConnectivityHandlers)
     {
-        printf("create remote endpoint error!!");
-        CADestroyRemoteEndpoint(endpoint);
-        return;
+        printf("None of the interface is initialized\n");
+        return 0;
     }
 
-    // create token
-    CAToken_t token = NULL;
-    res = CAGenerateToken(&token);
-
-    if (res != CA_STATUS_OK)
+    while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
     {
-        printf("token generate error!!");
-        token = NULL;
+        tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
     }
 
-    printf("generated token %s\n", (token != NULL) ? token : "");
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf( "No interface handler for type %d", connType);
+        return 0;
+    }
 
-    CAInfo_t requestData;
-    memset(&requestData, 0, sizeof(CAInfo_t));
-    requestData.token = token;
-    requestData.payload = "Temp Json Payload";
+    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));
+    }
+}
 
-    CARequestInfo_t requestInfo;
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
+void interfaceReadData(CAConnectivityType_t connType)
+{
+    ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf("None of the interface is initialized\n");
+        return;
+    }
 
-    // send request
-    CASendRequest(endpoint, &requestInfo);
+    while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+    {
+        tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+    }
 
-    if (token != NULL)
+    if (NULL == tempConnectivityHandlers)
     {
-        CADestroyToken(token);
+        printf( "No interface handler for type %d", connType);
+        return;
     }
 
-    // destroy remote endpoint
-    if (endpoint != NULL)
+    if (CA_STATUS_OK != tempConnectivityHandlers->handler.readData())
     {
-        CADestroyRemoteEndpoint(endpoint);
+        printf("Failed to Read Data\n");
+        return;
     }
 
-    printf("=============================================\n");
+    printf("Read Data is successfull\n");
+    return;
 }
 
-void advertise_resource()
+void interfaceGetNetworkInfo(CAConnectivityType_t connType)
 {
-    char buf[MAX_BUF_LEN];
+    int i = 0;
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+    ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf("None of the interface is initialized\n");
+        return;
+    }
 
-    printf("\n=============================================\n");
-    printf("uri : ");
+    while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+    {
+        tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
+    }
 
-    scanf("%s", buf);
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf( "No interface handler for type %d", connType);
+        return;
+    }
 
-    int optionNum = 0;
-    char optionData[MAX_OPT_LEN];
+    //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;
+    }
 
-    printf("Option Num : ");
-    scanf("%d", &optionNum);
-    CAHeaderOption_t *headerOpt;
+    if (0 >= size || info == NULL)
+    {
+        printf("No network found !!!\n");
+        return;
+    }
 
-    if (optionNum > 0)
+    printf("Network Information: \n");
+    for (; i < size; i++)
     {
-        headerOpt = (CAHeaderOption_t *) malloc(sizeof(CAHeaderOption_t) * optionNum);
-        if (NULL == headerOpt)
+        if (connType == CA_WIFI)
         {
-            printf("memory allocation failed!\n");
-            return;
+            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);
         }
-        memset(headerOpt, 0, sizeof(CAHeaderOption_t) * optionNum);
     }
+}
 
-    int i;
-    for (i = 0; i < optionNum; i++)
+int16_t interfaceStopAdapter(CAConnectivityType_t connType)
+{
+    ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
+    if (NULL == tempConnectivityHandlers)
     {
-        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, MAX_OPT_LEN);
-        printf("[%d] inputed option : ID : %d, data : %s\n", i + 1, optionID, optionData);
+        printf("None of the interface is initialized\n");
+        return 0;
+    }
 
-        headerOpt[i].optionLength = (uint16_t) strlen(optionData);
+    while (tempConnectivityHandlers && tempConnectivityHandlers->type != connType)
+    {
+        tempConnectivityHandlers = tempConnectivityHandlers->nextHandler;
     }
-    printf("\n=============================================\n");
 
-    CAAdvertiseResource(buf, headerOpt, (uint8_t) optionNum);
+    if (NULL == tempConnectivityHandlers)
+    {
+        printf( "No interface handler for type %d", connType);
+        return 0;
+    }
 
-    free(headerOpt);
+    if (CA_STATUS_OK != tempConnectivityHandlers->handler.stopAdapter())
+    {
+        printf("Failed to Stop adapter\n");
+        return 0;
+    }
 
+    printf("Stopped the adapter\n");
+    return 1;
 }
 
-void send_notification()
+void testInitializeInterface()
 {
-    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 : ");
+    printf("testInitializeInterface Entry\n");
 
-    gets(buf);
-
-    // create remote endpoint
-    CARemoteEndpoint_t *endpoint = NULL;
-    CAResult_t res = CACreateRemoteEndpoint(buf, &endpoint);
-
-    if (res != CA_STATUS_OK)
+    int16_t type = selectConnectivityType();
+    if (0 >= type || 3 < type)
     {
-        printf("create remote endpoint error!!");
-        CADestroyRemoteEndpoint(endpoint);
+        printf("Invalid selection...\n");
         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_CONTENT;
-    responseInfo.info = respondeData;
-
-    // send request
-    CASendNotification(endpoint, &responseInfo);
-
-    // destroy remote endpoint
-    if (endpoint != NULL)
+    switch (type)
     {
-        CADestroyRemoteEndpoint(endpoint);
+#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");
     }
-    printf("\n=============================================\n");
 }
 
-void select_network()
+void testTerminateInterface()
 {
-    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 : ");
+    int16_t type = selectConnectivityType();
+    if (0 >= type || 3 < type)
+    {
+        printf("Invalid selection...\n");
+        return;
+    }
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-    gets(buf);
+#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
 
-    int number = buf[0] - '0';
+    ConnectivityHandlerList *currentConnectivityHandler = gConnectivityHandlers;
+    ConnectivityHandlerList *prevConnectivityHandler = NULL;
 
-    number = (number < 0 || number > 3) ? 1 : number;
+    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;
+}
 
-    CASelectNetwork(1 << number);
+void testStartAdapter()
+{
+    int type = selectConnectivityType();
+    if (0 >= type || 3 < type)
+    {
+        printf("Invalid selection...\n");
+        return;
+    }
 
-    printf("=============================================\n");
+    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 unselect_network()
+void testStartServer(int serverType)
 {
-    char buf[MAX_BUF_LEN];
+    int type = selectConnectivityType();
+    if (0 >= type || 3 < type)
+    {
+        printf("Invalid selection...\n");
+        return;
+    }
 
-    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 : ");
+    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");
+    }
+}
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
-    gets(buf);
+void testSendUnicastData()
+{
+    int16_t type = selectConnectivityType();
+    if (0 >= type || 3 < type)
+    {
+        printf("Invalid selection...\n");
+        return;
+    }
 
-    int number = buf[0] - '0';
+    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");
+    }
+}
 
-    number = (number < 0 || number > 3) ? 1 : number;
+void testSendMulticastData()
+{
+    int16_t type = selectConnectivityType();
+    if (0 >= type || 3 < type)
+    {
+        printf("Invalid selection...\n");
+        return;
+    }
 
-    CAUnSelectNetwork(1 << number);
-    printf("Terminating...\n");
-    CATerminate();
-    //pthread_join(thread, NULL);
-    printf("=============================================\n");
+    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");
+    }
 }
 
-char get_menu()
+void testReadData(void)
 {
-    char buf[MAX_BUF_LEN];
-
-    printf("\n=============================================\n");
-    printf("\t\tMenu\n");
-    printf("\ti : Initialize\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("\tn : select network\n");
-    printf("\tx : unselect network\n");
-    printf("\th : handle request response\n");
-    printf("\tt : terminate\n");
-    printf("\tq : quit\n");
-    printf("=============================================\n");
-    printf("select : ");
+    int16_t type = selectConnectivityType();
+    if (0 >= type || 3 < type)
+    {
+        printf("Invalid selection...\n");
+        return;
+    }
 
-    memset(buf, 0, sizeof(char) * MAX_BUF_LEN);
+    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");
+    }
+}
 
-    gets(buf);
+void testGetNetworkInfo(void)
+{
+    int16_t type = selectConnectivityType();
+    if (0 >= type || 3 < type)
+    {
+        printf("Invalid selection...\n");
+        return;
+    }
 
-    return buf[0];
+    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 handle_request_response()
+void testStopAdapter()
 {
-    printf("handle_request_response\n");
-    CAHandleRequestResponse();
+    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");
+    }
 }
 
-void request_handler(const CARemoteEndpoint_t* object, const CARequestInfo_t* requestInfo)
+#ifdef BT_ADAPTER_TEST
+void testInitializeBTInterface(void)
 {
+    printf("Initiazing EDR\n");
 
-    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 : "");
+    printf("Initializing BT Adapter threadpool\n");
+    initializeThreadPool(CA_EDR);
 
-    if (requestInfo->info.options)
+    //Start bluetooth communication adapter
+    CAResult_t err = CAInitializeEDR(interfaceRegisterCallback, networkPacketHandler,
+                                     networkInterfaceCallback, gBTThreadPool);
+    if (CA_STATUS_OK != err && CA_ADAPTER_NOT_ENABLED != err)
     {
-        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("Failed to initialize bluetooth communication adapter!\n");
     }
+}
+
+void testTerminateBTInterface(void)
+{
+    printf("Terminating EDR\n");
 
-    printf("send response with URI\n");
-    send_response(object, (requestInfo != NULL) ? requestInfo->info.token : "");
+    //Terminate the Bluetooth communication adapter
+    CATerminateEDR();
 
+    printf( "Terminating BT Adapter thread pool");
+    u_thread_pool_free(gBTThreadPool);
 }
+#endif //BT_ADAPTER_TEST
 
-void response_handler(const CARemoteEndpoint_t* object, const CAResponseInfo_t* responseInfo)
+#ifdef WIFI_ADAPTER_TEST
+void testInitializeWIFIInterface(void)
 {
+    printf("testInitializeWIFIInterface IN\n");
 
-    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 : "");
+    printf("Initializing WIFI adapter threadpool\n");
+    initializeThreadPool(CA_WIFI);
 
-    if (responseInfo->info.options)
+    //Start Wifi communication adapter
+    if (0 != CAInitializeWifi(interfaceRegisterCallback, networkPacketHandler,
+                              networkInterfaceCallback, gWiFiThreadPool))
     {
-        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);
-        }
+        printf("testInitializeWIFIInterface Failed to initialize bluetooth communication adapter\n");
+        return;
     }
 
+    printf("testInitializeWIFIInterface OUT\n");
 }
 
-void send_response(CARemoteEndpoint_t *endpoint, CAToken_t request_token)
+void testTerminateWIFIInterface(void)
 {
+    printf("testTerminateWIFIInterface IN\n");
+
+    // Stop if Wifi communication adapter is running
+    interfaceStopAdapter(CA_WIFI);
 
-    printf("\n=============================================\n");
+    // Freeing threadpool for wifi communication adapter
+    printf( "Terminating WIFI Adapter thread pool");
+    u_thread_pool_free(gWiFiThreadPool);
 
-    CAInfo_t responseData;
-    //responseData = (CAInfo*) malloc(sizeof(CAInfo));
-    memset(&responseData, 0, sizeof(CAInfo_t));
-    responseData.token = request_token;
-    responseData.payload = "response payload";
+    //Terminate the Wifi communication adapter
+    CATerminateWIfI();
 
-    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("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);
 
-    printf("=============================================\n");
+    //Start bluetooth communication adapter
+    if (0 != CAInitializeLE(interfaceRegisterCallback, networkPacketHandler,
+                            networkInterfaceCallback, gLEThreadPool))
+    {
+        printf("testInitializeBLEInterface Failed due to CAInitializeLE\n");
+        return;
+    }
 
+    printf("testInitializeBLEInterface OUT\n");
 }
 
-void send_request_tmp(CARemoteEndpoint_t *endpoint, CAToken_t token)
+void testTerminateBLEInterface(void)
 {
+    printf("testTerminateBLEInterface IN\n");
 
-    printf("\n=============================================\n");
+    //Terminate the BLE server & Client
+    CATerminateLE();
 
-    CAInfo_t requestData;
-    memset(&requestData, 0, sizeof(CAInfo_t));
-    requestData.token = token;
-    requestData.payload = "Temp Json Payload";
+    printf( "Terminating BLE Adapter thread pool");
+    u_thread_pool_free(gLEThreadPool);
 
-    CARequestInfo_t requestInfo;
-    memset(&requestInfo, 0, sizeof(CARequestInfo_t));
-    requestInfo.method = CA_GET;
-    requestInfo.info = requestData;
+    printf("testTerminateBLEInterface OUT\n");
+}
+#endif //BLE_ADAPTER_TEST
 
-    // send request
-    endpoint->connectivityType = CA_WIFI;
-    CASendRequest(endpoint, &requestInfo);
+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;
 
-    printf("=============================================\n");
 
+    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;
 }
 
-void terminate()
+int main(int argc, char *argv[])
 {
-    unselect_network();
+    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;
 }
+
index bd95856..9ea21a3 100644 (file)
 
 #define MOD_NAME "TizenSample"
 
-//Comment any below for blocking testing of specific adapters
+/**
+ * Enable/disable one or more of the following macros to enable/disable 
+ * functionality of that particular adapter type in the interfacesample.
+ */
 //#define WIFI_ADAPTER_TEST
 #define BT_ADAPTER_TEST
 //#define BLE_ADAPTER_TEST
@@ -79,34 +82,34 @@ static ConnectivityHandlerList *gConnectivityHandlers = NULL;
 void initializeThreadPool(CAConnectivityType_t type)
 {
 #ifdef BT_ADAPTER_TEST
-       if (CA_EDR == type && NULL == gBTThreadPool)
-       {
+    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_WIFI == type && NULL == gWiFiThreadPool)
+    {
         if (CA_STATUS_OK != u_thread_pool_init(3, &gWiFiThreadPool))
         {
             printf("Failed to create thread pool for BT adapter!\n");
             return;
         }
-       }
+    }
 #endif
 #ifdef BLE_ADAPTER_TEST
-       if (CA_LE == type && NULL == gLEThreadPool)
-       {
+    if (CA_LE == type && NULL == gLEThreadPool)
+    {
         if (CA_STATUS_OK != u_thread_pool_init(3, &gLEThreadPool))
         {
             printf("Failed to create thread pool for BT adapter!\n");
             return;
         }
-       }
+    }
 #endif
 }
 
@@ -167,14 +170,14 @@ void networkPacketHandler(CARemoteEndpoint_t *object, void *data, uint32_t dataL
     }
     else if (CA_LE == object->connectivityType)
     {
-               printf(object->addressInfo.LE.leMacAddress);
+        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("\nReceived Data [Length: %d]: %s\n", dataLength, (char *)data);
     printf("networkPacketHandler Exit in Sample\n");
 }
 
@@ -302,9 +305,6 @@ int16_t interfaceMulticastStartServer(CAConnectivityType_t connType, int serverT
         case 2: //Listening server
             startServer = tempConnectivityHandlers->handler.startListenServer;
             break;
-        case 3: //Notification server
-            startServer = tempConnectivityHandlers->handler.startNotifyServer;
-            break;
     }
 
     if (startServer)
@@ -382,7 +382,7 @@ int16_t interfaceSendUnicastData(CAConnectivityType_t connType)
         endpoint.resourceUri = NULL;
 
         printf("Sent Unicast data to device: %s\n", endpoint.addressInfo.BT.btMacAddress);
-        tempConnectivityHandlers->handler.sendData(&endpoint, coapData, strlen(coapData)+1);
+        tempConnectivityHandlers->handler.sendData(&endpoint, coapData, strlen(coapData) + 1);
     }
     else if (CA_LE == connType)
     {
@@ -424,106 +424,6 @@ int16_t interfaceSendUnicastData(CAConnectivityType_t connType)
     return 1;
 }
 
-void interfaceSendNotification(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\n", connType);
-        return;
-    }
-
-    if (CA_WIFI == connType)
-    {
-        CARemoteEndpoint_t remoteEndpoint;
-        tempConnectivityHandlers->handler.sendNotification(&remoteEndpoint, coapData, strlen(coapData));
-    }
-    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;
-        }
-
-        //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;
-        }
-
-        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 = strdup(uuid);
-
-        tempConnectivityHandlers->handler.sendNotification(&endpoint, coapData, strlen(coapData));
-        printf("Sent Unicast data \n");
-        free(endpoint.resourceUri);
-    }
-    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;
-        }
-
-        //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;
-        }
-
-        endpoint.connectivityType = CA_LE;
-        strncpy(endpoint.addressInfo.BT.btMacAddress, deviceaddress, CA_MACADDR_SIZE - 1);
-        endpoint.addressInfo.BT.btMacAddress[CA_MACADDR_SIZE - 1] = '\0';
-        endpoint.resourceUri = strdup(uuid);
-
-        tempConnectivityHandlers->handler.sendNotification(&endpoint, coapData, strlen(coapData));
-        printf("Sent Unicast data \n");
-        free(endpoint.resourceUri);
-        printf("Feature is not implemented !!\n");
-    }
-}
-
 int16_t interfaceSendMulticastData(CAConnectivityType_t connType)
 {
     ConnectivityHandlerList *tempConnectivityHandlers = gConnectivityHandlers;
@@ -881,7 +781,7 @@ void testSendUnicastData()
     }
 }
 
-void testSendNotification()
+void testSendMulticastData()
 {
     int16_t type = selectConnectivityType();
     if (0 >= type || 3 < type)
@@ -895,21 +795,21 @@ void testSendNotification()
 #ifdef WIFI_ADAPTER_TEST
         case 1: //WIFI
             {
-                interfaceSendNotification(CA_WIFI);
+                interfaceSendMulticastData(CA_WIFI);
             }
             break;
 #endif
 #ifdef BT_ADAPTER_TEST
         case 2:   //BT
             {
-                interfaceSendNotification(CA_EDR);
+                interfaceSendMulticastData(CA_EDR);
             }
             break;
 #endif
 #ifdef BLE_ADAPTER_TEST
         case 3: //BLE
             {
-                interfaceSendNotification(CA_LE);
+                interfaceSendMulticastData(CA_LE);
             }
             break;
 #endif
@@ -918,7 +818,7 @@ void testSendNotification()
     }
 }
 
-void testSendMulticastData()
+void testReadData(void)
 {
     int16_t type = selectConnectivityType();
     if (0 >= type || 3 < type)
@@ -932,21 +832,21 @@ void testSendMulticastData()
 #ifdef WIFI_ADAPTER_TEST
         case 1: //WIFI
             {
-                interfaceSendMulticastData(CA_WIFI);
+                interfaceReadData(CA_WIFI);
             }
             break;
 #endif
 #ifdef BT_ADAPTER_TEST
         case 2:   //BT
             {
-                interfaceSendMulticastData(CA_EDR);
+                interfaceReadData(CA_EDR);
             }
             break;
 #endif
 #ifdef BLE_ADAPTER_TEST
         case 3: //BLE
             {
-                interfaceSendMulticastData(CA_LE);
+                interfaceReadData(CA_LE);
             }
             break;
 #endif
@@ -955,43 +855,6 @@ void testSendMulticastData()
     }
 }
 
-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();
@@ -1071,12 +934,12 @@ void testInitializeBTInterface(void)
 {
     printf("Initiazing EDR\n");
 
-       printf("Initializing BT Adapter threadpool\n");
-       initializeThreadPool(CA_EDR);
+    printf("Initializing BT Adapter threadpool\n");
+    initializeThreadPool(CA_EDR);
 
     //Start bluetooth communication adapter
     CAResult_t err = CAInitializeEDR(interfaceRegisterCallback, networkPacketHandler,
-                             networkInterfaceCallback, gBTThreadPool);
+                                     networkInterfaceCallback, gBTThreadPool);
     if (CA_STATUS_OK != err && CA_ADAPTER_NOT_ENABLED != err)
     {
         printf("Failed to initialize bluetooth communication adapter!\n");
@@ -1100,8 +963,8 @@ void testInitializeWIFIInterface(void)
 {
     printf("testInitializeWIFIInterface IN\n");
 
-       printf("Initializing WIFI adapter threadpool\n");
-       initializeThreadPool(CA_WIFI);
+    printf("Initializing WIFI adapter threadpool\n");
+    initializeThreadPool(CA_WIFI);
 
     //Start Wifi communication adapter
     if (0 != CAInitializeWifi(interfaceRegisterCallback, networkPacketHandler,
@@ -1138,8 +1001,8 @@ void testInitializeBLEInterface(void)
 {
     printf("testInitializeBLEInterface IN\n");
 
-       printf("Initializing BLE adapter threadpool\n");
-       initializeThreadPool(CA_LE);
+    printf("Initializing BLE adapter threadpool\n");
+    initializeThreadPool(CA_LE);
 
     //Start bluetooth communication adapter
     if (0 != CAInitializeLE(interfaceRegisterCallback, networkPacketHandler,
@@ -1179,14 +1042,12 @@ static void testPrintHelp(void)
     printf("|  b - Stop adapter                                                   |\n");
     printf("|  sd- Start Discovery Server                                         |\n");
     printf("|  sl- Start Listening Server                                         |\n");
-    printf("|  sn- Start Notification Server                                      |\n");
     printf("|  u - Send Unicast Data                                              |\n");
     printf("|  m - Send Multicast Data                                            |\n");
-    printf("|  n - Send Notification 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("|  h - Help menu.                                                     |\n");
     printf(" =====================================================================\n");
 }
 
@@ -1244,10 +1105,6 @@ static gboolean testThread(GIOChannel *source, GIOCondition condition , gpointer
                 {
                     testStartServer(2);
                 }
-                if (buf[1] == 'n')
-                {
-                    testStartServer(3);
-                }
             }
             break;
         case 'u':
@@ -1256,9 +1113,6 @@ static gboolean testThread(GIOChannel *source, GIOCondition condition , gpointer
         case 'm':
             testSendMulticastData();
             break;
-        case 'n':
-            testSendNotification();
-            break;
         case 'r':
             testReadData();
             break;
index 915078e..71b192b 100644 (file)
 #include "caadapterutils.h"
 
 #include <string.h>
-#ifndef __ARDUINO__
+
 #include "oic_malloc.h"
-#endif //#ifndef __ARDUINO__
+
 #define CA_ADAPTER_UTILS_TAG "CA_ADAPTER_UTILS"
 
 CALocalConnectivity_t *CAAdapterCreateLocalEndpoint(CAConnectivityType_t type, const char *address,
         const char *interfaceName)
 {
-    CALocalConnectivity_t *info = (CALocalConnectivity_t *) OICMalloc(
-            sizeof(CALocalConnectivity_t));
+    CALocalConnectivity_t *info = (CALocalConnectivity_t *)
+                                  OICMalloc(sizeof(CALocalConnectivity_t));
     if (NULL == info)
     {
         OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
@@ -65,8 +65,8 @@ CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(CALocalConnectivity_t *connect
 {
     VERIFY_NON_NULL_RET(connectivity, CA_ADAPTER_UTILS_TAG, "connectivity is NULL", NULL);
 
-    CALocalConnectivity_t *info = (CALocalConnectivity_t *) OICMalloc(
-            sizeof(CALocalConnectivity_t));
+    CALocalConnectivity_t *info = (CALocalConnectivity_t *)
+                                  OICMalloc(sizeof(CALocalConnectivity_t));
     if (NULL == info)
     {
         OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
@@ -88,7 +88,7 @@ CALocalConnectivity_t *CAAdapterCopyLocalEndpoint(CALocalConnectivity_t *connect
         info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
     }
     else if ((CA_WIFI == info->type || CA_ETHERNET == info->type)
-            && strlen(connectivity->addressInfo.IP.ipAddress))
+             && strlen(connectivity->addressInfo.IP.ipAddress))
     {
         strncpy(info->addressInfo.IP.ipAddress, connectivity->addressInfo.IP.ipAddress,
                 CA_IPADDR_SIZE - 1);
@@ -109,7 +109,8 @@ void CAAdapterFreeLocalEndpoint(CALocalConnectivity_t *localEndpoint)
 CARemoteEndpoint_t *CAAdapterCreateRemoteEndpoint(CAConnectivityType_t type, const char *address,
         const char *resourceUri)
 {
-    CARemoteEndpoint_t *info = (CARemoteEndpoint_t *) OICMalloc(sizeof(CARemoteEndpoint_t));
+    CARemoteEndpoint_t *info = (CARemoteEndpoint_t *)
+                               OICMalloc(sizeof(CARemoteEndpoint_t));
     if (NULL == info)
     {
         OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
@@ -149,7 +150,8 @@ CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(const CARemoteEndpoint_t *remote
 {
     VERIFY_NON_NULL_RET(remoteEndpoint, CA_ADAPTER_UTILS_TAG, "Remote endpoint is NULL", NULL);
 
-    CARemoteEndpoint_t *info = (CARemoteEndpoint_t *) OICMalloc(sizeof(CARemoteEndpoint_t));
+    CARemoteEndpoint_t *info = (CARemoteEndpoint_t *)
+                               OICMalloc(sizeof(CARemoteEndpoint_t));
     if (NULL == info)
     {
         OIC_LOG_V(ERROR, CA_ADAPTER_UTILS_TAG, "Memory allocation failed !");
@@ -171,7 +173,7 @@ CARemoteEndpoint_t *CAAdapterCopyRemoteEndpoint(const CARemoteEndpoint_t *remote
         info->addressInfo.LE.leMacAddress[CA_MACADDR_SIZE - 1] = '\0';
     }
     else if ((CA_WIFI == info->connectivityType || CA_ETHERNET == info->connectivityType)
-            && strlen(remoteEndpoint->addressInfo.IP.ipAddress))
+             && strlen(remoteEndpoint->addressInfo.IP.ipAddress))
     {
         strncpy(info->addressInfo.IP.ipAddress, remoteEndpoint->addressInfo.IP.ipAddress,
                 CA_IPADDR_SIZE - 1);
index 2543d30..c345d70 100644 (file)
@@ -36,8 +36,8 @@ CAResult_t CAAdapterInitializeMessageQueue(CAAdapterMessageQueue_t **queueHandle
     OIC_LOG(DEBUG, TAG, "IN");
     VERIFY_NON_NULL(queueHandle, TAG, "Invalid queue handle container");
 
-    CAAdapterMessageQueue_t *queuePtr = (CAAdapterMessageQueue_t *) OICMalloc(
-            sizeof(CAAdapterMessageQueue_t));
+    CAAdapterMessageQueue_t *queuePtr = (CAAdapterMessageQueue_t *)
+                                        OICMalloc(sizeof(CAAdapterMessageQueue_t));
     if (!queuePtr)
     {
         OIC_LOG_V(ERROR, TAG, "Out of memory!");
@@ -53,8 +53,14 @@ CAResult_t CAAdapterInitializeMessageQueue(CAAdapterMessageQueue_t **queueHandle
         OICFree(queuePtr);
         return CA_MEMORY_ALLOC_FAILED;
     }
-    queuePtr->begin = NULL;
-    queuePtr->end = NULL;
+
+    queuePtr->queue = u_queue_create();
+    if (NULL == queuePtr->queue)
+    {
+        u_mutex_free(queuePtr->queueMutex);
+        OICFree(queuePtr);
+        return CA_MEMORY_ALLOC_FAILED;
+    }
     *queueHandle = queuePtr;
 
     OIC_LOG(DEBUG, TAG, "OUT");
@@ -83,21 +89,17 @@ void CAAdapterTerminateMessageQueue(CAAdapterMessageQueue_t *queueHandle)
 {
     OIC_LOG(DEBUG, TAG, "IN");
     VERIFY_NON_NULL_VOID(queueHandle, TAG, "Invalid queue handle");
+    VERIFY_NON_NULL_VOID(queueHandle->queue, TAG, "Invalid queue");
     VERIFY_NON_NULL_VOID(queueHandle->queueMutex, TAG, "Invalid queue mutex");
-    CAAdapterMessage_t *messagePtr = NULL;
-    CAAdapterMessage_t *toRemove = NULL;
 
     u_mutex_lock(queueHandle->queueMutex);
-    messagePtr = queueHandle->begin;
-    while (messagePtr)
+    u_queue_message_t *messagePtr = NULL;
+    while ((messagePtr = u_queue_get_element(queueHandle->queue)))
     {
-        toRemove = messagePtr;
-        messagePtr = messagePtr->next;
-        CAAdapterFreeMessage(toRemove);
+        CAAdapterFreeMessage((CAAdapterMessage_t *)messagePtr->msg);
+        OICFree(messagePtr);
     }
 
-    queueHandle->begin = NULL;
-    queueHandle->end = NULL;
     u_mutex_unlock(queueHandle->queueMutex);
     u_mutex_free(queueHandle->queueMutex);
     queueHandle->queueMutex = NULL;
@@ -107,15 +109,17 @@ void CAAdapterTerminateMessageQueue(CAAdapterMessageQueue_t *queueHandle)
 }
 
 CAResult_t CAAdapterEnqueueMessage(CAAdapterMessageQueue_t *queueHandle,
-        const CARemoteEndpoint_t *remoteEndpoint, void *data, uint32_t dataLen)
+                                   const CARemoteEndpoint_t *remoteEndpoint,
+                                   void *data, uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TAG, "IN");
     VERIFY_NON_NULL(queueHandle, TAG, "Invalid queue handle");
+    VERIFY_NON_NULL(queueHandle->queue, TAG, "Invalid queue");
     VERIFY_NON_NULL(queueHandle->queueMutex, TAG, "Invalid queue mutex");
     VERIFY_NON_NULL(data, TAG, "Invalid data");
 
-    CAAdapterMessage_t *adapterMessage = (CAAdapterMessage_t *) OICMalloc(
-            sizeof(CAAdapterMessage_t));
+    CAAdapterMessage_t *adapterMessage = (CAAdapterMessage_t *)
+                                         OICMalloc(sizeof(CAAdapterMessage_t));
     if (!adapterMessage)
     {
         OIC_LOG_V(ERROR, TAG, "Out of memory!");
@@ -124,7 +128,7 @@ CAResult_t CAAdapterEnqueueMessage(CAAdapterMessageQueue_t *queueHandle,
     memset((void *) adapterMessage, 0, sizeof(CAAdapterMessage_t));
 
     // Copy data
-    adapterMessage->data = (void *) OICMalloc(dataLen);
+    adapterMessage->data = (void *)OICMalloc(dataLen);
     if (adapterMessage->data == NULL)
     {
         OIC_LOG_V(ERROR, TAG, "Out of memory!!!");
@@ -142,54 +146,55 @@ CAResult_t CAAdapterEnqueueMessage(CAAdapterMessageQueue_t *queueHandle,
         if (NULL == adapterMessage->remoteEndpoint)
         {
             OIC_LOG_V(ERROR, TAG, "Out of memory.!!");
-            OICFree(adapterMessage->data);
             CAAdapterFreeMessage(adapterMessage);
             return CA_MEMORY_ALLOC_FAILED;
         }
     }
+
     //Insert at end of queue
-    u_mutex_lock(queueHandle->queueMutex);
-    if (queueHandle->end)
+    u_queue_message_t *queueMessage = (u_queue_message_t *)OICMalloc(sizeof(u_queue_message_t));
+    if (!queueMessage)
     {
-        queueHandle->end->next = adapterMessage;
-        queueHandle->end = adapterMessage;
+        OIC_LOG_V(ERROR, TAG, "Out of memory.!!");
+        CAAdapterFreeMessage(adapterMessage);
+        return CA_MEMORY_ALLOC_FAILED;
     }
-    else
+    queueMessage->msg = (void *)adapterMessage;
+    queueMessage->size = sizeof(CAAdapterMessage_t);
+
+    u_mutex_lock(queueHandle->queueMutex);
+    CAResult_t ret = u_queue_add_element(queueHandle->queue, queueMessage);
+    if (ret != CA_STATUS_OK)
     {
-        queueHandle->begin = adapterMessage;
-        queueHandle->end = adapterMessage;
+        CAAdapterFreeMessage(adapterMessage);
+        OICFree(queueMessage);
     }
     u_mutex_unlock(queueHandle->queueMutex);
     OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
+    return ret;
 }
 
 CAResult_t CAAdapterDequeueMessage(CAAdapterMessageQueue_t *queueHandle,
-        CAAdapterMessage_t **message)
+                                   CAAdapterMessage_t **message)
 {
     OIC_LOG(DEBUG, TAG, "IN");
     VERIFY_NON_NULL(queueHandle, TAG, "Invalid queue handle");
+    VERIFY_NON_NULL(queueHandle->queue, TAG, "Invalid queue");
     VERIFY_NON_NULL(queueHandle->queueMutex, TAG, "Invalid queue mutex");
     VERIFY_NON_NULL(message, TAG, "Invalid message handle");
+
+    CAResult_t ret = CA_STATUS_FAILED;
     u_mutex_lock(queueHandle->queueMutex);
-    if (queueHandle->begin)
-    {
-        *message = queueHandle->begin;
-        queueHandle->begin = queueHandle->begin->next;
-        if (queueHandle->begin == NULL)
-        {
-            queueHandle->end = NULL;
-        }
-        // keep next as NULL for upper layer
-        (*message)->next = NULL;
-    }
-    else
+    u_queue_message_t *messagePtr = u_queue_get_element(queueHandle->queue);
+    if (messagePtr)
     {
-        u_mutex_unlock(queueHandle->queueMutex);
-        return CA_STATUS_FAILED;
+        ret = CA_STATUS_OK;
+        *message = (CAAdapterMessage_t *)messagePtr->msg;
+        OICFree(messagePtr);
     }
     u_mutex_unlock(queueHandle->queueMutex);
+
     OIC_LOG(DEBUG, TAG, "OUT");
-    return CA_STATUS_OK;
+    return ret;
 }
 
index 28efbc5..8735d96 100644 (file)
@@ -48,8 +48,6 @@ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
     handler.startDiscoverServer = CAStartEDRDiscoveryServer;
     handler.sendData = CASendEDRUnicastData;
     handler.sendDataToAll = CASendEDRMulticastData;
-    handler.startNotifyServer = CAStartEDRNotifyServer;
-    handler.sendNotification = CASendEDRNotification;
     handler.GetnetInfo = CAGetEDRInterfaceInformation;
     handler.readData = CAReadEDRData;
     handler.stopAdapter = CAStopEDR;
@@ -95,20 +93,6 @@ uint32_t CASendEDRMulticastData(void* data, uint32_t dataLen)
     return 0;
 }
 
-CAResult_t CAStartEDRNotifyServer()
-{
-    OIC_LOG_V(DEBUG, TAG, "CAStartEDRNotifyServer");
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendEDRNotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendEDRNotification");
-
-    return 0;
-}
-
 CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t** info, uint32_t* size)
 {
     OIC_LOG_V(DEBUG, TAG, "CAGetEDRInterfaceInformation");
index 1d86e88..7e872cc 100644 (file)
@@ -19,8 +19,8 @@
  ******************************************************************/
 
 /**
- * @file    cabtclient.c
- * @brief   This    file provides the APIs to establish RFCOMM connection with remote bluetooth device
+ * @file  cabtclient.c
+ * @brief  This file provides the APIs to establish RFCOMM connection with remote bluetooth device
  */
 
 #include "cabtclient.h"
@@ -33,17 +33,19 @@ CAResult_t CABTClientConnect(const char *remoteAddress, const char *serviceUUID)
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
     int err = BT_ERROR_NONE;
+    int addressLen = 0;
 
     VERIFY_NON_NULL(remoteAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
     VERIFY_NON_NULL(serviceUUID, BLUETOOTH_ADAPTER_TAG, "Service UUID is null");
 
-    if (0 >= strlen(remoteAddress))
+    addressLen = strlen(remoteAddress);
+    if (0 == addressLen || CA_MACADDR_SIZE - 1 != addressLen)
     {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: Empty remote address");
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: Invalid remote address");
         return  CA_STATUS_INVALID_PARAM;
     }
 
-    if (0 >= strlen(serviceUUID))
+    if (0 == strlen(serviceUUID))
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: Empty service uuid");
         return  CA_STATUS_INVALID_PARAM;
@@ -52,8 +54,8 @@ CAResult_t CABTClientConnect(const char *remoteAddress, const char *serviceUUID)
     if (BT_ERROR_NONE != (err = bt_socket_connect_rfcomm(remoteAddress, serviceUUID)))
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG,
-                  "Failed to connect!, address [%s] uuid [%s] error num [%x]",
-                  remoteAddress, serviceUUID, err);
+                  "Failed to connect!, address [%s] error num [%x]",
+                  remoteAddress, err);
         return CA_STATUS_FAILED;
     }
 
@@ -61,3 +63,25 @@ CAResult_t CABTClientConnect(const char *remoteAddress, const char *serviceUUID)
     return CA_STATUS_OK;
 }
 
+CAResult_t CABTClientDisconnect(const int32_t clientID)
+{
+       OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
+    //Input validation
+    if (0 > clientID)
+    {
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: negative client id");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    int err = BT_ERROR_NONE;
+    if (BT_ERROR_NONE != (err = bt_socket_disconnect_rfcomm(clientID)))
+    {
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed close rfcomm client socket!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;    
+    }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
+}
+
index a385488..3b6f5e0 100644 (file)
@@ -19,8 +19,8 @@
  ******************************************************************/
 
 /**
- * @file    cabtclient.h
- * @brief   This    file provides the APIs to establish RFCOMM connection with remote bluetooth device
+ * @file  cabtclient.h
+ * @brief  This file provides the APIs to establish RFCOMM connection with remote bluetooth device.
  */
 
 #ifndef __CA_BT_CLIENT_H_
@@ -40,17 +40,32 @@ extern "C"
  * @fn  CABTClientConnect
  * @brief  Establishes RFCOMM connection with remote bluetooth device
  *
- * @param  remoteAddress  The address of remote bluetooth device to which connection needs to be established
- * @param  serviceUUID  The UUID of service to which RFCOMM connection needs to established
+ * @param[in]  remoteAddress  The address of remote bluetooth device to which connection needs to be
+ *                                        established.
+ * @param[in]  serviceUUID  The UUID of service to which RFCOMM connection needs to established.
  *
- * @return  CA_STATUS_OK on success otherwise proper error code.
- * @retval  CA_STATUS_OK  Successful
- * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
- * @retval  CA_STATUS_FAILED Operation failed
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval  #CA_STATUS_FAILED Operation failed
  *
  */
 CAResult_t CABTClientConnect(const char *remoteAddress, const char *serviceUUID);
 
+/**
+ * @fn  CABTClientDisconnect
+ * @brief  Disconnect RFCOMM client socket connection
+ *
+ * @param[in]  clientID  The RFCOMM client socket file descriptor
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval  #CA_STATUS_FAILED Operation failed
+ *
+ */
+CAResult_t CABTClientDisconnect(const int32_t clientID);
+
 #ifdef __cplusplus
 } /* extern "C" */
 #endif
index f5e503b..15cf3e8 100644 (file)
@@ -19,8 +19,8 @@
  ******************************************************************/
 
 /**
- * @file    cabtdevicelist.c
- * @brief    This file provides APIs to access the discovered bluetooth device list
+ * @file  cabtdevicelist.c
+ * @brief  This file provides APIs to access the discovered bluetooth device list
  */
 
 #include "cabtdevicelist.h"
 #include "cabtutils.h"
 #include "logger.h"
 
-CAResult_t CAAddBTDeviceToList(BTDeviceList **deviceList, BTDevice *device)
-{
-    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
-
-    VERIFY_NON_NULL(deviceList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
-    VERIFY_NON_NULL(device, BLUETOOTH_ADAPTER_TAG, "Device is null");
-
-    BTDeviceList *node = (BTDeviceList *) OICMalloc(sizeof(BTDeviceList));
-    if (NULL == node)
-    {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Out of memory (device list)!");
-        return CA_MEMORY_ALLOC_FAILED;
-    }
-
-    node->device = device;
-    node->next = NULL;
-
-    if (NULL == *deviceList) //Empty list
-    {
-        *deviceList = node;
-    }
-    else //Add at front end
-    {
-        node->next = *deviceList;
-        *deviceList = node;
-    }
 
-    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
+/**
+ * @fn  CACreateBTDevice
+ * @brief  Creates #BTDevice for specified remote address and uuid.
+ *
+ */
+static CAResult_t CACreateBTDevice(const char *deviceAddress, const char *uuid, BTDevice **device);
 
-CAResult_t CARemoveBTDeviceFromList(BTDeviceList **deviceList, const char *remoteAddress)
-{
-    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
-    VERIFY_NON_NULL(deviceList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
-    VERIFY_NON_NULL(remoteAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
+/**
+ * @fn  CADestroyBTDevice
+ * @brief  Free all the memory associated with specified device.
+ *
+ */
+static void CADestroyBTDevice(BTDevice *device);
 
-    BTDeviceList *cur = NULL;
-    BTDeviceList *prev = NULL;
 
-    cur = *deviceList;
-    while (cur != NULL)
-    {
-        if (!strcasecmp(cur->device->remoteAddress, remoteAddress))
-        {
-            if (cur == *deviceList)
-            {
-                *deviceList = cur->next;
-
-                cur->next = NULL;
-                CAFreeBTDeviceList(cur);
-                return CA_STATUS_OK;
-            }
-            else
-            {
-                prev->next = cur->next;
+/**
+ * @fn  CADestroyBTData
+ * @brief  Free all the memory associated with specified data.
+ *
+ */
+static void CADestroyBTData(BTData *data);
 
-                cur->next = NULL;
-                CAFreeBTDeviceList(cur);
-                return CA_STATUS_OK;
-            }
-        }
-        else
-        {
-            prev = cur;
-            cur = cur->next;
-        }
-    }
 
-    OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Device not in the list !");
-    return CA_STATUS_FAILED;
-}
-
-CAResult_t CAGetBTDevice(BTDeviceList *deviceList, const char *remoteAddress, BTDevice **device)
+CAResult_t CACreateAndAddToDeviceList(BTDeviceList **deviceList, const char *deviceAddress,
+        const char *uuid, BTDevice **device)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
     VERIFY_NON_NULL(deviceList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
-    VERIFY_NON_NULL(remoteAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(deviceAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
     VERIFY_NON_NULL(device, BLUETOOTH_ADAPTER_TAG, "Device is null");
 
-    BTDeviceList *cur = deviceList;
-    *device = NULL;
-    while (cur != NULL)
+    if (CA_STATUS_OK != CACreateBTDevice(deviceAddress, uuid, device) || NULL == *device)
     {
-        if (!strcasecmp(cur->device->remoteAddress, remoteAddress))
-        {
-            *device = cur->device;
-            return CA_STATUS_OK;
-        }
-
-        cur = cur->next;
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid or Not bonded device!");
+        return CA_STATUS_FAILED;
     }
 
-    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT [Device not found!]");
-    return CA_STATUS_FAILED;
-}
-
-CAResult_t CAGetBTDeviceBySocketId(BTDeviceList *deviceList, int32_t socketFd, BTDevice **device)
-{
-    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
-
-    VERIFY_NON_NULL(deviceList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
-    VERIFY_NON_NULL(device, BLUETOOTH_ADAPTER_TAG, "Device is null");
-
-    BTDeviceList *cur = deviceList;
-    *device = NULL;
-    while (cur != NULL)
+    if (CA_STATUS_OK != CAAddBTDeviceToList(deviceList, *device))
     {
-        if (cur->device->socketFD == socketFd)
-        {
-            *device = cur->device;
-            return CA_STATUS_OK;
-        }
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to add in list!");
+
+        //Remove created BTDevice
+        CADestroyBTDevice(*device);
+        *device = NULL;
 
-        cur = cur->next;
+        return CA_STATUS_FAILED;
     }
 
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
-    return CA_STATUS_FAILED;
+    return CA_STATUS_OK;
 }
 
-CAResult_t CACreateBTDevice(const char *remoteAddress, const char *uuid, BTDevice **device)
+CAResult_t CACreateBTDevice(const char *deviceAddress, const char *uuid, BTDevice **device)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
-    VERIFY_NON_NULL(remoteAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(deviceAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
     VERIFY_NON_NULL(uuid, BLUETOOTH_ADAPTER_TAG, "uuid is null");
     VERIFY_NON_NULL(device, BLUETOOTH_ADAPTER_TAG, "Device is null");
 
@@ -167,9 +99,9 @@ CAResult_t CACreateBTDevice(const char *remoteAddress, const char *uuid, BTDevic
     }
 
     //Copy bluetooth address
-    if (remoteAddress && strlen(remoteAddress))
+    if (strlen(deviceAddress))
     {
-        (*device)->remoteAddress = strndup(remoteAddress, strlen(remoteAddress));
+        (*device)->remoteAddress = strndup(deviceAddress, strlen(deviceAddress));
         if (NULL == (*device)->remoteAddress)
         {
             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Out of memory (remote address)!");
@@ -181,13 +113,13 @@ CAResult_t CACreateBTDevice(const char *remoteAddress, const char *uuid, BTDevic
     }
 
     //Copy OIC service uuid
-    if (uuid && strlen(uuid))
+    if (strlen(uuid))
     {
         (*device)->serviceUUID = strndup(uuid, strlen(uuid));
         if (NULL == (*device)->serviceUUID)
         {
             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG,
-                      "[createBTDevice] Out of memory (service uuid)!");
+                    "[createBTDevice] Out of memory (service uuid)!");
 
             OICFree((*device)->remoteAddress);
             OICFree(*device);
@@ -204,79 +136,159 @@ CAResult_t CACreateBTDevice(const char *remoteAddress, const char *uuid, BTDevic
     return CA_STATUS_OK;
 }
 
-CAResult_t CACreateAndAddToDeviceList(BTDeviceList **devicList, const char *remoteAddress,
-                                      const char *serviceUUID, BTDevice **device)
+CAResult_t CAAddBTDeviceToList(BTDeviceList **deviceList, BTDevice *device)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
-    VERIFY_NON_NULL(devicList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
-    VERIFY_NON_NULL(remoteAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(deviceList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
     VERIFY_NON_NULL(device, BLUETOOTH_ADAPTER_TAG, "Device is null");
 
-    if (CA_STATUS_OK != CACreateBTDevice(remoteAddress, serviceUUID, device) || NULL == *device)
+    BTDeviceList *node = (BTDeviceList *) OICMalloc(sizeof(BTDeviceList));
+    if (NULL == node)
     {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid or Not bonded device!");
-        return CA_STATUS_FAILED;
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Out of memory (device list)!");
+        return CA_MEMORY_ALLOC_FAILED;
     }
 
-    if (CA_STATUS_OK != CAAddBTDeviceToList(devicList, *device))
-    {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to add in list!");
-
-        //Remove created BTDevice
-        CAFreeBTDevice(*device);
-        *device = NULL;
+    node->device = device;
+    node->next = NULL;
 
-        return CA_STATUS_FAILED;
+    if (NULL == *deviceList) //Empty list
+    {
+        *deviceList = node;
+    }
+    else //Add at front end
+    {
+        node->next = *deviceList;
+        *deviceList = node;
     }
 
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-void CAFreeBTDeviceList(BTDeviceList *deviceList)
+CAResult_t CAGetBTDevice(BTDeviceList *deviceList, const char *deviceAddress, BTDevice **device)
 {
-    while (deviceList)
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
+    VERIFY_NON_NULL(deviceAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
+    VERIFY_NON_NULL(device, BLUETOOTH_ADAPTER_TAG, "Device is null");
+
+    BTDeviceList *curNode = deviceList;
+    *device = NULL;
+    while (curNode != NULL)
     {
-        BTDeviceList *curList = deviceList;
-        deviceList = deviceList->next;
+        if (!strcasecmp(curNode->device->remoteAddress, deviceAddress))
+        {
+            *device = curNode->device;
+            return CA_STATUS_OK;
+        }
 
-        CAFreeBTDevice(curList->device);
-        OICFree(curList);
+        curNode = curNode->next;
     }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT [Device not found!]");
+    return CA_STATUS_FAILED;
 }
 
-void CAFreeBTDevice(BTDevice *device)
+CAResult_t CAGetBTDeviceBySocketId(BTDeviceList *deviceList, int32_t socketID, BTDevice **device)
 {
-    if (device)
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
+    VERIFY_NON_NULL(device, BLUETOOTH_ADAPTER_TAG, "Device is null");
+    BTDeviceList *curNode = deviceList;
+    *device = NULL;
+    while (curNode != NULL)
     {
-        if (device->remoteAddress)
+        if (curNode->device->socketFD == socketID)
         {
-            OICFree(device->remoteAddress);
+            *device = curNode->device;
+            return CA_STATUS_OK;
         }
 
-        if (device->serviceUUID)
+        curNode = curNode->next;
+    }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
+    return CA_STATUS_FAILED;
+}
+
+CAResult_t CARemoveBTDeviceFromList(BTDeviceList **deviceList, const char *deviceAddress)
+{
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(deviceList, BLUETOOTH_ADAPTER_TAG, "Device list is null");
+    VERIFY_NON_NULL(deviceAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
+
+    BTDeviceList *curNode = NULL;
+    BTDeviceList *prevNode = NULL;
+
+    curNode = *deviceList;
+    while (curNode != NULL)
+    {
+        if (!strcasecmp(curNode->device->remoteAddress, deviceAddress))
         {
-            OICFree(device->serviceUUID);
-        }
+            if (curNode == *deviceList)
+            {
+                *deviceList = curNode->next;
 
-        if (device->pendingDataList)
+                curNode->next = NULL;
+                CADestroyBTDeviceList(&curNode);
+                return CA_STATUS_OK;
+            }
+            else
+            {
+                prevNode->next = curNode->next;
+
+                curNode->next = NULL;
+                CADestroyBTDeviceList(&curNode);
+                return CA_STATUS_OK;
+            }
+        }
+        else
         {
-            CARemoveAllDataFromDevicePendingList(&device->pendingDataList);
+            prevNode = curNode;
+            curNode = curNode->next;
         }
+    }
 
+    OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Device not in the list !");
+    return CA_STATUS_FAILED;
+}
+
+void CADestroyBTDeviceList(BTDeviceList **deviceList)
+{
+    while (*deviceList)
+    {
+        BTDeviceList *curNode = *deviceList;
+        *deviceList = (*deviceList)->next;
+
+        CADestroyBTDevice(curNode->device);
+        OICFree(curNode);
+    }
+}
+
+void CADestroyBTDevice(BTDevice *device)
+{
+    if (device)
+    {
+        OICFree(device->remoteAddress);
+        OICFree(device->serviceUUID);
+        CADestroyBTDataList(&device->pendingDataList);
         OICFree(device);
     }
 }
 
-CAResult_t CAAddDataToDevicePendingList(BTDataList **dataList, void *data, uint32_t dataLen)
+CAResult_t CAAddBTDataToList(BTDataList **dataList, void *data, uint32_t dataLength)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
     VERIFY_NON_NULL(dataList, BLUETOOTH_ADAPTER_TAG, "Data list is null");
     VERIFY_NON_NULL(data, BLUETOOTH_ADAPTER_TAG, "Data is null");
 
-    if (0 == dataLen)
+    if (0 == dataLength)
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: data length is zero!");
         return CA_STATUS_INVALID_PARAM;
@@ -299,7 +311,7 @@ CAResult_t CAAddDataToDevicePendingList(BTDataList **dataList, void *data, uint3
     }
     pending_data->next = NULL;
 
-    pending_data->data->data = (void *) OICMalloc(dataLen); //data
+    pending_data->data->data = (void *) OICMalloc(dataLength); //data
     if (NULL == pending_data->data->data)
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "OICMalloc failed (data)!");
@@ -309,8 +321,8 @@ CAResult_t CAAddDataToDevicePendingList(BTDataList **dataList, void *data, uint3
         return CA_MEMORY_ALLOC_FAILED;
     }
 
-    memcpy(pending_data->data->data, data, dataLen);
-    pending_data->data->dataLength = dataLen;
+    memcpy(pending_data->data->data, data, dataLength);
+    pending_data->data->dataLength = dataLength;
 
     if (NULL == *dataList) //Empty list
     {
@@ -318,83 +330,63 @@ CAResult_t CAAddDataToDevicePendingList(BTDataList **dataList, void *data, uint3
     }
     else //Add at rear end
     {
-        BTDataList *curList = *dataList;
-        while (curList->next != NULL)
+        BTDataList *curNode = *dataList;
+        while (curNode->next != NULL)
         {
-            curList = curList->next;
+            curNode = curNode->next;
         }
 
-        curList->next = pending_data;
+        curNode->next = pending_data;
     }
 
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-CAResult_t CARemoveDataFromDevicePendingList(BTDataList **dataList)
+CAResult_t CARemoveBTDataFromList(BTDataList **dataList)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
     VERIFY_NON_NULL(dataList, BLUETOOTH_ADAPTER_TAG, "Data list is null");
 
-    BTDataList *cur = NULL;
-    BTDataList *prev = NULL;
-
-    cur = *dataList;
-    if (NULL != cur->next) //next node present in list
+    if (*dataList)
     {
-        prev = cur;
-        cur = cur->next;
-        CAFreeDataFromBTDataList(prev);
-        *dataList = cur;
-    }
-    else //last node
-    {
-        CAFreeDataFromBTDataList(cur);
-        *dataList = NULL;
+        BTDataList *curNode = *dataList;
+        *dataList = (*dataList)->next;
+
+        //Delete the first node
+        CADestroyBTData(curNode->data);
+        OICFree(curNode);
     }
 
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
-CAResult_t CARemoveAllDataFromDevicePendingList(BTDataList **dataList)
+void CADestroyBTDataList(BTDataList **dataList)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
-    VERIFY_NON_NULL(dataList, BLUETOOTH_ADAPTER_TAG, "Data list is null");
-
-    BTDataList *cur = NULL;
-    BTDataList *prev = NULL;
-
-    cur = *dataList;
-    while (cur)
+    while (*dataList)
     {
-        prev = cur;
-        cur = cur->next;
-        CAFreeDataFromBTDataList(prev);
+        BTDataList *curNode = *dataList;
+        *dataList = (*dataList)->next;
+        
+        CADestroyBTData(curNode->data);
+        OICFree(curNode);
     }
 
     *dataList = NULL;
 
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
 }
 
-void CAFreeDataFromBTDataList(BTDataList *dataList)
+void CADestroyBTData(BTData *data)
 {
-    if (dataList)
+    if (data)
     {
-        if (dataList->data)
-        {
-            if (dataList->data->data)
-            {
-                OICFree(dataList->data->data);
-            }
-            OICFree(dataList->data);
-        }
-        OICFree(dataList);
-        dataList = NULL;
+        OICFree(data->data);
+        OICFree(data);
     }
 }
 
index 2357498..c85970d 100644 (file)
@@ -19,8 +19,8 @@
  ******************************************************************/
 
 /**
- * @file    cabtdevicelist.h
- * @brief    This file provides APIs to access the discovered bluetooth device list
+ * @file  cabtdevicelist.h
+ * @brief  This file provides APIs to manage discovered bluetooth device list.
  */
 
 #ifndef __CA_BT_DEVICE_LIST_H_
@@ -39,7 +39,7 @@ extern "C"
  */
 typedef struct
 {
-    void *data;        /**< Data to be send to peer Bluetooth device. */
+    void *data;             /**< Data to be send to peer Bluetooth device. */
     uint32_t dataLength;    /**< Length of the data. */
 } BTData;
 
@@ -61,9 +61,9 @@ typedef struct
 {
     char *remoteAddress;        /**< Address of peer Bluetooth device. */
     char *serviceUUID;          /**< OIC service UUID running in peer Bluetooth device. */
-    int32_t socketFD;               /**< RfComm connection socket FD. */
+    int32_t socketFD;           /**< RfComm connection socket FD. */
     BTDataList *pendingDataList;/**< List of data needs to send to peer Bluetooth device. */
-    uint32_t serviceSearched;        /**< Flag to indicate the status of service search. */
+    uint32_t serviceSearched;   /**< Flag to indicate the status of service search. */
 } BTDevice;
 
 /**
@@ -76,20 +76,136 @@ typedef struct _BTDeviceList
     struct _BTDeviceList *next;  /**< Reference to next device information. */
 } BTDeviceList;
 
+/**
+ * @fn  CACreateAndAddToDeviceList
+ * @brief  Creates #BTDevice for specified remote address and uuid and to device list.
+ *
+ * @param[in][out]  deviceList Device list which created device add to.
+ * @param[in]  deviceAddress  Bluetooth device address.
+ * @param[in]  uuid  service uuid.
+ * @param[in]  device  created #BTDevice.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval  #CA_STATUS_FAILED Failed to create device and add to list
+ *
+ */
+CAResult_t CACreateAndAddToDeviceList(BTDeviceList **deviceList, const char *deviceAddress,
+        const char *uuid, BTDevice **device);
+
+/**
+ * @fn  CAAddBTDeviceToList
+ * @brief  Insert device to specified list.
+ *
+ * @param[in][out]  deviceList  Device list to which specifed @device to be added.
+ * @param[in]  device  Device to be added to list.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval  #CA_MEMORY_ALLOC_FAILED Memory allocation failed
+ *
+ */
 CAResult_t CAAddBTDeviceToList(BTDeviceList **deviceList, BTDevice *device);
-CAResult_t CARemoveBTDeviceFromList(BTDeviceList **deviceList, const char *remoteAddress);
-CAResult_t CAGetBTDevice(BTDeviceList *deviceList, const char *remoteAddress, BTDevice **device);
-CAResult_t CAGetBTDeviceBySocketId(BTDeviceList *deviceList, int32_t socket_id, BTDevice **device);
-CAResult_t CACreateBTDevice(const char *remoteAddress, const char *uuid, BTDevice **device);
-CAResult_t CACreateAndAddToDeviceList(BTDeviceList **deviceList, const char *remoteAddress,
-                                      const char *serviceUUID, BTDevice **device);
-void CAFreeBTDeviceList(BTDeviceList *deviceList);
-void CAFreeBTDevice(BTDevice *device);
-
-CAResult_t CAAddDataToDevicePendingList(BTDataList **dataList, void *data, uint32_t data_len);
-CAResult_t CARemoveDataFromDevicePendingList(BTDataList **dataList);
-CAResult_t CARemoveAllDataFromDevicePendingList(BTDataList **dataList);
-void CAFreeDataFromBTDataList(BTDataList *dataList);
+
+/**
+ * @fn  CAGetBTDevice
+ * @brief  Get the device from list which matches specified device address.
+ *
+ * @param[in]  deviceList  Device list to search for the device.
+ * @param[in]  deviceAddress  Device address used for matching.
+ * @param[out]  device  #BTDevice which has matching device address.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval  #CA_STATUS_FAILED Device is not found in the list
+ *
+ */
+CAResult_t CAGetBTDevice(BTDeviceList *deviceList, const char *deviceAddress, BTDevice **device);
+
+/**
+ * @fn  CAGetBTDeviceBySocketId
+ * @brief  Get the device from list which matches specified RFCOMM socket id.
+ *
+ * @param[in]  deviceList  Device list to search for the device.
+ * @param[in]  socketID  RFCOMM socket id.
+ * @param[out]  device  #BTDevice which has matching RFCOMM socket id .
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval  #CA_STATUS_FAILED Device is not found in the list
+ *
+ */
+CAResult_t CAGetBTDeviceBySocketId(BTDeviceList *deviceList, int32_t socketID, BTDevice **device);
+
+/**
+ * @fn  CARemoveBTDeviceFromList
+ * @brief  Remove and delete the device matching specified device address from list.
+ *
+ * @param[in][out]  deviceList  Device list to search for the device.
+ * @param[in]  deviceAddress  Bluetooth device address.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval  #CA_STATUS_FAILED Device is not found in the list
+ *
+ */
+CAResult_t CARemoveBTDeviceFromList(BTDeviceList **deviceList, const char *deviceAddress);
+
+/**
+ * @fn  CADestroyBTDeviceList
+ * @brief  Destroy the specified device list. Removes and delete all the devices in the list.
+ *
+ * @param[in][out]  deviceList  Device list to be destroyed.
+ *
+ */
+void CADestroyBTDeviceList(BTDeviceList **deviceList);
+
+/**
+ * @fn  CAAddBTDataToList
+ * @brief  Insert data to specified list.
+ *
+ * @param[in][out]  dataList  Data list to which data will be add.
+ * @param[in]  data  Data to be stored.
+ * @param[in]  data_len  Length of the data.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input parameters
+ * @retval  #CA_MEMORY_ALLOC_FAILED Memory allocation failed
+ *
+ */
+CAResult_t CAAddBTDataToList(BTDataList **dataList, void *data, uint32_t dataLength);
+
+/**
+ * @fn  CARemoveBTDataFromList
+ * @brief  Remove and delete data from front end of list.
+ *
+ * @param[in][out]  dataList  Data list from which data will be removed.
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM Invalid input parameters
+ *
+ */
+CAResult_t CARemoveBTDataFromList(BTDataList **dataList);
+
+/**
+ * @fn  CADestroyBTDataList
+ * @brief  Destroy the specified data list. Removes and deletes all the data in the list.
+ *
+ * @param[in]  dataList  Data list to be destroyed.
+ *
+ */
+void CADestroyBTDataList(BTDataList **dataList);
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
 
 #ifdef __cplusplus
 } /* extern "C" */
index 31c38e5..8120a64 100644 (file)
@@ -19,8 +19,8 @@
  ******************************************************************/
 
 /**
- * @file    cabtendpoint.h
- * @brief   This    file provides the APIs to send data on established RFCOMM connections.
+ * @file  cabtendpoint.h
+ * @brief  This file provides the APIs to send data on established RFCOMM connections.
  */
 
 #ifndef __CA_BT_ENDPOINT_H_
@@ -37,12 +37,12 @@ extern "C"
 
 /**
  * @fn  CABTSendData
- * @brief  Send data over RFCOMM connection
+ * @brief  Send data over RFCOMM connection.
  *
- * @param  serverFD  The RFCOMM connection socket file descriptor
- * @param  data  The data needs to be sent
- * @param  dataLength  The length of data
- * @param  sentDataLen  The length of data which actually sent successful
+ * @param[in]  serverFD  The RFCOMM connection socket file descriptor.
+ * @param[in]  data  The data needs to be sent.
+ * @param[in]  dataLength  The length of data.
+ * @param[in]  sentDataLength  The length of data which actually sent successful.
  *
  * @return  CA_STATUS_OK on success otherwise proper error code.
  * @retval  CA_STATUS_OK  Successful
@@ -51,7 +51,7 @@ extern "C"
  *
  */
 CAResult_t CABTSendData(const int32_t serverFD, const void *data, const uint32_t dataLength,
-                        uint32_t *sentDataLen);
+                        uint32_t *sentDataLength);
 
 #ifdef __cplusplus
 } /* extern "C" */
index 4d9d079..875d353 100644 (file)
@@ -19,8 +19,8 @@
  ******************************************************************/
 
 /**
- * @file    cabtmanager.c
- * @brief   This    file provides the APIs to control Bluetooth transport
+ * @file  cabtmanager.c
+ * @brief  This file provides the APIs to control Bluetooth transport
  */
 
 #include "cabtmanager.h"
 #include "caadapterutils.h"
 #include "camessagequeue.h"
 
-
+/**
+ * @struct CABTNetworkEvent
+ * @brief Structure to maintain the adapter information and its status.
+ */
 typedef struct
 {
     CALocalConnectivity_t *info;
     CANetworkStatus_t status;
 } CABTNetworkEvent;
 
+/**
+ * @struct CABTMessage
+ * @brief Structure to maintain the information of data in message queue.
+ */
 typedef struct
 {
     void *data;
-    int32_t dataLen;
+    int32_t dataLength;
     CARemoteEndpoint_t *remoteEndpoint;
 } CABTMessage;
 
@@ -105,7 +112,7 @@ static u_cond gSendDataCond = NULL;
  * @var gDataSendHandlerState
  * @brief Stop condition of sendhandler.
  */
-static CABool_t gDataSendHandlerState = CA_FALSE;
+static bool gDataSendHandlerState = false;
 
 /**
  * @fn CABTAdapterStateChangeCallback
@@ -135,7 +142,8 @@ static void CABTDataRecvCallback(bt_socket_received_data_s *data, void *userData
  */
 static void CABTDeviceDiscoveryCallback(int result,
                                         bt_adapter_device_discovery_state_e discoveryState,
-                                        bt_adapter_device_discovery_info_s *discoveryInfo, void *userData);
+                                        bt_adapter_device_discovery_info_s *discoveryInfo,
+                                        void *userData);
 
 /**
  * @fn CABTServiceSearchedCallback
@@ -147,13 +155,13 @@ static void CABTServiceSearchedCallback(int result, bt_device_sdp_info_s *sdpInf
 
 /**
  * @fn CABTManagerInitializeQueues
- * @brief This function creates send and receive message queues.
+ * @brief This function creates and initialize send message queue.
  */
 static CAResult_t CABTManagerInitializeQueues(void);
 
 /**
  * @fn CABTManagerTerminateQueues
- * @brief This function releases send and receive message queues.
+ * @brief This function terminates the send message queue.
  */
 static void CABTManagerTerminateQueues(void);
 
@@ -171,32 +179,55 @@ static void CABTManagerTerminateMutex(void);
 
 /**
  * @fn CABTManagerDataSendHandler
- * @brief This function handles message from send queue.
+ * @brief This function handles data from send message queue.
  */
 static void CABTManagerDataSendHandler(void *context);
 
 /**
  * @fn CABTManagerSendUnicastData
- * @brief This function send data to specified remote bluetooth device.
+ * @brief This function sends data to specified remote bluetooth device.
  */
 static CAResult_t CABTManagerSendUnicastData(const char *remoteAddress, const char *serviceUUID,
         void *data, uint32_t dataLength, uint32_t *sentLength);
 
 /**
  * @fn CABTManagerSendMulticastData
- * @brief This function send data to all bluetooth devices running OIC service.
+ * @brief This function sends data to all bluetooth devices running OIC service.
  */
 static CAResult_t CABTManagerSendMulticastData(const char *serviceUUID, void *data,
-        uint32_t dataLength,
-        uint32_t *sentLength);
+        uint32_t dataLength, uint32_t *sentLength);
+
+/**
+ * @fn CABTGetAdapterEnableState
+ * @brief This function gets bluetooth adatper enable state.
+ */
+static CAResult_t CABTGetAdapterEnableState(bool *state);
+
+/**
+ * @fn CABTStartDeviceDiscovery
+ * @brief This function starts device discovery.
+ */
+static CAResult_t CABTStartDeviceDiscovery(void);
+
+/**
+ * @fn CABTStopDeviceDiscovery
+ * @brief This function stops device discovery.
+ */
+static CAResult_t CABTStopDeviceDiscovery(void);
 
 /**
  * @fn CABTStartServiceSearch
- * @brief This function search for OIC service for remote Bluetooth device.
+ * @brief This function searches for OIC service for remote Bluetooth device.
  */
 static CAResult_t CABTStartServiceSearch(const char *remoteAddress);
 
 /**
+ * @fn CABTStopServiceSearch
+ * @brief This function stops any ongoing service sevice search.
+ */
+static CAResult_t CABTStopServiceSearch(void);
+
+/**
  * @fn CABTNotifyNetworkStauts
  * @brief This function creates notification task for network adapter status and add it to thread pool.
  */
@@ -217,12 +248,17 @@ static CABTNetworkEvent *CABTCreateNetworkEvent(CALocalConnectivity_t *connectiv
 
 /**
  * @fn CABTFreeNetworkEvent
- * @brief destroy instance of CABTNetworkEvent.
+ * @brief Free the memory associated with @event.
  */
 static void CABTFreeNetworkEvent(CABTNetworkEvent *event);
 
+/**
+ * @fn CABTManagerDisconnectAll
+ * @brief Closes all the client connection to peer bluetooth devices.
+ */
+static void CABTManagerDisconnectAll(void);
 
-CAResult_t CABTManagerIntialize(u_thread_pool_t threadPool)
+CAResult_t CABTManagerInitialize(u_thread_pool_t threadPool)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
@@ -236,38 +272,9 @@ CAResult_t CABTManagerIntialize(u_thread_pool_t threadPool)
         return CA_STATUS_FAILED;
     }
 
-    //Set bluetooth adapter sate change callback
-    if (BT_ERROR_NONE != (err = bt_adapter_set_state_changed_cb(CABTAdapterStateChangeCallback, NULL)))
-    {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG,
-                  "Setting bluetooth state change callback failed!, error num [%x]", err);
-
-        //Deinitialize the Bluetooth stack
-        bt_deinitialize();
-        return CA_STATUS_FAILED;
-    }
-
-    //Get Bluetooth adapter state
-    bt_adapter_state_e adapterState;
-    if (BT_ERROR_NONE != (err = bt_adapter_get_state(&adapterState)))
-    {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth get state failed!, error num [%x]",
-                  err);
-
-        //Reset the adapter state change callback
-        bt_adapter_unset_state_changed_cb();
-
-        //Deinitialize the Bluetooth stack
-        bt_deinitialize();
-        return CA_STATUS_FAILED;
-    }
-
     //Initialize Send/Receive data message queues
     if (CA_STATUS_OK != CABTManagerInitializeQueues())
     {
-        //Reset the adapter state change callback
-        bt_adapter_unset_state_changed_cb();
-
         //Deinitialize the Bluetooth stack
         bt_deinitialize();
         return CA_STATUS_FAILED;
@@ -281,9 +288,22 @@ CAResult_t CABTManagerIntialize(u_thread_pool_t threadPool)
         gBTThreadPool = threadPool;
     }
 
-    if (BT_ADAPTER_DISABLED == adapterState)
+    //Get Bluetooth adapter state
+    bool adapterState = false;
+    if (CA_STATUS_OK != CABTGetAdapterEnableState(&adapterState))
+    {
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get adatper enable state");
+
+        //Deinitialize the Bluetooth stack
+        bt_deinitialize();
+        return CA_STATUS_FAILED;
+    }
+
+    if (false == adapterState)
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth adapter is disabled!");
+
+        bt_adapter_set_state_changed_cb(CABTAdapterStateChangeCallback, NULL);
         return CA_ADAPTER_NOT_ENABLED;
     }
 
@@ -321,8 +341,7 @@ void CABTManagerTerminate(void)
     if (gBTDeviceListMutex)
     {
         u_mutex_lock(gBTDeviceListMutex);
-        CAFreeBTDeviceList(gBTDeviceList);
-        gBTDeviceList = NULL;
+        CADestroyBTDeviceList(&gBTDeviceList);
         u_mutex_unlock(gBTDeviceListMutex);
     }
 
@@ -339,19 +358,15 @@ CAResult_t CABTManagerStart(void)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
-    int err = BT_ERROR_NONE;
-    bool isDiscoveryStarted = false;
-
     //Get Bluetooth adapter state
-    bt_adapter_state_e adapterState;
-    if (BT_ERROR_NONE != (err = bt_adapter_get_state(&adapterState)))
+    bool adapterState = false;
+    if (CA_STATUS_OK != CABTGetAdapterEnableState(&adapterState))
     {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth get state failed!, error num [%x]",
-                  err);
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get adatper enable state");
         return CA_STATUS_FAILED;
     }
 
-    if (BT_ADAPTER_DISABLED == adapterState)
+    if (false == adapterState)
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth adapter is disabled!");
         return CA_ADAPTER_NOT_ENABLED;
@@ -363,32 +378,22 @@ CAResult_t CABTManagerStart(void)
     bt_socket_set_connection_state_changed_cb(CABTSocketConnectionStateCallback, NULL);
     bt_socket_set_data_received_cb(CABTDataRecvCallback, NULL);
 
-    if (BT_ERROR_NONE != (err = bt_adapter_is_discovering(&isDiscoveryStarted)))
-    {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
-                  err);
-        return CA_STATUS_FAILED;
-    }
+    //Start device discovery
+    CABTStartDeviceDiscovery();
 
-    //Start device discovery if its not started
-    if (false == isDiscoveryStarted )
+    //Start data send and receive handlers
+    if (!gDataSendHandlerState)
     {
-        if (BT_ERROR_NONE != (err = bt_adapter_start_device_discovery()))
+        gDataSendHandlerState = true;
+        if (CA_STATUS_OK != u_thread_pool_add_task(gBTThreadPool, CABTManagerDataSendHandler, NULL))
         {
-            OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Device discovery failed!, error num [%x]",
-                      err);
+            OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to start data send handler!");
+
+            gDataSendHandlerState = false;
             return CA_STATUS_FAILED;
         }
     }
 
-    //Start data send and receive handlers
-    gDataSendHandlerState = CA_TRUE;
-    if (CA_STATUS_OK != u_thread_pool_add_task(gBTThreadPool, CABTManagerDataSendHandler, NULL))
-    {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to start data send handler!");
-        return CA_STATUS_FAILED;
-    }
-
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -397,37 +402,21 @@ void CABTManagerStop(void)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
-    int err = BT_ERROR_NONE;
-    bool isDiscoveryStarted = false;
-
     //Stop data send and receive handlers
     if (gSendDataMutex && gSendDataCond && gDataSendHandlerState)
     {
         u_mutex_lock(gSendDataMutex);
-        gDataSendHandlerState = CA_FALSE;
+        gDataSendHandlerState = false;
         u_cond_signal(gSendDataCond);
         u_mutex_unlock(gSendDataMutex);
     }
 
-    //Check discovery status
-    if (BT_ERROR_NONE != (err = bt_adapter_is_discovering(&isDiscoveryStarted)))
-    {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
-                  err);
-        return;
-    }
-
-    //stop the device discovery process
-    if (true == isDiscoveryStarted)
-    {
-        OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Stopping the device search process");
-        if (BT_ERROR_NONE != (err = bt_adapter_stop_device_discovery()))
-        {
-            OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to stop device discovery!, error num [%x]",
-                      err);
-        }
-    }
-
+    //Stop service search
+    CABTStopServiceSearch();
+    
+    //Stop the device discovery process
+    CABTStopDeviceDiscovery();
+    
     //reset bluetooth adapter callbacks
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Resetting the callbacks");
     bt_adapter_unset_device_discovery_state_changed_cb();
@@ -435,6 +424,9 @@ void CABTManagerStop(void)
     bt_socket_unset_connection_state_changed_cb();
     bt_socket_unset_data_received_cb();
 
+    //Disconnect all the client connections
+    CABTManagerDisconnectAll();
+
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
 }
 
@@ -453,18 +445,17 @@ CAResult_t CABTManagerSendData(const char *remoteAddress, const char *serviceUUI
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
+    if (!gDataSendHandlerState)
+    {
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Send handler is not running!");
+        return CA_STATUS_FAILED;
+    }
+
     //Input validation
     VERIFY_NON_NULL(serviceUUID, BLUETOOTH_ADAPTER_TAG, "service UUID is null");
     VERIFY_NON_NULL(data, BLUETOOTH_ADAPTER_TAG, "Data is null");
     VERIFY_NON_NULL(sentLength, BLUETOOTH_ADAPTER_TAG, "Sent data length holder is null");
 
-    VERIFY_NON_NULL_RET(gSendDataQueue, BLUETOOTH_ADAPTER_TAG, "Send data queue is NULL",
-                        CA_STATUS_FAILED);
-    VERIFY_NON_NULL_RET(gSendDataMutex, BLUETOOTH_ADAPTER_TAG, "Send data queue mutex is NULL",
-                        CA_STATUS_FAILED);
-    VERIFY_NON_NULL_RET(gSendDataCond, BLUETOOTH_ADAPTER_TAG, "Send data queue condition is NULL",
-                        CA_STATUS_FAILED);
-
     //Add message to data queue
     CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
                                          serviceUUID);
@@ -477,6 +468,8 @@ CAResult_t CABTManagerSendData(const char *remoteAddress, const char *serviceUUI
     if (CA_STATUS_OK != CAAdapterEnqueueMessage(gSendDataQueue, remoteEndpoint, data, dataLength))
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to add message to queue !");
+
+        CAAdapterFreeRemoteEndpoint(remoteEndpoint);
         return CA_STATUS_FAILED;
     }
 
@@ -545,13 +538,14 @@ CAResult_t CABTManagerGetInterface(CALocalConnectivity_t **info)
 CAResult_t CABTManagerReadData(void)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
-
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
     return CA_NOT_SUPPORTED;
 }
 
 CAResult_t CABTManagerInitializeQueues(void)
 {
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
     if (NULL == gSendDataQueue)
     {
         if (CA_STATUS_OK != CAAdapterInitializeMessageQueue(&gSendDataQueue))
@@ -559,38 +553,52 @@ CAResult_t CABTManagerInitializeQueues(void)
             return CA_STATUS_FAILED;
         }
     }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
 }
 
 void CABTManagerTerminateQueues(void)
 {
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
     if (gSendDataQueue)
     {
         CAAdapterTerminateMessageQueue(gSendDataQueue);
         gSendDataQueue = NULL;
     }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");    
 }
 
 void CABTManagerInitializeMutex(void)
 {
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
     u_mutex_init();
-    if (NULL == gBTDeviceListMutex)
+
+    if (!gBTDeviceListMutex)
     {
         gBTDeviceListMutex = u_mutex_new();
     }
 
-    if (NULL == gSendDataMutex)
+    if (!gSendDataMutex)
     {
         gSendDataMutex = u_mutex_new();
     }
 
-    if (NULL == gSendDataCond)
+    if (!gSendDataCond)
     {
         gSendDataCond = u_cond_new();
     }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");    
 }
 
 void CABTManagerTerminateMutex(void)
 {
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
     if (gBTDeviceListMutex)
     {
         u_mutex_free(gBTDeviceListMutex);
@@ -608,6 +616,8 @@ void CABTManagerTerminateMutex(void)
         u_cond_free(gSendDataCond);
         gSendDataCond = NULL;
     }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
 }
 
 void CABTManagerDataSendHandler(void *context)
@@ -653,7 +663,7 @@ void CABTManagerDataSendHandler(void *context)
         u_cond_wait(gSendDataCond, gSendDataMutex);
         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Got the signal that data is pending");
 
-        if (CA_FALSE == gDataSendHandlerState)
+        if (false == gDataSendHandlerState)
         {
             break;
         }
@@ -713,7 +723,7 @@ CAResult_t CABTManagerSendUnicastData(const char *remoteAddress, const char *ser
     if (-1 == device->socketFD)
     {
         //Adding to pending list
-        if (CA_STATUS_OK != CAAddDataToDevicePendingList(&device->pendingDataList, data,
+        if (CA_STATUS_OK != CAAddBTDataToList(&device->pendingDataList, data,
                 dataLength))
         {
             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to add data to pending list!");
@@ -753,8 +763,6 @@ CAResult_t CABTManagerSendMulticastData(const char *serviceUUID, void *data, uin
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
-    BTDeviceList *cur = NULL;
-
     //Input validation
     VERIFY_NON_NULL(serviceUUID, BLUETOOTH_ADAPTER_TAG, "service UUID is null");
     VERIFY_NON_NULL(data, BLUETOOTH_ADAPTER_TAG, "Data is null");
@@ -770,12 +778,18 @@ CAResult_t CABTManagerSendMulticastData(const char *serviceUUID, void *data, uin
 
     //Send the packet to all OIC devices
     u_mutex_lock(gBTDeviceListMutex);
-    cur = gBTDeviceList;
-    while (cur != NULL)
+    BTDeviceList *curList = gBTDeviceList;
+    while (curList != NULL)
     {
-        BTDevice *device = cur->device;
-        cur = cur->next;
+        BTDevice *device = curList->device;
+        curList = curList->next;
 
+        if (!device)
+        {
+            OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "There is no device!");
+            break;
+        }
+        
         if (-1 == device->socketFD)
         {
             //Check if the device service search is finished
@@ -786,7 +800,7 @@ CAResult_t CABTManagerSendMulticastData(const char *serviceUUID, void *data, uin
             }
 
             //Adding to pendding list
-            if (CA_STATUS_OK != CAAddDataToDevicePendingList(&device->pendingDataList, data,
+            if (CA_STATUS_OK != CAAddBTDataToList(&device->pendingDataList, data,
                     dataLength))
             {
                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to add data to pending list !");
@@ -799,7 +813,7 @@ CAResult_t CABTManagerSendMulticastData(const char *serviceUUID, void *data, uin
                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to make RFCOMM connection !");
 
                 //Remove the data which added to pending list
-                CARemoveDataFromDevicePendingList(&device->pendingDataList);
+                CARemoveBTDataFromList(&device->pendingDataList);
                 continue;
             }
         }
@@ -818,6 +832,95 @@ CAResult_t CABTManagerSendMulticastData(const char *serviceUUID, void *data, uin
     return CA_STATUS_OK;
 }
 
+CAResult_t CABTGetAdapterEnableState(bool *state)
+{
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
+    //Input validation
+    VERIFY_NON_NULL(state, BLUETOOTH_ADAPTER_TAG, "state holder is NULL!");
+
+    int err = BT_ERROR_NONE;
+    bt_adapter_state_e adapterState;    
+
+    //Get Bluetooth adapter state
+    if (BT_ERROR_NONE != (err = bt_adapter_get_state(&adapterState)))
+    {
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth get state failed!, error num [%x]",
+                  err);
+
+        return CA_STATUS_FAILED;
+    }
+
+    *state = false;
+    if (BT_ADAPTER_ENABLED == adapterState)
+    {
+        *state = true;
+    }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CABTStartDeviceDiscovery(void)
+{
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
+    int err = BT_ERROR_NONE;
+    bool isDiscoveryStarted = false;
+
+    //Check the device discovery state
+    if (BT_ERROR_NONE != (err = bt_adapter_is_discovering(&isDiscoveryStarted)))
+    {
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    //Start device discovery if its not started
+    if (false == isDiscoveryStarted)
+    {
+        if (BT_ERROR_NONE != (err = bt_adapter_start_device_discovery()))
+        {
+            OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Device discovery failed!, error num [%x]",
+                      err);
+            return CA_STATUS_FAILED;
+        }
+    }
+    
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CABTStopDeviceDiscovery(void)
+{
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
+    int err = BT_ERROR_NONE;
+    bool isDiscoveryStarted = false;
+
+    //Check the device discovery state
+    if (BT_ERROR_NONE != (err = bt_adapter_is_discovering(&isDiscoveryStarted)))
+    {
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    //stop the device discovery process
+    if (true == isDiscoveryStarted)
+    {
+        OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Stopping the device search process");
+        if (BT_ERROR_NONE != (err = bt_adapter_stop_device_discovery()))
+        {
+            OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to stop device discovery!, error num [%x]",
+                      err);
+        }
+    }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;    
+}
+
 CAResult_t CABTStartServiceSearch(const char *remoteAddress)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
@@ -844,6 +947,24 @@ CAResult_t CABTStartServiceSearch(const char *remoteAddress)
     return CA_STATUS_OK;
 }
 
+CAResult_t CABTStopServiceSearch(void)
+{
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+
+    int err = BT_ERROR_NONE;
+
+    //Stop ongoing service search
+    if (BT_ERROR_NONE != (err = bt_device_cancel_service_search()))
+    {
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Get bonded device failed!, error num [%x]",
+                  err);
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
 void CABTAdapterStateChangeCallback(int result, bt_adapter_state_e adapterState, void *userData)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
@@ -910,12 +1031,12 @@ void CABTSocketConnectionStateCallback(int result, bt_socket_connection_state_e
                                   device->remoteAddress);
 
                         //Remove all the data from pending list
-                        CARemoveAllDataFromDevicePendingList(&device->pendingDataList);
+                        CADestroyBTDataList(&device->pendingDataList);
                         break;
                     }
 
                     //Remove the data which send from pending list
-                    CARemoveDataFromDevicePendingList(&device->pendingDataList);
+                    CARemoveBTDataFromList(&device->pendingDataList);
                 }
                 u_mutex_unlock(gBTDeviceListMutex);
             }
@@ -1018,7 +1139,7 @@ void CABTDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_e
             {
                 OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Device discovered [%s]!",
                           discoveryInfo->remote_name);
-                if (CA_TRUE == CABTIsServiceSupported((const char **)discoveryInfo->service_uuid,
+                if (true == CABTIsServiceSupported((const char **)discoveryInfo->service_uuid,
                                                       discoveryInfo->service_count,
                                                       OIC_BT_SERVICE_ID))
                 {
@@ -1078,7 +1199,7 @@ void CABTServiceSearchedCallback(int result, bt_device_sdp_info_s *sdpInfo, void
             return;
         }
 
-        if (CA_TRUE == CABTIsServiceSupported((const char **)sdpInfo->service_uuid,
+        if (true == CABTIsServiceSupported((const char **)sdpInfo->service_uuid,
                                               sdpInfo->service_count, OIC_BT_SERVICE_ID))
         {
             device->serviceSearched = 1;
@@ -1181,13 +1302,36 @@ void CABTFreeNetworkEvent(CABTNetworkEvent *event)
 {
     if (event)
     {
-        if (event->info)
-        {
-            CAAdapterFreeLocalEndpoint(event->info);
-        }
-
+        CAAdapterFreeLocalEndpoint(event->info);
         OICFree(event);
     }
 }
 
+void CABTManagerDisconnectAll(void)
+{
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
+    
+    u_mutex_lock(gBTDeviceListMutex);
+    
+    BTDeviceList *cur = gBTDeviceList;
+    while (cur != NULL)
+    {
+        BTDevice *device = cur->device;
+        cur = cur->next;
+
+        if (device && 0 <= device->socketFD)
+        {
+            if (CA_STATUS_OK != CABTClientDisconnect(device->socketFD))
+            {
+                OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to disconnect the client connection address:%s",device->remoteAddress);
+            }
+
+            device->socketFD = -1;
+        }
+    }
+    
+    u_mutex_unlock(gBTDeviceListMutex);
+
+    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
+}
 
index 562503a..76a7b0c 100644 (file)
@@ -19,8 +19,8 @@
  ******************************************************************/
 
 /**
- * @file    cabtmanager.h
- * @brief   This    file provides the APIs to control Bluetooth transport
+ * @file  cabtmanager.h
+ * @brief  This file provides the APIs to control Bluetooth transport
  */
 
 #ifndef __CA_BT_MANAGER_H_
@@ -39,96 +39,101 @@ extern "C"
 
 /**
  * @fn  CABTManagerInitialize
- * @brief  Initializes Bluetooth adapter
+ * @brief  Initializes bluetooth adapter.
  *
- * @param  threadPool  Thread pool for handling asynchronous tasks
+ * @param[in]  threadPool  Thread pool for handling asynchronous tasks.
  *
- * @return  CA_STATUS_OK or CA_ADAPTER_NOT_ENABLED on success otherwise proper error code.
- * @retval  CA_STATUS_OK  Successful
- * @retval  CA_ADAPTER_NOT_ENABLED Initialization is successful, but bluetooth adapter is
- *                                                    not enabled.
- * @retval  CA_STATUS_FAILED Operation failed
+ * @return  #CA_STATUS_OK or #CA_ADAPTER_NOT_ENABLED on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_ADAPTER_NOT_ENABLED Initialization is successful, but bluetooth adapter is
+ *                                                      not enabled.
+ * @retval  #CA_STATUS_FAILED Operation failed
  *
+ * @see  CABTManagerTerminate()
  */
 CAResult_t CABTManagerInitialize(u_thread_pool_t threadPool);
 
 /**
  * @fn  CABTManagerTerminate
- * @brief  Deinitialize with bluetooth adapter
+ * @brief  Deinitialize with bluetooth adapter.
  *
- * @see CABTManagerIntialize
+ * @pre  CABTManagerIntialize() should be invoked before using this API.
+ *
+ * @see  CABTManagerIntialize()
  *
  */
 void CABTManagerTerminate(void);
 
 /**
  * @fn  CABTManagerStart
- * @brief  Start bluetooth adapter which includes start searching for nearby OIC devices
+ * @brief  Starts discovery for nearby OIC bluetooth devices.
  *
- * @return  CA_STATUS_OK on success otherwise proper error code.
- * @retval  CA_STATUS_OK  Successful
- * @retval  CA_STATUS_FAILED Operation failed
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
  *
- * @pre CABTManagerIntialize should be invoked before using this API
+ * @pre  CABTManagerIntialize() should be invoked before using this API.
  *
- * @see CABTManagerIntialize
+ * @see  CABTManagerIntialize()
  *
  */
 CAResult_t CABTManagerStart(void);
 
 /**
  * @fn  CABTManagerStop
- * @brief  Stop bluetooth adapter which includes stoping searching for nearby OIC devices
+ * @brief  Resetting callbacks with bluetooth framework and stop OIC device discovery.
  *
- * @pre CABTManagerIntialize should be invoked before using this API
+ * @pre  CABTManagerStart() should be invoked before using this API.
  *
- * @see CABTManagerIntialize
- * @see CABTManagerStart
+ * @see  CABTManagerIntialize()
+ * @see  CABTManagerStart()
  *
  */
 void CABTManagerStop(void);
 
 /**
  * @fn  CABTManagerSetPacketReceivedCallback
- * @brief  Register callback for receiving packets from remote Bluetooth device.
+ * @brief  Register callback for receiving packets from remote bluetooth device.
  *
- * @param  packetReceivedCallback  Callback function to register for receiving network packets
+ * @param[in]  packetReceivedCallback  Callback function to register for receiving network packets.
  *
- * @return  none.
+ * @post  CANetworkPacketReceivedCallback() will be called if any data received from peer
+ *           connected bluetooth device.
  *
- * @see CBNetworkPacketReceived
+ * @see  CANetworkPacketReceivedCallback()
  *
  */
 void CABTManagerSetPacketReceivedCallback(CANetworkPacketReceivedCallback packetReceivedCallback);
 
 /**
  * @fn  CABTManagerSetNetworkChangeCallback
- * @brief  Register callback for receiving network chang state of local Bluetooth adapter.
+ * @brief  Register callback for receiving local bluetooth adapter state.
  *
- * @param  networkChangeCallback  Callback function to register for receiving network adapter status
+ * @param[in]  networkStateChangeCallback  Callback function to register for receiving local bluetooth
+ *                                                           adapter status.
  *
- * @return  none
+ * @post  CANetworkChangeCallback() will be called if bluetooth adatper state changes.
  *
- * @see CBNetworkChange
+ * @see  CANetworkChangeCallback()
  *
  */
-void CABTManagerSetNetworkChangeCallback(CANetworkChangeCallback networkChangeCallback);
+void CABTManagerSetNetworkChangeCallback(CANetworkChangeCallback networkStateChangeCallback);
 
 /**
  * @fn  CABTManagerSendData
- * @brief  Send unicast/multicast data to remote bluetooth device
+ * @brief  Send unicast/multicast data to remote bluetooth device.
  *
- * @param  remoteAddress  The address of remote bluetooth device to which data needs to be sent.
- *                                   This will be NULL in case of sending multicast data.
- * @param  serviceUUID  The UUID of service to which RFCOMM connection needs to established
- * @param  data  The data needs to be send to remote bluetooth device
- * @param  dataLength  Length of data
- * @param  sentLength  Length of data actually sent or added to pending list for sending
+ * @param[in]  remoteAddress  Address of remote bluetooth device to which data needs to be sent.
+ *                                        This will be NULL in case of sending multicast data.
+ * @param[in]  serviceUUID  The UUID of service to which RFCOMM connection needs to established.
+ * @param[in]  data  The data needs to be send to remote bluetooth device.
+ * @param[in]  dataLength  Length of data.
+ * @param[out]  sentLength  Length of data actually sent or added to pending list for sending.
  *
- * @return  CA_STATUS_OK on success otherwise proper error code.
- * @retval  CA_STATUS_OK  Successful
- * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
- * @retval  CA_STATUS_FAILED Operation failed
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval  #CA_STATUS_FAILED Operation failed
  *
  */
 CAResult_t CABTManagerSendData(const char *remoteAddress, const char *serviceUUID,
@@ -136,16 +141,16 @@ CAResult_t CABTManagerSendData(const char *remoteAddress, const char *serviceUUI
 
 /**
  * @fn  CABTManagerStartServer
- * @brief  Start RFCOMM server for given service UUID
+ * @brief  Start RFCOMM server for given service UUID.
  *
- * @param  serviceUUID  The UUID of service with which RFCOMM server needs to be started
- * @param  serverID  The ID for the server which started
+ * @param[in]  serviceUUID  The UUID of service with which RFCOMM server needs to be started
+ * @param[out]  serverID  The ID for the server which started
  *
- * @return  CA_STATUS_OK on success otherwise proper error code.
- * @retval  CA_STATUS_OK  Successful
- * @retval  CA_SERVER_STARTED_ALREADY Service on the specified UUID is already running.
- * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
- * @retval  CA_STATUS_FAILED Operation failed
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_SERVER_STARTED_ALREADY Service on the specified UUID is already running.
+ * @retval  #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval  #CA_STATUS_FAILED Operation failed
  *
  */
 CAResult_t CABTManagerStartServer(const char *serviceUUID, int32_t *serverID);
@@ -154,12 +159,15 @@ CAResult_t CABTManagerStartServer(const char *serviceUUID, int32_t *serverID);
  * @fn  CABTManagerStopServer
  * @brief  Stop RFCOMM server
  *
- * @param  serverID  The ID of server which needs to be stopped
+ * @param[in]  serverID  The ID of server which needs to be stopped
+ *
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
  *
- * @return  CA_STATUS_OK on success otherwise proper error code.
- * @retval  CA_STATUS_OK  Successful
- * @retval  CA_STATUS_FAILED Operation failed
+ * @pre  Server must be started with CABTManagerStartServer().
  *
+ * @see  CABTManagerStartServer()
  */
 CAResult_t CABTManagerStopServer(const int32_t serverID);
 
@@ -167,28 +175,30 @@ CAResult_t CABTManagerStopServer(const int32_t serverID);
  * @fn  CABTManagerGetInterface
  * @brief  Get the local bluetooth adapter information.
  *
- * @param  info  Local bluetooth adapter information
+ * @param[in]  info  Local bluetooth adapter information
  *
- * @return  CA_STATUS_OK on success otherwise proper error code.
- * @retval  CA_STATUS_OK  Successful
- * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets
- * @retval  CA_STATUS_FAILED Operation failed
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_INVALID_PARAM  Invalid input argumets
+ * @retval  #CA_STATUS_FAILED Operation failed
  *
- * @see CALocalConnectivity_t
+ * @see #CALocalConnectivity_t
  *
  */
 CAResult_t CABTManagerGetInterface(CALocalConnectivity_t **info);
 
+#if 0
 /**
  * @fn  CABTManagerReadData
  * @brief  All received data will be notified to upper layer.
  *
- * @return  CA_STATUS_OK on success otherwise proper error code.
- * @retval  CA_STATUS_OK  Successful
- * @retval  CA_STATUS_FAILED Operation failed
+ * @return  #CA_STATUS_OK on success otherwise proper error code.
+ * @retval  #CA_STATUS_OK  Successful
+ * @retval  #CA_STATUS_FAILED Operation failed
  *
  */
 CAResult_t CABTManagerReadData(void);
+#endif
 
 #ifdef __cplusplus
 } /* extern "C" */
index 637099d..8c0f2e0 100644 (file)
@@ -92,7 +92,7 @@ CAResult_t CABTServerStop(const int32_t serverFD)
     int err = BT_ERROR_NONE;
     if (BT_ERROR_NONE != (err = bt_socket_destroy_rfcomm(serverFD)))
     {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed close rfcomm server socket!, error num [%x]",
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed close server socket!, error num [%x]",
                   err);
         return CA_STATUS_FAILED;
     }
index 59959b1..1c2dd5f 100644 (file)
@@ -40,8 +40,8 @@ extern "C"
  * @fn  CABTServerStart
  * @brief  Start RFCOMM server for given service UUID
  *
- * @param  serviceUUID  The UUID of service with which RFCOMM server needs to be started
- * @param  serverFD  The RFCOMM server socket file descriptor
+ * @param[in]  serviceUUID  The UUID of service with which RFCOMM server needs to be started.
+ * @param[out]  serverFD  The RFCOMM server socket file descriptor.
  *
  * @return  CA_STATUS_OK on success otherwise proper error code.
  * @retval  CA_STATUS_OK  Successful
@@ -55,7 +55,7 @@ CAResult_t CABTServerStart(const char *serviceUUID, int32_t *serverFD);
  * @fn  CABTServerStop
  * @brief  Stop RFCOMM server
  *
- * @param  serverFD  The RFCOMM server socket file descriptor which needs to be stopped
+ * @param[in]  serverFD  The RFCOMM server socket file descriptor which needs to be stopped.
  *
  * @return  CA_STATUS_OK on success otherwise proper error code.
  * @retval  CA_STATUS_OK  Successful
index 2bdeff3..661a6c2 100644 (file)
@@ -28,7 +28,7 @@
 
 #include <bluetooth.h>
 
-CABool_t CABTIsServiceSupported(const char **serviceUUID, const int32_t serviceCount,
+bool CABTIsServiceSupported(const char **serviceUUID, const int32_t serviceCount,
                                 const char *matchService)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
@@ -36,21 +36,20 @@ CABool_t CABTIsServiceSupported(const char **serviceUUID, const int32_t serviceC
     if (NULL == serviceUUID || 0 == serviceCount || NULL == matchService)
     {
         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Invalid input");
-        return CA_FALSE;
+        return false;
     }
 
-    int i;
-    for (i = 0; i < serviceCount; i++)
+    for (int i = 0; i < serviceCount; i++)
     {
         if (!strcasecmp(serviceUUID[i], matchService))
         {
             OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Service found !");
-            return CA_TRUE;
+            return true;
         }
     }
 
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
-    return CA_FALSE;
+    return false;
 }
 
 
index 54378fa..92192be 100644 (file)
@@ -26,6 +26,7 @@
 #ifndef __CA_BT_UTILS_H_
 #define __CA_BT_UTILS_H_
 
+#include <stdbool.h>
 #include <string.h>
 
 #include "cacommon.h"
@@ -46,16 +47,16 @@ extern "C"
 
 /**
  * @fn  CABTIsServiceSupported
- * @brief  Check if the specified list of service UUIDs contains OIC service UUID.
+ * @brief  Checks if the specified list of service UUIDs contains OIC service UUID.
  *
- * @param  serviceUUID  Array of service UUIDs
- * @param  serviceCount  Size of the service UUIDs array.
- * @param  matchService  Service UUID to be checked in the given array of service UUIDs
+ * @param[in]  serviceUUID  Array of service UUIDs
+ * @param[in]  serviceCount  Size of the service UUIDs array.
+ * @param[in]  matchService  Service UUID to be checked in the given array of service UUIDs
  *
- * @return  CA_TRUE if service UUID found otherwise CA_FALSE.
+ * @return  true if match service UUID found otherwise false.
  *
  */
-CABool_t CABTIsServiceSupported(const char **serviceUUID, const int32_t serviceCount,
+bool CABTIsServiceSupported(const char **serviceUUID, const int32_t serviceCount,
                                 const char *matchService);
 
 #ifdef __cplusplus
index d34895f..b8f98f7 100644 (file)
@@ -36,8 +36,8 @@ static int32_t gNotificationServerID = -1;
 static CAResult_t CAStartServer(const char *serviceUUID, int32_t *serverID);
 
 CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
-                           CANetworkPacketReceivedCallback networkPacketCallback,
-                           CANetworkChangeCallback netChangeCallback,
+                           CANetworkPacketReceivedCallback packetReceivedCallback,
+                           CANetworkChangeCallback networkStateChangeCallback,
                            u_thread_pool_t handle)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
@@ -45,17 +45,20 @@ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
     CAResult_t err = CA_STATUS_OK;
 
     //Input validation
-    VERIFY_NON_NULL(registerCallback, BLUETOOTH_ADAPTER_TAG, "register callback is NULL");
-    VERIFY_NON_NULL(networkPacketCallback, BLUETOOTH_ADAPTER_TAG, "data receive callback is NULL");
-    VERIFY_NON_NULL(netChangeCallback, BLUETOOTH_ADAPTER_TAG, "network changge callback is NULL");
+    VERIFY_NON_NULL(registerCallback, BLUETOOTH_ADAPTER_TAG,
+               "register callback is NULL");
+    VERIFY_NON_NULL(packetReceivedCallback, BLUETOOTH_ADAPTER_TAG,
+               "data receive callback is NULL");
+    VERIFY_NON_NULL(networkStateChangeCallback, BLUETOOTH_ADAPTER_TAG,
+               "network state change callback is NULL");
     VERIFY_NON_NULL(handle, BLUETOOTH_ADAPTER_TAG, "Thread pool hanlde is NULL");
 
     //Register the callbacks with BT Manager
-    CABTManagerSetPacketReceivedCallback(networkPacketCallback);
-    CABTManagerSetNetworkChangeCallback(netChangeCallback);
+    CABTManagerSetPacketReceivedCallback(packetReceivedCallback);
+    CABTManagerSetNetworkChangeCallback(networkStateChangeCallback);
 
     //Initialize BT Manager
-    err = CABTManagerIntialize(handle);
+    err = CABTManagerInitialize(handle);
     if (CA_STATUS_OK != err && CA_ADAPTER_NOT_ENABLED != err)
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "BT Manger initialize failed!, error number [%d]",
@@ -69,8 +72,6 @@ CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback,
     handler.startDiscoverServer = CAStartEDRDiscoveryServer;
     handler.sendData = CASendEDRUnicastData;
     handler.sendDataToAll = CASendEDRMulticastData;
-    handler.startNotifyServer = CAStartEDRNotifyServer;
-    handler.sendNotification = CASendEDRNotification;
     handler.GetnetInfo = CAGetEDRInterfaceInformation;
     handler.readData = CAReadEDRData;
     handler.stopAdapter = CAStopEDR;
@@ -111,63 +112,64 @@ CAResult_t CAStartEDRDiscoveryServer(void)
     return CAStartServer(OIC_BT_SERVICE_ID, &gDiscoveryServerID);
 }
 
-uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+                               uint32_t dataLength)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
     CAResult_t err = CA_STATUS_OK;
-    uint32_t sentLen = 0;
-    const char *serviceUUID = OIC_BT_SERVICE_ID;
 
     //Input validation
-    VERIFY_NON_NULL_RET(endpoint, BLUETOOTH_ADAPTER_TAG, "Remote endpoint is null", 0);
+    VERIFY_NON_NULL_RET(remoteEndpoint, BLUETOOTH_ADAPTER_TAG, "Remote endpoint is null", 0);
     VERIFY_NON_NULL_RET(data, BLUETOOTH_ADAPTER_TAG, "Data is null", 0);
 
-    if (0 == strlen(endpoint->addressInfo.BT.btMacAddress))
+    if (0 == strlen(remoteEndpoint->addressInfo.BT.btMacAddress))
     {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: Address is empty!");
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: BT Address is empty!");
         return 0;
     }
 
-    if (0 == dataLen)
+    if (0 == dataLength)
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: data length is zero!");
         return 0;
     }
 
-    if (CA_STATUS_OK != (err = CABTManagerSendData(endpoint->addressInfo.BT.btMacAddress,
-                               serviceUUID, data,
-                               dataLen, &sentLen)))
+    uint32_t sentLength = 0;
+    const char *serviceUUID = OIC_BT_SERVICE_ID;
+    const char *address = remoteEndpoint->addressInfo.BT.btMacAddress;
+    if (CA_STATUS_OK != (err = CABTManagerSendData(address, serviceUUID, data,
+                 dataLength, &sentLength)))
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Send unicast data failed!, error num [%d]", err);
         return 0;
     }
 
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
-    return sentLen;
+    return sentLength;
 }
 
-uint32_t CASendEDRMulticastData(void *data, uint32_t dataLen)
+uint32_t CASendEDRMulticastData(void *data, uint32_t dataLength)
 {
     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
 
     CAResult_t err = CA_STATUS_OK;
-    uint32_t sentLen = 0;
-    const char *serviceUUID = OIC_BT_SERVICE_ID;
 
     //Input validation
     VERIFY_NON_NULL_RET(data, BLUETOOTH_ADAPTER_TAG, "Data is null", 0);
 
-    if (0 == dataLen)
+    if (0 == dataLength)
     {
         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: data length is zero!");
         return 0;
     }
 
-    if (CA_STATUS_OK != (err = CABTManagerSendData(NULL, serviceUUID, data, dataLen,
+    uint32_t sentLen = 0;
+    const char *serviceUUID = OIC_BT_SERVICE_ID;
+    if (CA_STATUS_OK != (err = CABTManagerSendData(NULL, serviceUUID, data, dataLength,
                                &sentLen)))
     {
-        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, " Send multicast data failed!, error num [%d]",
+        OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Send multicast data failed!, error num [%d]",
                   err);
         return 0;
     }
@@ -176,19 +178,6 @@ uint32_t CASendEDRMulticastData(void *data, uint32_t dataLen)
     return sentLen;
 }
 
-CAResult_t CAStartEDRNotifyServer(void)
-{
-    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
-
-    return CAStartServer(OIC_BT_SERVICE_ID, &gNotificationServerID);
-}
-
-uint32_t CASendEDRNotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
-{
-    OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
-
-    return CASendEDRUnicastData(endpoint, data, dataLen);
-}
 
 CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
 {
index 91f6534..7b2c713 100644 (file)
@@ -57,7 +57,7 @@ static u_mutex gBleLocalAddressMutex = NULL;
 int32_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
 
 #ifdef __TIZEN__
-int32_t CALEDeviceStateChangedCb(int32_t result, bt_adapter_state_e adapter_state,
+void CALEDeviceStateChangedCb(int32_t result, bt_adapter_state_e adapter_state,
                                  void *user_data);
 CAResult_t CAInitBleAdapterMutex();
 CAResult_t CATermiateBleAdapterMutex();
@@ -103,8 +103,6 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
     connHandler.startDiscoverServer = CAStartLEDiscoveryServer;
     connHandler.sendData = CASendLEUnicastData;
     connHandler.sendDataToAll = CASendLEMulticastData;
-    connHandler.startNotifyServer = CAStartLENotifyServer;
-    connHandler.sendNotification = CASendLENotification;
     connHandler.GetnetInfo = CAGetLEInterfaceInformation;
     connHandler.readData = CAReadLEData;
     connHandler.terminate = CATerminateLE;
@@ -355,16 +353,10 @@ int32_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
 
 #ifdef __TIZEN__
 
-int32_t CALEDeviceStateChangedCb(int32_t result, bt_adapter_state_e adapter_state, void *user_data)
+void CALEDeviceStateChangedCb(int32_t result, bt_adapter_state_e adapter_state, void *user_data)
 {
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
 
-    bt_adapter_state_e btAdaptorState = BT_ADAPTER_DISABLED;
-    if (BT_ADAPTER_ENABLED == adapter_state)
-    {
-        btAdaptorState = BT_ADAPTER_ENABLED;
-    }
-
     CALocalConnectivity_t localEndpoint;
 
     u_mutex_lock(gBleLocalAddressMutex);
@@ -382,7 +374,6 @@ int32_t CALEDeviceStateChangedCb(int32_t result, bt_adapter_state_e adapter_stat
     }
     u_mutex_unlock(gBleNetworkCbMutex);
     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
 }
 
 CAResult_t CAInitBleAdapterMutex()
index 9f9ac9e..1daf199 100644 (file)
@@ -48,8 +48,6 @@ CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
     handler.startDiscoverServer = CAStartLEDiscoveryServer;
     handler.sendData = CASendLEUnicastData;
     handler.sendDataToAll = CASendLEMulticastData;
-    handler.startNotifyServer = CAStartLENotifyServer;
-    handler.sendNotification = CASendLENotification;
     handler.GetnetInfo = CAGetLEInterfaceInformation;
     handler.readData = CAReadLEData;
     handler.stopAdapter = CAStopLE;
@@ -95,20 +93,6 @@ uint32_t CASendLEMulticastData(void* data, uint32_t dataLen)
     return 0;
 }
 
-CAResult_t CAStartLENotifyServer()
-{
-    OIC_LOG_V(DEBUG, TAG, "CAStartLENotifyServer");
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendLENotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG_V(DEBUG, TAG, "CASendLENotification");
-
-    return 0;
-}
-
 CAResult_t CAGetLEInterfaceInformation(CALocalConnectivity_t** info, uint32_t* size)
 {
     OIC_LOG_V(DEBUG, TAG, "CAGetLEInterfaceInformation");
index f28fdd2..0b35ffe 100644 (file)
@@ -1,22 +1,22 @@
 /******************************************************************
- *
- * 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 "cableclient.h"
 
  */
 #define TZ_BLE_CLIENT_TAG "TZ_BLE_GATT_CLIENT"
 
+/**
+ * @var BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG
+ * @brief Its the constant value for characteristic descriptor from spec.
+ */
+#define BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG 0x2902
+
+/**
+ * @var gBLEServiceList
+ * @brief This contains the list of OIC services a client connect tot.
+ */
 static BLEServiceList *gBLEServiceList = NULL;
 
+/**
+ * @var gIsBleGattClientStarted
+ * @brief Boolean variable to keep the state of the GATT Client.
+ */
 static CABool_t gIsBleGattClientStarted = CA_FALSE;
 
+/**
+ * @var gCABleClientSenderQueue
+ * @brief Queue to process the outgoing packets from GATTClient.
+ */
 static CAAdapterMessageQueue_t *gCABleClientSenderQueue = NULL;
 
+/**
+ * @var gCABleClientReceiverQueue
+ * @brief Queue to process the incoming packets to GATT Client.
+ */
 static CAAdapterMessageQueue_t *gCABleClientReceiverQueue = NULL;
 
+/**
+ * @var gBleServiceListMutex
+ * @brief Mutex to synchronize access to BleServiceList.
+ */
 static u_mutex gBleServiceListMutex = NULL;
 
+/**
+ * @var gBleReqRespClientCbMutex
+ * @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;
 
+/**
+ * @var gBleClientStateMutex
+ * @brief Mutex to synchronize the calls to be done to the platform from GATTClient
+ *           interfaces from different threads.
+ */
 static u_mutex gBleClientStateMutex = NULL;
 
+/**
+ * @var gBleClientSendDataMutex
+ * @brief Mutex to synchronize the queing of the data from SenderQueue.
+ */
 static u_mutex gBleClientSendDataMutex = NULL;
 
+/**
+ * @var gBleClientSendCondWait
+ * @brief Condition used for notifying handler the presence of data in send queue.
+ */
 static u_cond gBleClientSendCondWait = NULL;
 
+/**
+ * @var gBleClientReceiveDataMutex
+ * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
+ */
 static u_mutex gBleClientReceiveDataMutex = NULL;
 
+/**
+ * @var gBleClientThreadPoolMutex
+ * @brief Mutex to synchronize the task to be pushed to thread pool.
+ */
 static u_mutex gBleClientThreadPoolMutex = NULL;
 
-static CANetworkPacketReceivedCallback gReqRespClientCallback = NULL;
+/**
+ * @var gNetworkPacketReceivedClientCallback
+ * @brief Maintains the callback to be notified on receival of network packets from other
+ *           BLE devices
+ */
+static CANetworkPacketReceivedCallback gNetworkPacketReceivedClientCallback = NULL;
 
+/**
+ * @var gClientUp
+ * @brief Boolean variable to maintain the GATT Client state.
+ */
 static CABool_t gClientUp = CA_FALSE;
 
+/**
+ * @var g_event_loop
+ * @brief gmainLoop to manage the threads to receive the callback from the platfrom.
+ */
 static GMainLoop *g_event_loop = NULL;
 
+/**
+ * @var gBleClientThreadPool
+ * @brief reference to threadpool
+ */
 static u_thread_pool_t gBleClientThreadPool = NULL;
 
+/**
+ * @struct stGattServiceInfo_t
+ * @brief structure to map the service attribute to BD Address.
+ *
+ */
 typedef struct gattService
 {
-    bt_gatt_attribute_h serviceInfo;
-    char *address;
+    bt_gatt_attribute_h serviceInfo;         /**< bluetoth attribute for oic service*/
+    char *address;                                  /**< BD Address of */
 } stGattServiceInfo_t;
 
-void CABleGattCharacteristicWriteCb(bt_gatt_attribute_h handle)
+void CABleGattCharacteristicWriteCb(int result, void *user_data)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
 
+
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
 }
 
@@ -91,16 +166,17 @@ void *CABleClientSenderQueueProcessor()
     {
         CAAdapterMessage_t *senderData = NULL;
 
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, " conditional wait");
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, " Waiting for the data ... ");
 
         u_mutex_lock(gBleClientSendDataMutex);
         u_cond_wait(gBleClientSendCondWait, gBleClientSendDataMutex);
 
-        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "wait unlocked");
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Data got pushed to the queue...");
 
         CAResult_t result = CA_STATUS_FAILED;
 
-        while (CA_STATUS_OK == CAAdapterDequeueMessage(gCABleClientSenderQueue, &senderData))
+        while (CA_STATUS_OK == CAAdapterDequeueMessage(gCABleClientSenderQueue,
+                &senderData))
         {
             if (NULL == senderData)
             {
@@ -112,29 +188,26 @@ void *CABleClientSenderQueueProcessor()
                 OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Sending Unicast data");
                 const char *bdAddress = senderData->remoteEndpoint->addressInfo.LE.leMacAddress;
 
-                if (NULL == bdAddress)
-                {
-                    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "bdAddress is NULL");
-                    continue;
-                }
+                VERIFY_NON_NULL_RET(bdAddress, TZ_BLE_CLIENT_TAG, "bdAddress is NULL", NULL);
 
                 result = CAUpdateCharacteristicsToGattServer(bdAddress, senderData->data,
-                        senderData->dataLen, UNICAST, 0);
+                         senderData->dataLen,
+                         UNICAST, 0);
                 if (CA_STATUS_OK != result)
                 {
                     OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                            "Failed to UpdateCharacteristicsToGattServer [%s]", bdAddress);
+                              "Failed to UpdateCharacteristicsToGattServer [%s]", bdAddress);
                 }
             }
             else
             {
                 OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Sending Multicast data");
                 result = CAUpdateCharacteristicsToAllGattServers(senderData->data,
-                        senderData->dataLen);
+                         senderData->dataLen);
                 if (CA_STATUS_OK != result)
                 {
                     OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                            "Failed to UpdateCharacteristicsToAllGattServers !");
+                              "Failed to UpdateCharacteristicsToAllGattServers !");
                 }
             }
 
@@ -148,24 +221,23 @@ void *CABleClientSenderQueueProcessor()
     return NULL;
 }
 
+
 CAResult_t CASetCharacteristicDescriptorValue(stGattCharDescriptor_t *stGattCharDescriptorInfo)
 {
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
     uint8_t desc[stGattCharDescriptorInfo->total];
-    unsigned char noti[4] =
-    { 0, };
+    unsigned char noti[4] = {0,};
     char *strUUID = NULL;
 
-    memcpy(desc, (uint8_t *) stGattCharDescriptorInfo->descriptor, stGattCharDescriptorInfo->total);
+    memcpy(desc, (uint8_t *)stGattCharDescriptorInfo->descriptor,
+           stGattCharDescriptorInfo->total);
+
+    strUUID =  (char *)OICMalloc(sizeof(char) * 5);
+
+    VERIFY_NON_NULL_RET(strUUID, TZ_BLE_CLIENT_TAG, "malloc failed", CA_STATUS_FAILED);
 
-    strUUID = (char *) OICMalloc(sizeof(char) * 5);
-    if (NULL == strUUID)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "malloc failure!");
-        return CA_STATUS_FAILED;
-    }
     memset(strUUID, 0x0, sizeof(char) * 5);
     snprintf(strUUID, 4, "%x%x", desc[3], desc[2]);
     noti[0] = desc[0];
@@ -173,19 +245,19 @@ CAResult_t CASetCharacteristicDescriptorValue(stGattCharDescriptor_t *stGattChar
     noti[2] = 0x01;
     noti[3] = 0x00;
 
-    if (!strncmp(strUUID, "2902", 2))
+    if (!strncmp(strUUID, BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG, 2))
     {
-        int32_t ret = 0;
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "setting notification/indication for descriptor");
 
-        ret = bt_gatt_set_characteristic_desc_value_request(
-                stGattCharDescriptorInfo->characteristic, noti, 4, CABleGattCharacteristicWriteCb);
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "setting notification/indication for descriptor");
 
+        int32_t ret =  bt_gatt_set_characteristic_desc_value_request(
+                           stGattCharDescriptorInfo->characteristic,
+                           noti,  4, CABleGattCharacteristicWriteCb);
         if (BT_ERROR_NONE != ret)
         {
             OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                    "bt_gatt_set_characteristic_desc_value_request failed with return[%s] \n",
-                    CABTGetErrorMsg(ret));
+                      "bt_gatt_set_characteristic_desc_value_request failed with return[%s] \n",
+                      CABTGetErrorMsg(ret));
             OICFree(strUUID);
             return CA_STATUS_FAILED;
         }
@@ -203,21 +275,13 @@ void *CASetCharacteristicDescriptorValueThread(void *stServiceInfo)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
-    if (NULL == stServiceInfo)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Param stServiceInfo is NULL");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL", NULL);
 
-    stGattCharDescriptor_t *stTemp = (stGattCharDescriptor_t *) stServiceInfo;
+    stGattCharDescriptor_t *stTemp  = (stGattCharDescriptor_t *)stServiceInfo;
 
-    if (NULL == stTemp)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "stTemp is NULL");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "stTemp is NULL", NULL);
 
-    CAResult_t result = CASetCharacteristicDescriptorValue(stTemp);
+    CAResult_t  result = CASetCharacteristicDescriptorValue(stTemp);
 
     if (CA_STATUS_OK != result)
     {
@@ -229,19 +293,18 @@ void *CASetCharacteristicDescriptorValueThread(void *stServiceInfo)
     return NULL;
 }
 
-void CABleGattDescriptorDiscoveredCb(int result, unsigned char format, int total,
-        bt_gatt_attribute_h descriptor, bt_gatt_attribute_h characteristic, void *userData)
+
+void CABleGattDescriptorDiscoveredCb(int32_t result, unsigned char format, int32_t 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 *)OICMalloc(sizeof(
+                                         stGattCharDescriptor_t));
+
+    VERIFY_NON_NULL_VOID(stTemp, TZ_BLE_CLIENT_TAG, "stTemp is NULL");
 
-    if (NULL == stTemp)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "stTemp is NULL");
-        return;
-    }
     bt_gatt_clone_attribute_handle(&(stTemp->descriptor), descriptor);
 
     bt_gatt_clone_attribute_handle(&(stTemp->characteristic), characteristic);
@@ -253,31 +316,31 @@ void CABleGattDescriptorDiscoveredCb(int result, unsigned char format, int total
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gBleClientThreadPool is NULL");
         OICFree(stTemp);
         u_mutex_unlock(gBleClientThreadPoolMutex);
-        return;
+        return ;
     }
 
     CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool,
-            (void *) CASetCharacteristicDescriptorValueThread, (void *) stTemp);
+                                            (void *) CASetCharacteristicDescriptorValueThread,
+                                            (void *) stTemp);
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed with ret [%d]", ret);
         OICFree(stTemp);
         u_mutex_unlock(gBleClientThreadPoolMutex);
-        //CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo, bleServiceInfo->bdAddress);
-        return;
+        return ;
     }
 
-    sleep(2);
-    ret = u_thread_pool_add_task(gBleClientThreadPool, (void *) CABleClientSenderQueueProcessor,
-            (void *) NULL);
+    ret = u_thread_pool_add_task(gBleClientThreadPool,
+                                 (void *) CABleClientSenderQueueProcessor,
+                                 (void *) NULL);
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed with ret [%d]", ret);
         u_mutex_unlock(gBleClientThreadPoolMutex);
-        //CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo, bleServiceInfo->bdAddress);
-        return;
+        return ;
     }
     u_mutex_unlock(gBleClientThreadPoolMutex);
+
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG,
             "LE Client initialization complete. Enabling gClientUp state to TRUE ");
     gClientUp = CA_TRUE;
@@ -290,21 +353,18 @@ void *CADiscoverDescriptorThread(void *stServiceInfo)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, " IN");
 
-    if (NULL == stServiceInfo)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL");
-        return NULL;
-    }
-    stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *) stServiceInfo;
+    VERIFY_NON_NULL_RET(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL", NULL);
+
+    stGattServiceInfo_t *stTemp  = (stGattServiceInfo_t *)stServiceInfo;
 
     int32_t ret = bt_gatt_discover_characteristic_descriptor(stTemp->serviceInfo,
-            CABleGattDescriptorDiscoveredCb, NULL);
+                  CABleGattDescriptorDiscoveredCb, NULL);
 
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                "bt_gatt_discover_characteristic_descriptor failed with returns[%s] \n",
-                CABTGetErrorMsg(ret));
+                  "bt_gatt_discover_characteristic_descriptor failed with returns[%s] \n",
+                  CABTGetErrorMsg(ret));
         return NULL;
     }
 
@@ -316,24 +376,15 @@ void *CADiscoverCharThread(void *stServiceInfo)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
-    if (NULL == stServiceInfo)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Param stServiceInfo is NULL");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL", NULL);
 
-    stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *) stServiceInfo;
+    stGattServiceInfo_t *stTemp  = (stGattServiceInfo_t *)stServiceInfo;
 
-    if (NULL == stTemp)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "stTemp is NULL");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "stTemp is NULL", NULL);
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address [%s]", stTemp->address);
 
-    CAResult_t result = CABleDiscoverCharacteristics(stTemp->serviceInfo, stTemp->address);
-
+    CAResult_t  result = CABleDiscoverCharacteristics(stTemp->serviceInfo, stTemp->address);
     bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
 
     OICFree(stTemp->address);
@@ -345,7 +396,6 @@ void *CADiscoverCharThread(void *stServiceInfo)
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG , "CABleDiscoverCharacteristics failed!");
         return NULL;
     }
-
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
     return NULL;
 }
@@ -353,23 +403,25 @@ void *CADiscoverCharThread(void *stServiceInfo)
 void CABtGattBondCreatedCb(int32_t result, bt_device_info_s *device_info, void *user_data)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
-    if (result == BT_ERROR_NONE)
+    if (BT_ERROR_NONE != result)
     {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "A bond with chat_server is created.");OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Callback: The number of service : %d.",
-                device_info->service_count);
-
-        int32_t i = 0;
+        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
+                  " create_bond Failed as [%s ]", CABTGetErrorMsg(result));
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "A bond with chat_server is created.");
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Callback: The number of service : %d.",
+                  device_info->service_count);
 
         char *bdAddress = device_info->remote_address;
 
         int32_t len = strlen(bdAddress);
 
-        char *addr = (char *) OICMalloc(sizeof(char) * len + 1);
-        if (NULL == addr)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc  failed! ");
-            return;
-        }
+        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, bdAddress, len);
@@ -386,37 +438,37 @@ void CABtGattBondCreatedCb(int32_t result, bt_device_info_s *device_info, void *
         {
             OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "CAGetBLEServiceInfo failed! ");
             bleServiceInfo = NULL;
-            return;
+            return ;
         }
 
         int32_t ret = CAVerifyOICService(bleServiceInfo->service_clone);
-
-        if (CA_STATUS_OK == ret)
+        if (CA_STATUS_OK != ret)
+        {
+            OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG,
+                    "We dont need to interact with this generic BLE device since it deos not have OIC service");
+        }
+        else
         {
             OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its OIC service");
 
             OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG ,
-                    " serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
+                      " serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
 
-            stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *) OICMalloc(
-                    sizeof(stGattServiceInfo_t));
-            if (NULL == stTemp)
-            {
-                OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc  failed! ");
-                return;
-            }
+            stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICMalloc(sizeof(stGattServiceInfo_t));
+
+            VERIFY_NON_NULL_VOID(stTemp, TZ_BLE_CLIENT_TAG, "malloc failed");
 
             bt_gatt_clone_attribute_handle(&(stTemp->serviceInfo), bleServiceInfo->service_clone);
 
             len = strlen(bleServiceInfo->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! ");
                 bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
                 OICFree(stTemp);
-                return;
+                return ;
             }
             memset(stTemp->address, 0x0, len + 1);
 
@@ -430,73 +482,55 @@ void CABtGattBondCreatedCb(int32_t result, bt_device_info_s *device_info, void *
                 OICFree(stTemp->address);
                 OICFree(stTemp);
                 u_mutex_unlock(gBleClientThreadPoolMutex);
-                /*CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo,
-                 * bleServiceInfo->bdAddress); */
-                return;
+                return ;
             }
 
             CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool,
-                    (void *) CADiscoverCharThread, (void *) stTemp);
+                                                    (void *) CADiscoverCharThread, (void *) stTemp);
             if (CA_STATUS_OK != ret)
             {
                 OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                        "u_thread_pool_add_task failed with ret [%d]", ret);
+                          "u_thread_pool_add_task failed with ret [%d]", ret);
                 bt_gatt_destroy_attribute_handle(stTemp->serviceInfo);
                 OICFree(stTemp->address);
                 OICFree(stTemp);
                 u_mutex_unlock(gBleClientThreadPoolMutex);
-                return;
+                return ;
             }
             u_mutex_unlock(gBleClientThreadPoolMutex);
         }
-        else
-        {
-            OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its not OIC service!! ");
-        }
 
         OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-                "Callback: is_bonded - %d.", device_info->is_bonded);OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-                "Callback: is_connected - %d.", device_info->is_connected);
+                  "Callback: is_bonded - %d.", device_info->is_bonded);
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
+                  "Callback: is_connected - %d.", device_info->is_connected);
 
     }
-    else
-    {
-        OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                " create_bond Failed as [%s ]", CABTGetErrorMsg(result));
-    }OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
 }
 
 void *CAGATTCreateBondThread(void *stServiceInfo)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
-    if (NULL == stServiceInfo)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Param stServiceInfo is NULL");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(stServiceInfo, TZ_BLE_CLIENT_TAG, "stServiceInfo is NULL", NULL);
 
-    stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *) stServiceInfo;
+    stGattServiceInfo_t *stTemp  = (stGattServiceInfo_t *)stServiceInfo;
 
-    if (NULL == stTemp)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "stTemp is NULL");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(stTemp, TZ_BLE_CLIENT_TAG, "stTemp is NULL", NULL);
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address [%s]",
-            stTemp->address);
+              stTemp->address);
 
-    CAResult_t result = CABleGATTCreateBond(stTemp->address);
+    CAResult_t  result = CABleGATTCreateBond(stTemp->address);
 
     OICFree(stTemp->address);
-
     OICFree(stTemp);
 
     if (CA_STATUS_OK != result)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG ,
-                "CABleDiscoverCharacteristics failed!");
+                  "CABleDiscoverCharacteristics failed!");
         return NULL;
     }
 
@@ -504,8 +538,9 @@ void *CAGATTCreateBondThread(void *stServiceInfo)
     return NULL;
 }
 
-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,
+                                      int32_t valueLen, void *userData)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
@@ -520,35 +555,16 @@ void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic, unsign
         OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Changed characteristic  value %c", value[i]);
     }
 
-    CARemoteEndpoint_t *remoteEndPoint = (CARemoteEndpoint_t *) OICMalloc(
-            sizeof(CARemoteEndpoint_t));
-    if (NULL == remoteEndPoint)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Malloc Failure!");
-        return;
-    }
+    CARemoteEndpoint_t  *remoteEndPoint = (CARemoteEndpoint_t *) OICMalloc(sizeof(CARemoteEndpoint_t));
+
+    VERIFY_NON_NULL_VOID(remoteEndPoint, TZ_BLE_CLIENT_TAG, "malloc failed");
+
     memset(remoteEndPoint, 0x0, sizeof(CARemoteEndpoint_t));
 
     ///TODO: Currently Empty endpoint is being sent.
     ///TODO:Later proper remote address has to be added when tizen team changed their code
-#if 0
-    VERIFY_NON_NULL(gCABleClientReceiverQueue, TZ_BLE_CLIENT_TAG,
-            "BleClientReceiverQueue is  NULL");
-    u_mutex_lock(gBleClientReceiveDataMutex);
-    CAResult_t retVal = CAAdapterEnqueueMessage(gCABleClientReceiverQueue,
-            remoteEndPoint, value,
-            valueLen);
-    if (CA_STATUS_OK != retVal )
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAAdapterEnqueueMessage failed!");
-        u_mutex_unlock(gBleClientReceiveDataMutex);
-        CATerminateBLEGattClient();
-        return;
-    }
-    u_mutex_unlock(gBleClientReceiveDataMutex);
-#endif
 
-    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!");
@@ -557,20 +573,20 @@ void CABleGattCharacteristicChangedCb(bt_gatt_attribute_h characteristic, unsign
     }
 
     memset(data, 0x0, valueLen + 1);
-
     strncpy(data, value, valueLen);
 
     u_mutex_lock(gBleReqRespClientCbMutex);
-    if (NULL == gReqRespClientCallback)
+    if (NULL == gNetworkPacketReceivedClientCallback)
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gReqRespCallback is NULL!");
         OICFree(value);
         OICFree(remoteEndPoint);
+        OICFree(data);
         u_mutex_unlock(gBleReqRespClientCbMutex);
         return;
     }
 
-    gReqRespClientCallback(remoteEndPoint, data, valueLen);
+    gNetworkPacketReceivedClientCallback(remoteEndPoint, data, valueLen);
 
     u_mutex_unlock(gBleReqRespClientCbMutex);
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
@@ -591,16 +607,19 @@ CABool_t CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, void *userData)
 
     int32_t ret = CAVerifyOICService(service);
 
-    if (CA_STATUS_OK == ret)
+    if (CA_STATUS_OK != ret)
+    {
+        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "No need to process the service ");
+    }
+    else
     {
-
         OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its OIC service");
 
-        char *bdAddress = (char *) userData;
+        char *bdAddress = (char *)userData;
 
         int32_t len = strlen(bdAddress);
 
-        char *addr = (char *) OICMalloc(sizeof(char) * len + 1);
+        char *addr = (char *)OICMalloc(sizeof(char) * len + 1);
         if (NULL == addr)
         {
             OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "malloc failed! ");
@@ -624,7 +643,7 @@ CABool_t CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, void *userData)
         }
 
         OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG ,
-                " serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
+                  " serviceInfo remote address [%s]", bleServiceInfo->bdAddress);
 
         u_mutex_lock(gBleServiceListMutex);
         result = CAAddBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo);
@@ -645,23 +664,22 @@ CABool_t CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, void *userData)
         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));
             u_mutex_lock(gBleServiceListMutex);
-            CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo,
-                    bleServiceInfo->bdAddress);
+            CARemoveBLEServiceInfoToList(&gBLEServiceList,
+                                         bleServiceInfo, bleServiceInfo->bdAddress);
             u_mutex_unlock(gBleServiceListMutex);
             return false;
         }
 
-        stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *) OICMalloc(
-                sizeof(stGattServiceInfo_t));
+        stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICMalloc(sizeof(stGattServiceInfo_t));
 
         if (NULL == stTemp)
         {
             OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc  failed! ");
             u_mutex_lock(gBleServiceListMutex);
-            CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo,
-                    bleServiceInfo->bdAddress);
+            CARemoveBLEServiceInfoToList(&gBLEServiceList,
+                                         bleServiceInfo, bleServiceInfo->bdAddress);
             u_mutex_unlock(gBleServiceListMutex);
             return false;
         }
@@ -670,14 +688,14 @@ CABool_t CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, void *userData)
 
         len = strlen(bleServiceInfo->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! ");
             u_mutex_lock(gBleServiceListMutex);
             CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo,
-                    bleServiceInfo->bdAddress);
+                                         bleServiceInfo->bdAddress);
             u_mutex_unlock(gBleServiceListMutex);
             OICFree(stTemp);
             return false;
@@ -695,39 +713,38 @@ CABool_t CABleGattPrimaryServiceCb(bt_gatt_attribute_h service, void *userData)
             OICFree(stTemp);
             u_mutex_lock(gBleServiceListMutex);
             CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo,
-                    bleServiceInfo->bdAddress);
+                                         bleServiceInfo->bdAddress);
             u_mutex_unlock(gBleServiceListMutex);
             u_mutex_unlock(gBleClientThreadPoolMutex);
             return false;
         }
 
-        result = u_thread_pool_add_task(gBleClientThreadPool, (void *) CAGATTCreateBondThread,
-                (void *) stTemp);
+        result = u_thread_pool_add_task(gBleClientThreadPool,
+                                        (void *) CAGATTCreateBondThread,
+                                        (void *) stTemp);
         if (CA_STATUS_OK != result)
         {
             OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                    "u_thread_pool_add_task failed with ret [%d]", result);
+                      "u_thread_pool_add_task failed with ret [%d]", result);
             OICFree(stTemp->address);
             OICFree(stTemp);
             u_mutex_lock(gBleServiceListMutex);
             CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo,
-                    bleServiceInfo->bdAddress);
+                                         bleServiceInfo->bdAddress);
             u_mutex_unlock(gBleServiceListMutex);
             u_mutex_unlock(gBleClientThreadPoolMutex);
             return false;
         }
         u_mutex_unlock(gBleClientThreadPoolMutex);
     }
-    else
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Its not OIC service!! ");
-    }
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
     return true;;
 }
 
-CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex, int32_t total,
+
+CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result,
+        int32_t inputIndex, int32_t total,
         bt_gatt_attribute_h characteristic, void *userData)
 {
 
@@ -740,11 +757,11 @@ CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex
     }
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-            "result [%d] input_index [%d] total [%d]",
-            result, inputIndex, total);
+              "result [%d] input_index [%d] total [%d]",
+              result, inputIndex, total);
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-            "new characteristic found is [%s]", (char *)characteristic);
+              "new characteristic found is [%s]", (char *)characteristic);
 
     char *bdAddress = (char *) userData;
 
@@ -756,7 +773,7 @@ CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex
 
     u_mutex_unlock(gBleServiceListMutex);
 
-    if (1 == inputIndex)
+    if ( READ_CHAR_INDEX == inputIndex)
     {
         CAResult_t retVal = CAAppendBLECharInfo(characteristic, READ_CHAR, bleServiceInfo);
         if (CA_STATUS_OK != retVal)
@@ -765,7 +782,7 @@ CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex
             return false;
         }
     }
-    else if (2 == inputIndex)
+    else if ( WRITE_CHAR_INDEX == inputIndex)
     {
         CAResult_t retVal = CAAppendBLECharInfo(characteristic, WRITE_CHAR, bleServiceInfo);
         if (CA_STATUS_OK != retVal)
@@ -776,7 +793,7 @@ CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex
 
     }
 
-    stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *) OICMalloc(sizeof(stGattServiceInfo_t));
+    stGattServiceInfo_t *stTemp = (stGattServiceInfo_t *)OICMalloc(sizeof(stGattServiceInfo_t));
 
     if (NULL == stTemp)
     {
@@ -790,7 +807,7 @@ CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex
 
     int32_t len = strlen(bleServiceInfo->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! ");
@@ -810,11 +827,13 @@ CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex
         OICFree(stTemp->address);
         OICFree(stTemp);
         u_mutex_unlock(gBleClientThreadPoolMutex);
+        //CARemoveBLEServiceInfoToList(&gBLEServiceList, bleServiceInfo, bleServiceInfo->bdAddress);
         return false;
     }
 
     CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool,
-            (void *) CADiscoverDescriptorThread, (void *) stTemp);
+                                            (void *) CADiscoverDescriptorThread,
+                                            (void *) stTemp);
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed with ret [%d]", ret);
@@ -831,7 +850,7 @@ CABool_t CABleGattCharacteristicsDiscoveredCb(int32_t result, int32_t inputIndex
 
 }
 
-CAResult_t CABleClientSenderQueueEnqueueMessage(CARemoteEndpoint_t *remoteEndpoint, void *data,
+CAResult_t CABleClientSenderQueueEnqueueMessage(const CARemoteEndpoint_t *remoteEndpoint, void *data,
         uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
@@ -839,21 +858,25 @@ CAResult_t CABleClientSenderQueueEnqueueMessage(CARemoteEndpoint_t *remoteEndpoi
     VERIFY_NON_NULL(data, NULL, "Param data is NULL");
 
     VERIFY_NON_NULL_RET(gCABleClientSenderQueue, TZ_BLE_CLIENT_TAG,
-            "BleClientReceiverQueue is  NULL", CA_STATUS_FAILED);
+                        "BleClientReceiverQueue is  NULL",
+                        CA_STATUS_FAILED);
     VERIFY_NON_NULL_RET(gBleClientSendDataMutex, TZ_BLE_CLIENT_TAG,
-            "BleClientSendDataMutex is NULL", CA_STATUS_FAILED);
-    VERIFY_NON_NULL_RET(gBleClientSendCondWait, TZ_BLE_CLIENT_TAG, "BleClientSendCondWait is NULL",
-            CA_STATUS_FAILED);
+                        "BleClientSendDataMutex is NULL",
+                        CA_STATUS_FAILED);
+    VERIFY_NON_NULL_RET(gBleClientSendCondWait, TZ_BLE_CLIENT_TAG,
+                        "BleClientSendCondWait is NULL",
+                        CA_STATUS_FAILED);
 
     u_mutex_lock(gBleClientSendDataMutex);
-    CAResult_t retVal = CAAdapterEnqueueMessage(gCABleClientSenderQueue, remoteEndpoint, data,
-            dataLen);
-    if (CA_STATUS_OK != retVal)
+    CAResult_t retVal = CAAdapterEnqueueMessage(gCABleClientSenderQueue,
+                        remoteEndpoint, data, dataLen);
+    if (CA_STATUS_OK != retVal )
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAAdapterEnqueueMessage failed!");
         u_mutex_unlock(gBleClientSendDataMutex);
         return CA_STATUS_FAILED;
-    }OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Sending signal for the sender processor ");
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Sending signal for the sender processor ");
     u_mutex_unlock(gBleClientSendDataMutex);
     u_cond_signal(gBleClientSendCondWait);
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
@@ -861,41 +884,21 @@ CAResult_t CABleClientSenderQueueEnqueueMessage(CARemoteEndpoint_t *remoteEndpoi
     return CA_STATUS_OK;
 }
 
+
 CAResult_t CALEReadDataFromLEClient()
 {
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
-#if 0
-    CAAdapterMessage_t *receiverData = NULL;
 
-    u_mutex_lock(gBleClientReceiveDataMutex);
-    CAResult_t result = CAAdapterDequeueMessage(gCABleClientReceiverQueue, &receiverData);
+    ///TODO: If CA layer request for the data, this function ll be implemented.
 
-    if (CA_STATUS_OK != result)
-    {
-        u_mutex_lock(gBleReqRespClientCbMutex);
-        if (NULL == gReqRespClientCallback)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "gReqRespClientCallback is NULL!");
-            CAAdapterFreeMessage(receiverData);
-            u_mutex_unlock(gBleReqRespClientCbMutex);
-            u_mutex_unlock(gBleClientReceiveDataMutex);
-            return;
-        }
-
-        gReqRespClientCallback(receiverData->remoteEndpoint, receiverData->data, receiverData->dataLen);
-
-        CAAdapterFreeMessage(receiverData);
-    }
-    u_mutex_unlock(gBleClientReceiveDataMutex);
-
-#endif
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT ");
 
     return CA_STATUS_OK;
 }
 
-void *CAGattConnectThread(void *remoteAddress)
+
+void *CAGattConnectThread (void *remoteAddress)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
 
@@ -905,7 +908,7 @@ void *CAGattConnectThread(void *remoteAddress)
         return NULL;
     }
 
-    char *address = (char *) remoteAddress;
+    char *address  = (char *)remoteAddress;
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "remote address is [%s]", address);
 
@@ -940,55 +943,51 @@ void CAPrintDiscoveryInformation(bt_adapter_le_device_discovery_info_s *discover
     }
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-            " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
-            discoveryInfo->adv_data_len, discoveryInfo->scan_data_len, discoveryInfo->rssi,
-            discoveryInfo->address_type);OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+              " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
+              discoveryInfo->adv_data_len, discoveryInfo->scan_data_len, discoveryInfo->rssi,
+              discoveryInfo->address_type);
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
 }
 
 void CABtAdapterLeDeviceDiscoveryStateChangedCb(int32_t result,
         bt_adapter_le_device_discovery_state_e discoveryState,
-        bt_adapter_le_device_discovery_info_s *discoveryInfo, void *userData)
+        bt_adapter_le_device_discovery_info_s *discoveryInfo,
+        void *userData)
 {
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
-    if (discoveryInfo == NULL && discoveryState == BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND)
+    if (NULL  == discoveryInfo && BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND == discoveryState)
     {
         OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "discoveryInfo is NULL");
         return;
     }
 
-    if (discoveryState != BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND)
+    if (BT_ADAPTER_LE_DEVICE_DISCOVERY_FOUND != discoveryState)
     {
         OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG,
-                " LE Discovery state is [%s]",
-                discoveryState == BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED ? "Started" : "Finished" );
+                  " LE Discovery state is [%s]",
+                  discoveryState == BT_ADAPTER_LE_DEVICE_DISCOVERY_STARTED ? "Started" : "Finished" );
     }
     else
     {
 
         CAPrintDiscoveryInformation(discoveryInfo);
 
-        if (NULL == discoveryInfo->remote_address)
-        {
-            OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "discoveryInfo->remote_address is NULL");
-            return;
-        }
+        VERIFY_NON_NULL_VOID(discoveryInfo->remote_address, TZ_BLE_CLIENT_TAG,
+                        "discoveryInfo->remote_address is NULL");
 
         int32_t len = strlen(discoveryInfo->remote_address);
 
-        char *addr = (char *) OICMalloc(sizeof(char) * len + 1);
-        if (NULL == addr)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc  failed! ");
-            return;
-        }
-        memset(addr, 0x0, len + 1);
+        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);
 
         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)
@@ -1000,7 +999,7 @@ void CABtAdapterLeDeviceDiscoveryStateChangedCb(int32_t result,
         }
 
         CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool, (void *) CAGattConnectThread,
-                (void *) addr);
+                                                (void *) addr);
         if (CA_STATUS_OK != ret)
         {
             OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed with ret [%d]", ret);
@@ -1015,20 +1014,18 @@ void CABtAdapterLeDeviceDiscoveryStateChangedCb(int32_t result,
             return;
         }
 
-    }OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
 }
 
-void *CADiscoverBLEServicesThread(void *remoteAddress)
+
+void *CADiscoverBLEServicesThread (void *remoteAddress)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
-    if (NULL == remoteAddress)
-    {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Param remoteAddress is NULL ");
-        return NULL;
-    }
+    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL", NULL);
 
-    char *address = (char *) remoteAddress;
+    char *address  = (char *)remoteAddress;
 
     CAResult_t result = CABleDiscoverServices(remoteAddress);
 
@@ -1046,31 +1043,30 @@ void *CADiscoverBLEServicesThread(void *remoteAddress)
 }
 
 void CABleGattConnectionStateChangedCb(int32_t result, bool connected, const char *remoteAddress,
-        void *userData)
+                                       void *userData)
 {
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN ");
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "CABleGattConnectionStateChangedCb result[%d] ", result);
 
-    if (NULL == remoteAddress)
+    VERIFY_NON_NULL_VOID(remoteAddress, TZ_BLE_CLIENT_TAG, "remote address is NULL");
+
+    if (!connected)
+
     {
-        OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Param remoteAddress is NULL ");
-        return;
+        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "DisConnected from [%s] ", remoteAddress);
     }
-
-    if (connected)
+    else
     {
 
         OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "Connected to [%s] ", remoteAddress);
 
         int32_t len = strlen(remoteAddress);
 
-        char *addr = (char *) OICMalloc(sizeof(char) * len + 1);
-        if (NULL == addr)
-        {
-            OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc  failed! ");
-            return;
-        }
+        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, remoteAddress, len);
@@ -1084,8 +1080,8 @@ void CABleGattConnectionStateChangedCb(int32_t result, bool connected, const cha
             return;
         }
 
-        CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool,
-                (void *) CADiscoverBLEServicesThread, (void *) addr);
+        CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool, (void *) CADiscoverBLEServicesThread,
+                                                (void *) addr);
         if (CA_STATUS_OK != ret)
         {
             OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed with ret [%d]", ret);
@@ -1095,10 +1091,6 @@ void CABleGattConnectionStateChangedCb(int32_t result, bool connected, const cha
         }
         u_mutex_unlock(gBleClientThreadPoolMutex);
     }
-    else
-    {
-        OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "DisConnected from [%s] ", remoteAddress);
-    }
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
 }
@@ -1108,13 +1100,10 @@ CAResult_t CABleGATTCreateBond(const char *remoteAddress)
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
-    if (NULL == remoteAddress)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "remoteAddress  is NULL! ");
-        return CA_STATUS_FAILED;
-    }
+    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
+                        "remote address is NULL", CA_STATUS_FAILED);
 
-    VERIFY_NON_NULL(remoteAddress, NULL, "Param remoteAddress is NULL");
+    sleep(2);
 
     int32_t ret = bt_device_create_bond(remoteAddress);
 
@@ -1126,8 +1115,9 @@ CAResult_t CABleGATTCreateBond(const char *remoteAddress)
     else
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                " bt_device_create_bond query success for address [%s]", remoteAddress);
-    }OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+                  " bt_device_create_bond query success for address [%s]", remoteAddress);
+    }
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
 
     return CA_STATUS_OK;
 
@@ -1138,36 +1128,33 @@ CAResult_t CABleDiscoverServices(const char *remoteAddress)
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
-    VERIFY_NON_NULL(remoteAddress, NULL, "Param remoteAddress is NULL");
-
+    VERIFY_NON_NULL_RET(remoteAddress, TZ_BLE_CLIENT_TAG,
+                        "remote address is NULL", CA_STATUS_FAILED);
     sleep(2);
 
     int32_t len = strlen(remoteAddress);
 
-    char *addr = (char *) OICMalloc(sizeof(char) * len + 1);
-    if (NULL == addr)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc  failed! ");
-        return CA_STATUS_FAILED;
-    }
-    memset(addr, 0x0, len + 1);
+    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);
 
     int32_t ret = bt_gatt_foreach_primary_services(remoteAddress, CABleGattPrimaryServiceCb,
-            (void *) addr); //addr memory will be free in callback.
-
+                  (void *)addr); //addr memory will be free in callback.
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_foreach_primary_services Failed with ret value [%d] ",
-                ret);
+                  ret);
         OICFree(addr);
         return CA_STATUS_FAILED;
     }
     else
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                "bt_gatt_foreach_primary_services success for address [%s]", remoteAddress);
+                  "bt_gatt_foreach_primary_services success for address [%s]", remoteAddress);
     }
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
@@ -1181,29 +1168,25 @@ CAResult_t CABleDiscoverCharacteristics(bt_gatt_attribute_h service, const char
 
     OIC_LOG_V(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
 
-    VERIFY_NON_NULL(service, NULL, "service is NULL");
+    VERIFY_NON_NULL_RET(service, NULL, "service is NULL", CA_STATUS_FAILED);
 
-    VERIFY_NON_NULL(remoteAddress, NULL, "remoteAddress is NULL");
+    VERIFY_NON_NULL_RET(remoteAddress, NULL, "remoteAddress is NULL", CA_STATUS_FAILED);
 
     int32_t len = strlen(remoteAddress);
 
-    char *addr = (char *) OICMalloc(sizeof(char) * len + 1);
-    if (NULL == addr)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG , "Malloc  failed! ");
-        return CA_STATUS_FAILED;
-    }
-    memset(addr, 0x0, len + 1);
+    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);
 
     int32_t ret = bt_gatt_discover_characteristics(service, CABleGattCharacteristicsDiscoveredCb,
-            (void *) addr); // addr will be freed in callback.
-
+                  (void *)addr); // addr will be freed in callback.
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                "bt_gatt_discover_characteristics failed with error [%d]", ret);
+                  "bt_gatt_discover_characteristics failed with error [%d]", ret);
         OICFree(addr);
         return CA_STATUS_FAILED;
     }
@@ -1216,16 +1199,17 @@ CAResult_t CABleDiscoverCharacteristics(bt_gatt_attribute_h service, const char
 
 CAResult_t CAStartBLEGattClient()
 {
+    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+
     CAResult_t retVal = CAInitGattClientMutexVaraibles();
 
-    if (retVal != CA_STATUS_OK)
+    if (CA_STATUS_OK != retVal)
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAInitGattClientMutexVaraibles failed!");
         CATerminateGattClientMutexVariables();
         return CA_STATUS_FAILED;
     }
 
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
     u_mutex_unlock(gBleClientThreadPoolMutex);
     if (NULL == gBleClientThreadPool)
     {
@@ -1234,8 +1218,8 @@ CAResult_t CAStartBLEGattClient()
         return CA_STATUS_FAILED;
     }
 
-    CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool,
-            (void *) CAStartBleGattClientThread, (void *) NULL);
+    CAResult_t ret = u_thread_pool_add_task(gBleClientThreadPool, (void *) CAStartBleGattClientThread,
+                                            (void *) NULL);
     if (CA_STATUS_OK != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "u_thread_pool_add_task failed with ret [%d]", ret);
@@ -1250,7 +1234,7 @@ void *CAStartBleGattClientThread(void *data)
 {
     u_mutex_lock(gBleClientStateMutex);
 
-    if (CA_TRUE == gIsBleGattClientStarted)
+    if (CA_TRUE  == gIsBleGattClientStarted)
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "Gatt Client is already running");
         u_mutex_unlock(gBleClientStateMutex);
@@ -1258,14 +1242,12 @@ void *CAStartBleGattClientThread(void *data)
         return NULL;
     }
 
-    bt_adapter_le_scan_params_s scan_param =
-    { 0, };
+    bt_adapter_le_scan_params_s scan_param = { 0, };
     scan_param.type = BT_ADAPTER_LE_PASSIVE_SCAN;
     scan_param.interval = 1560;
     scan_param.window = 160;
 
-    int32_t ret = bt_adapter_le_set_scan_parameter(&scan_param);
-
+    int32_t  ret = bt_adapter_le_set_scan_parameter(&scan_param);
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "bt_adapter_le_set_scan_parameter Failed");
@@ -1275,7 +1257,6 @@ void *CAStartBleGattClientThread(void *data)
     }
 
     ret = bt_gatt_set_connection_state_changed_cb(CABleGattConnectionStateChangedCb, NULL);
-
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG,
@@ -1286,8 +1267,7 @@ void *CAStartBleGattClientThread(void *data)
     }
 
     ret = bt_adapter_le_set_device_discovery_state_changed_cb(
-            CABtAdapterLeDeviceDiscoveryStateChangedCb, NULL);
-
+              CABtAdapterLeDeviceDiscoveryStateChangedCb, NULL);
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG,
@@ -1300,11 +1280,10 @@ void *CAStartBleGattClientThread(void *data)
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Setting characteristic_changed cb \n");
 
     ret = bt_gatt_set_characteristic_changed_cb(CABleGattCharacteristicChangedCb, NULL);
-
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "bt_gatt_set_characteristic_changed_cb Failed as [%s ]",
-                CABTGetErrorMsg(ret));
+                  CABTGetErrorMsg(ret));
         u_mutex_unlock(gBleClientStateMutex);
         CATerminateBLEGattClient();
         return NULL;
@@ -1313,19 +1292,16 @@ void *CAStartBleGattClientThread(void *data)
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Setting bt_device_set_bond_created_cb \n");
 
     ret = bt_device_set_bond_created_cb(CABtGattBondCreatedCb, NULL);
-
     if (BT_ERROR_NONE != ret)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, " bt_device_set_bond_created_cb Failed as [%s ]",
-                CABTGetErrorMsg(ret));
-        u_mutex_unlock(gBleClientStateMutex);
+                  CABTGetErrorMsg(ret));
         return NULL;
     }
 
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "Starting LE device discovery");
 
     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");
@@ -1344,7 +1320,7 @@ void *CAStartBleGattClientThread(void *data)
     u_mutex_unlock(gBleClientStateMutex);
 
     CAResult_t retVal = CAAdapterInitializeMessageQueue(&gCABleClientSenderQueue);
-    if (CA_STATUS_OK != retVal)
+    if (CA_STATUS_OK != retVal )
     {
         OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "CAAdapterInitializeMessageQueue failed!");
         CATerminateBLEGattClient();
@@ -1375,7 +1351,7 @@ void *CAStartBleGattClientThread(void *data)
 
 void CAStopBLEGattClient()
 {
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
 
     u_mutex_lock(gBleClientStateMutex);
 
@@ -1390,23 +1366,23 @@ void CAStopBLEGattClient()
 
     CATerminateBLEGattClient();
 
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
 }
 
 void CATerminateBLEGattClient()
 {
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
 
     u_mutex_lock(gBleClientStateMutex);
 
     // Required for waking up the thread which is running in gmain loop
 
-    GMainContext *context_event_loop = g_main_loop_get_context(g_event_loop);
+    GMainContext  *context_event_loop = g_main_loop_get_context(g_event_loop);
 
     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_event_loop context %x", context_event_loop);
 
         g_main_context_wakeup(context_event_loop);
 
@@ -1435,12 +1411,10 @@ void CATerminateBLEGattClient()
 
     bt_device_unset_bond_created_cb();
     bt_gatt_unset_characteristic_changed_cb();
-    u_mutex_lock(gBleServiceListMutex);
 
+    u_mutex_lock(gBleServiceListMutex);
     CAFreeBLEServiceList(gBLEServiceList);
-
     gBLEServiceList = NULL;
-
     u_mutex_unlock(gBleServiceListMutex);
 
     gIsBleGattClientStarted = CA_FALSE;
@@ -1466,14 +1440,14 @@ void CATerminateBLEGattClient()
     }
     u_mutex_unlock(gBleClientReceiveDataMutex);
 
-    CATerminateGattClientMutexVaraibles();
+    CATerminateGattClientMutexVariables();
 
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
 }
 
 CAResult_t CAInitGattClientMutexVaraibles()
 {
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
     u_mutex_init();
     if (NULL == gBleClientStateMutex)
     {
@@ -1543,28 +1517,36 @@ CAResult_t CAInitGattClientMutexVaraibles()
             OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "u_cond_new failed");
             return CA_STATUS_FAILED;
         }
-    }OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+    }
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
     return CA_STATUS_OK;
 }
 
 void CATerminateGattClientMutexVariables()
 {
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
     u_mutex_free(gBleClientReceiveDataMutex);
     gBleClientReceiveDataMutex = NULL;
+
     u_mutex_free(gBleClientStateMutex);
     gBleClientStateMutex = NULL;
+
     u_mutex_free(gBleServiceListMutex);
     gBleServiceListMutex = NULL;
+
     u_mutex_free(gBleReqRespClientCbMutex);
     gBleReqRespClientCbMutex = NULL;
+
     u_mutex_free(gBleClientSendDataMutex);
     gBleClientSendDataMutex = NULL;
+
     u_mutex_free(gBleClientThreadPoolMutex);
     gBleClientThreadPoolMutex = NULL;
+
     u_mutex_free(gBleClientSendCondWait);
     gBleClientSendCondWait = NULL;
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
+
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "OUT");
 }
 
 void CASetBleClientThreadPoolHandle(u_thread_pool_t handle)
@@ -1576,7 +1558,7 @@ void CASetBleClientThreadPoolHandle(u_thread_pool_t handle)
     OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "OUT");
 }
 
-CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const char *data,
+CAResult_t  CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const char  *data,
         int32_t dataLen, TRANSFER_TYPE type, int32_t position)
 {
 
@@ -1591,60 +1573,49 @@ CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const
     }
 
     BLEServiceInfo *bleServiceInfo = NULL;
-    if (UNICAST == type)
+
+    u_mutex_lock(gBleServiceListMutex);
+    CAResult_t ret =  CA_STATUS_FAILED;
+    if ( UNICAST == type)
     {
         VERIFY_NON_NULL(remoteAddress, NULL, "remoteAddress is NULL");
-        u_mutex_lock(gBleServiceListMutex);
-        CAResult_t ret = CAGetBLEServiceInfo(gBLEServiceList, remoteAddress, &bleServiceInfo);
 
-        if (CA_STATUS_OK != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "CAGetBLEServiceInfo is failed!");
-            u_mutex_unlock(gBleServiceListMutex);
-            return CA_STATUS_FAILED;
-        }
-        u_mutex_unlock(gBleServiceListMutex);
+        ret = CAGetBLEServiceInfo(gBLEServiceList, remoteAddress, &bleServiceInfo);
     }
-    else if (MULTICAST == type)
+    else if ( MULTICAST == type)
     {
-        u_mutex_lock(gBleServiceListMutex);
-        CAResult_t ret = CAGetBLEServiceInfoByPosition(gBLEServiceList, position, &bleServiceInfo);
-
-        if (CA_STATUS_OK != ret)
-        {
-            OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG, "CAGetBLEServiceInfoByPosition is failed");
-            u_mutex_unlock(gBleServiceListMutex);
-            return CA_STATUS_FAILED;
-        }
+        ret = CAGetBLEServiceInfoByPosition(gBLEServiceList, position, &bleServiceInfo);
+    }
+    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 the data of length [%d] to [%s] ", dataLen,
-            bleServiceInfo->bdAddress);
+              bleServiceInfo->bdAddress);
 
-    char *value = (char *) OICMalloc(sizeof(char) * (dataLen + 1));
+    unsigned char *value = (unsigned char *) OICMalloc(sizeof(char) * (dataLen + 1));
+    VERIFY_NON_NULL_RET(value, TZ_BLE_CLIENT_TAG, "malloc failed", CA_STATUS_FAILED);
 
-    if (NULL == value)
-    {
-        OIC_LOG(ERROR, TZ_BLE_CLIENT_TAG, "malloc failed!");
-        return CA_STATUS_FAILED;
-    }
     memset(value, 0x0, (dataLen + 1));
-
     strncpy(value, data, dataLen);
 
-    int32_t ret = bt_gatt_set_characteristic_value_request(bleServiceInfo->write_char, value,
-            dataLen, CABleGattCharacteristicWriteCb);
+    int32_t result = bt_gatt_set_characteristic_value_request(bleServiceInfo->write_char, value,
+                     dataLen,
+                     CABleGattCharacteristicWriteCb);
 
     OICFree(value);
 
-    if (BT_ERROR_NONE != ret)
+    if (BT_ERROR_NONE != result)
     {
         OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                "bt_gatt_set_characteristic_value_request Failed with return val [%d]",
-                ret);
+                  "bt_gatt_set_characteristic_value_request Failed with return val [%d]",
+                  result);
         return CA_STATUS_FAILED;
     }
 
@@ -1653,10 +1624,11 @@ CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress, const
     return CA_STATUS_OK;
 }
 
-CAResult_t CAUpdateCharacteristicsToAllGattServers(const char *data, int32_t dataLen)
+
+CAResult_t  CAUpdateCharacteristicsToAllGattServers(const char  *data, int32_t dataLen)
 {
 
-    OIC_LOG(DEBUG, TZ_BLE_CLIENT_TAG, "IN");
+    OIC_LOG(DEBUG,  TZ_BLE_CLIENT_TAG, "IN");
 
     VERIFY_NON_NULL(data, NULL, "data is NULL");
 
@@ -1670,17 +1642,17 @@ CAResult_t CAUpdateCharacteristicsToAllGattServers(const char *data, int32_t dat
 
     int32_t NumberOfServersConnected = CAGetRegisteredServiceCount();
 
-    for (pos = 0; pos < NumberOfServersConnected; pos++)
+    for (pos = 0; pos < NumberOfServersConnected ; pos++)
     {
         /*remoteAddress will be NULL.
-         Since we have to send to all the address. pos will be used for getting remote address.
-         */
+            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);
 
         if (CA_STATUS_OK != ret)
         {
             OIC_LOG_V(ERROR, TZ_BLE_CLIENT_TAG,
-                    "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
+                      "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
         }
     }
 
@@ -1694,7 +1666,7 @@ void CASetBLEReqRespClientCallback(CANetworkPacketReceivedCallback callback)
 
     u_mutex_lock(gBleReqRespClientCbMutex);
 
-    gReqRespClientCallback = callback;
+    gNetworkPacketReceivedClientCallback = callback;
 
     u_mutex_unlock(gBleReqRespClientCbMutex);
 
index 2abc414..c491c3a 100644 (file)
@@ -265,7 +265,7 @@ CAResult_t CALEReadDataFromLEClient();
 * @retval  CA_STATUS_FAILED Operation failed
 *
 */
-CAResult_t CABleClientSenderQueueEnqueueMessage(CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABleClientSenderQueueEnqueueMessage(const CARemoteEndpoint_t *remoteEndpoint,
         void *data, uint32_t dataLen);
 
 /**
@@ -277,7 +277,7 @@ CAResult_t CABleClientSenderQueueEnqueueMessage(CARemoteEndpoint_t *remoteEndpoi
 * @return  void
 *
 */
-void CABleGattCharacteristicWriteCb(bt_gatt_attribute_h handle);
+void CABleGattCharacteristicWriteCb(int result, void *user_data);
 
 /**
 * @fn  CABleClientSenderQueueProcessor
index 2342bff..8f37630 100644 (file)
@@ -36,7 +36,6 @@
 #define OIC_BLE_SERVICE_ID "000018f3-0000-1000-8000-00805f9b34fb"
 ///TODO: OIC_BLE_SERVICE_ID  will be generated by invoking API in future.
 
-static BLEServiceList *gBLEServiceList = NULL;
 
 static int32_t gNumberOfServiceConnected = 0;
 
index 7daf85e..39471b0 100644 (file)
@@ -71,6 +71,20 @@ typedef enum
 } CHAR_TYPE;
 
 /**
+ * @ENUM CHAR_INDEX
+ * @brief indexes for the characteristics defined..
+ *
+ *  This ENUM provides index values for the characteristics
+ *  which will be added to OIC service.
+ */
+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. */
+} CHAR_INDEX;
+
+/**
  * @ENUM TRANSFER_TYPE
  * @brief Provide info about different mode of data transfer
  *
@@ -263,4 +277,14 @@ void CAFreeBLEServiceInfo(BLEServiceInfo *bleServiceInfo);
 */
 CAResult_t CAVerifyOICService(bt_gatt_attribute_h serviceHandle);
 
+/**
+* @fn  CABTGetErrorMsg
+* @brief  Used to get the Error message.
+*
+* @param[in] err - Error code(bt_error_e)
+*
+* @return  Error string corresponding to the BT error code.
+*
+*/
+const char *CABTGetErrorMsg(bt_error_e err);
 #endif //#ifndef _BLE_CLIENT_UTIL
index c0ce878..da9cd2a 100644 (file)
 
 ///TODO:: Currently keeping as single service. Later service path will be added in list for supporting multiple services.
 
+/**
+ * @var gGattSvcPath
+ * @brief attribute handler for OIC server attribute.
+ */
 static char *gGattSvcPath = NULL;
 
+/**
+ * @var gGattReadCharPath
+ * @brief attribute handler for readCharacteristic of OIC server
+ */
 static char *gGattReadCharPath = NULL;
 
+/**
+ * @var gGattWriteCharPath
+ * @brief attribute handler for writeCharacteristic of OIC server
+ */
 static char *gGattWriteCharPath = NULL;
 
+/**
+ * @var hAdvertiser
+ * @brief handler for OIC advertiser.
+ */
 static bt_advertiser_h hAdvertiser = NULL;
 
-static CANetworkPacketReceivedCallback gReqRespCallback = NULL;
+/**
+ * @var    gNetworkPacketReceivedServerCallback
+ * @brief  Maintains the callback to be notified on receival of network packets from other
+ *           BLE devices
+ */
+static CANetworkPacketReceivedCallback gNetworkPacketReceivedServerCallback = NULL;
 
+/**
+ * @var gCABleServerSenderQueue
+ * @brief Queue to process the outgoing packets from GATTServer.
+ */
 static CAAdapterMessageQueue_t *gCABleServerSenderQueue = NULL;
 
+/**
+ * @var gCABleServerReceiverQueue
+ * @brief Queue to process the incoming packets to GATTServer
+ */
 static CAAdapterMessageQueue_t *gCABleServerReceiverQueue = NULL;
 
+/**
+ * @var gIsBleGattServerStarted
+ * @brief Boolean variable to keep the state of the GATTServer
+ */
 static CABool_t gIsBleGattServerStarted = CA_FALSE;
 
 /**
- * @var gServiceStateMutex
- * @brief Mutex to synchronize the process of starting Gatt Server.
+ * @var gBleServerStateMutex
+ * @brief Mutex to synchronize the calls to be done to the platform from GATTServer
+ *           interfaces from different threads.
  */
 static u_mutex gBleServerStateMutex = NULL;
 
+/**
+ * @var gBleCharacteristicMutex
+ * @brief Mutex to synchronize writing operations on the characteristics.
+ */
 static  u_mutex gBleCharacteristicMutex = NULL;
 
+/**
+ * @var gBleServiceMutex
+ * @brief  Mutex to synchronize to create the OIC service..
+ */
 static  u_mutex gBleServiceMutex = NULL;
 
+/**
+ * @var gBleReqRespCbMutex
+ * @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;
 
+/**
+ * @var gBleServerSendDataMutex
+ * @brief Mutex to synchronize the queing of the data from SenderQueue.
+ */
 static u_mutex gBleServerSendDataMutex = NULL;
 
+/**
+ * @var gBleServerThreadPoolMutex
+ * @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 gBleServerReceiveDataMutex
+ * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
+ */
 static u_mutex gBleServerReceiveDataMutex = NULL;
 
+/**
+ * @var g_event_loop
+ * @brief gmainLoop to manage the threads to receive the callback from the platfrom.
+ */
 static GMainLoop *g_event_loop = NULL;
 
+/**
+ * @var gBleServerThreadPool
+ * @brief reference to threadpool
+ */
 static u_thread_pool_t gBleServerThreadPool = NULL;
 
+/**
+ * @var gServerUp
+ * @brief Boolean variable to maintain the GATT Server state.
+ */
 static CABool_t gServerUp = CA_FALSE;
 
 
@@ -564,31 +639,9 @@ void CASetBleServerThreadPoolHandle(u_thread_pool_t handle)
 
 CAResult_t CALEReadDataFromLEServer()
 {
-#if 0
-    OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN ");
-
-    CAAdapterMessage_t *receiverData = NULL;
-
-    CAResult_t result = CAAdapterDequeueMessage(gCABleServerReceiverQueue, &receiverData);
-
-    if (CA_STATUS_OK != result)
-    {
-        u_mutex_lock(gBleReqRespCbMutex);
-        if (NULL == gReqRespCallback)
-        {
-            OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gReqRespCallback is NULL!");
-            u_mutex_unlock(gBleReqRespCbMutex);
-            return;
-        }
-
-        gReqRespCallback(receiverData->remoteEndpoint, receiverData->data, receiverData->dataLen);
-
-        u_mutex_unlock(gBleReqRespCbMutex);
-
-        CAAdapterFreeMessage(receiverData);
-    }
-#endif
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT ");
+
+    return CA_STATUS_OK;
 }
 
 CAResult_t CAAddNewBleServiceInGattServer(const char *serviceUUID)
@@ -714,21 +767,22 @@ void CABleGattRemoteCharacteristicWriteCb(char *charPath,
     strncpy(data, charValue, charValueLen);
 
     u_mutex_lock(gBleReqRespCbMutex);
-    if (NULL == gReqRespCallback)
+    if (NULL == gNetworkPacketReceivedServerCallback)
     {
-        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gReqRespCallback is NULL!");
+        OIC_LOG(ERROR, TZ_BLE_SERVER_TAG, "gNetworkPacketReceivedServerCallback is NULL!");
         OICFree(charValue);
         OICFree(remoteEndPoint);
+        OICFree(data);
         u_mutex_unlock(gBleReqRespCbMutex);
         return;
     }
 
-    gReqRespCallback(remoteEndPoint, data, charValueLen);
+    gNetworkPacketReceivedServerCallback(remoteEndPoint, data, charValueLen);
     u_mutex_unlock(gBleReqRespCbMutex);
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "OUT");
 }
 
-CAResult_t CABleServerSenderQueueEnqueueMessage(CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABleServerSenderQueueEnqueueMessage(const CARemoteEndpoint_t *remoteEndpoint,
         void *data, uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TZ_BLE_SERVER_TAG, "IN ");
@@ -890,7 +944,7 @@ void CASetBLEReqRespServerCallback(CANetworkPacketReceivedCallback callback)
 
     u_mutex_lock(gBleReqRespCbMutex);
 
-    gReqRespCallback = callback;
+    gNetworkPacketReceivedServerCallback = callback;
 
     u_mutex_unlock(gBleReqRespCbMutex);
 
index 0f632be..7a274a7 100644 (file)
@@ -291,7 +291,7 @@ CAResult_t CALEReadDataFromLEServer();
 * @retval  CA_STATUS_FAILED Operation failed
 *
 */
-CAResult_t CABleServerSenderQueueEnqueueMessage(CARemoteEndpoint_t *remoteEndpoint,
+CAResult_t CABleServerSenderQueueEnqueueMessage(const CARemoteEndpoint_t *remoteEndpoint,
         void *data, uint32_t dataLen);
 
 /**
index 4e8c2cc..127361d 100644 (file)
@@ -118,11 +118,11 @@ CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t* size)
     return CAGetNetworkInformationInternal(info, size);
 }
 
-CAResult_t CAFindResource(const CAURI_t resourceUri)
+CAResult_t CAFindResource(const CAURI_t resourceUri, const CAToken_t token)
 {
     OIC_LOG_V(DEBUG, TAG, "CAFindResource");
 
-    return CADetachMessageResourceUri(resourceUri, NULL, 0);
+    return CADetachMessageResourceUri(resourceUri, token, NULL, 0);
 
 }
 
@@ -149,12 +149,12 @@ CAResult_t CASendResponse(const CARemoteEndpoint_t* object, CAResponseInfo_t* re
 
 }
 
-CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAHeaderOption_t* options,
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAToken_t token, CAHeaderOption_t* options,
         uint8_t numOptions)
 {
     OIC_LOG_V(DEBUG, TAG, "CAAdvertiseResource");
 
-    return CADetachMessageResourceUri(resourceUri, options, numOptions);
+    return CADetachMessageResourceUri(resourceUri, token, options, numOptions);
 
 }
 
diff --git a/resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c b/resource/csdk/connectivity/src/caconnectivitymanager_singlethread.c
new file mode 100644 (file)
index 0000000..ad37f36
--- /dev/null
@@ -0,0 +1,257 @@
+/******************************************************************
+ *
+ * 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 <stdint.h>
+
+#include "cainterface.h"
+#include "caremotehandler.h"
+#include "caprotocolmessage.h"
+#include "canetworkconfigurator.h"
+#include "logger.h"
+
+#include "cainterfacecontroller_singlethread.h"
+#include "camessagehandler_singlethread.h"
+
+#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;
+}
+
+void CATerminate()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CATerminateMessageHandler();
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAStartListeningServer()
+{
+    return CAStartListeningServerAdapters();
+}
+
+CAResult_t CAStartDiscoveryServer()
+{
+    return CAStartDiscoveryServerAdapters();
+}
+
+CAResult_t CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CASetRequestResponseCallbacks(ReqHandler, RespHandler);
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+    return CA_STATUS_OK;
+}
+
+CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, CARemoteEndpoint_t **remoteEndpoint)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    CARemoteEndpoint_t *remote = CACreateRemoteEndpointUriInternal(uri);
+
+    *remoteEndpoint = remote;
+
+    if (remote == NULL)
+        return CA_STATUS_FAILED;
+
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CADestroyRemoteEndpoint(CARemoteEndpoint_t *rep)
+{
+    CADestroyRemoteEndpointInternal(rep);
+}
+
+CAResult_t CAGenerateToken(CAToken_t *token)
+{
+    return CAGenerateTokenInternal(token);
+}
+
+void CADestroyToken(CAToken_t token)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    CADestroyTokenInternal(token);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAGetNetworkInformation(CALocalConnectivity_t **info, uint32_t *size)
+{
+    return CAGetNetworkInformationInternal(info, size);
+}
+
+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;
+}
+
+CAResult_t CASendRequest(const CARemoteEndpoint_t *object, CARequestInfo_t *requestInfo)
+{
+    return CADetachRequestMessage(object, requestInfo);
+}
+
+CAResult_t CASendNotification(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo)
+{
+    return CADetachResponseMessage(object, responseInfo);
+}
+
+CAResult_t CASendResponse(const CARemoteEndpoint_t *object, CAResponseInfo_t *responseInfo)
+{
+    return CADetachResponseMessage(object, responseInfo);
+}
+
+CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAToken_t token, CAHeaderOption_t* options,
+        uint8_t numOptions)
+{
+    return CADetachMessageResourceUri(resourceUri, token, options, numOptions);
+}
+
+CAResult_t CASelectNetwork(const uint32_t interestedNetwork)
+{
+    OIC_LOG_V(DEBUG, TAG, "Selected n/W=%d", interestedNetwork);
+
+    if (!(interestedNetwork & 0xf))
+    {
+        return CA_NOT_SUPPORTED;
+    }
+    CAResult_t res;
+
+    if (interestedNetwork & CA_ETHERNET)
+    {
+        res = CAAddNetworkType(CA_ETHERNET);
+        if (res != CA_STATUS_OK)
+        {
+            return res;
+        }
+    }
+
+    if (interestedNetwork & CA_WIFI)
+    {
+        res = CAAddNetworkType(CA_WIFI);
+        if (res != CA_STATUS_OK)
+        {
+            return res;
+        }
+    }
+
+    if (interestedNetwork & CA_EDR)
+    {
+        res = CAAddNetworkType(CA_EDR);
+        if (res != CA_STATUS_OK)
+        {
+            return res;
+        }
+    }
+
+    if (interestedNetwork & CA_LE)
+    {
+        res = CAAddNetworkType(CA_LE);
+        if (res != CA_STATUS_OK)
+        {
+            return res;
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork)
+{
+    OIC_LOG_V(DEBUG, TAG, "unselected n/w=%d", nonInterestedNetwork);
+
+    if (!(nonInterestedNetwork & 0xf))
+    {
+        return CA_NOT_SUPPORTED;
+    }
+
+    CAResult_t res;
+
+    if (nonInterestedNetwork & CA_ETHERNET)
+    {
+        res = CARemoveNetworkType(CA_ETHERNET);
+        if (res != CA_STATUS_OK)
+        {
+            return res;
+        }
+    }
+
+    if (nonInterestedNetwork & CA_WIFI)
+    {
+        res = CARemoveNetworkType(CA_WIFI);
+        if (res != CA_STATUS_OK)
+        {
+            return res;
+        }
+    }
+
+    if (nonInterestedNetwork & CA_EDR)
+    {
+        res = CARemoveNetworkType(CA_EDR);
+        if (res != CA_STATUS_OK)
+        {
+            return res;
+        }
+    }
+
+    if (nonInterestedNetwork & CA_LE)
+    {
+        res = CARemoveNetworkType(CA_LE);
+        if (res != CA_STATUS_OK)
+        {
+            return res;
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAHandleRequestResponse()
+{
+    //OIC_LOG(DEBUG, TAG, "IN");
+    CAHandleRequestResponseCallbacks();
+    //OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
index 867bca1..33124b8 100644 (file)
@@ -82,7 +82,7 @@ static void CARegisterCallback(CAConnectivityHandler_t handler, CAConnectivityTy
     OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", cType);
 }
 
-static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
+static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TAG, "receivedPacketCallback in interface controller");
 
@@ -93,7 +93,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, u
     }
 }
 
-static void CANetworkChangedCallback(CALocalConnectivity_tinfo, CANetworkStatus_t status)
+static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
 {
     OIC_LOG(DEBUG, TAG, "Network Changed callback");
 
@@ -112,7 +112,8 @@ void CAInitializeAdapters(u_thread_pool_t handle)
 
     // Initialize adapters and register callback.
 #ifdef ETHERNET_ADAPTER
-    CAInitializeEthernet(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback, handle);
+    CAInitializeEthernet(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback,
+                         handle);
 #endif /* ETHERNET_ADAPTER */
 
 #ifdef WIFI_ADAPTER
@@ -183,20 +184,20 @@ void CAStopAdapter(CAConnectivityType_t cType)
     }
 }
 
-CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_tsize)
+CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t *size)
 {
     CAResult_t res = CA_STATUS_FAILED;
     int8_t index = 0;
     int8_t i = 0;
 
-    CALocalConnectivity_tresInfo = NULL;
+    CALocalConnectivity_t *resInfo = NULL;
     uint32_t resSize = 0;
 
-    CALocalConnectivity_ttempInfo[CA_CONNECTIVITY_TYPE_NUM];
+    CALocalConnectivity_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM];
     uint32_t tempSize[CA_CONNECTIVITY_TYPE_NUM];
 
-    memset(tempInfo, 0, sizeof(CALocalConnectivity_t*) * CA_CONNECTIVITY_TYPE_NUM);
-    memset(tempSize, 0, sizeof(int8_t) * CA_CONNECTIVITY_TYPE_NUM);
+    memset(tempInfo, 0, sizeof(CALocalConnectivity_t *) * CA_CONNECTIVITY_TYPE_NUM);
+    memset(tempSize, 0, sizeof(uint32_t) * CA_CONNECTIVITY_TYPE_NUM);
 
     // #1. get information each adapter
     for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
@@ -227,12 +228,13 @@ CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t* size)
 
     if (resSize <= 0)
     {
+        res = CA_STATUS_FAILED;
         return res;
     }
 
     // #3. add data into result
     // memory allocation
-    resInfo = (CALocalConnectivity_t*) OICMalloc(sizeof(CALocalConnectivity_t) * resSize);
+    resInfo = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t) * resSize);
     CA_MEMORY_ALLOC_CHECK(resInfo);
     memset(resInfo, 0, sizeof(CALocalConnectivity_t) * resSize);
 
@@ -262,12 +264,12 @@ CAResult_t CAGetNetworkInfo(CALocalConnectivity_t **info, uint32_t* size)
     return res;
 
     // memory error label.
-    memory_error_exit:
+memory_error_exit:
 
     return CA_MEMORY_ALLOC_FAILED;
 }
 
-CAResult_t CASendUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t length)
+CAResult_t CASendUnicastData(CARemoteEndpoint_t* endpoint, void* data, uint32_t length)
 {
     OIC_LOG(DEBUG, TAG, "Send unicast data to enabled interface..");
 
@@ -294,11 +296,14 @@ CAResult_t CASendUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uin
     {
         res = gAdapterHandler[index].sendData(endpoint, data, length);
     }
+    //For Unicast , data will be deleted by adapters
+
+    CADestroyRemoteEndpointInternal(endpoint);
 
     return res;
 }
 
-CAResult_t CASendMulticastData(voiddata, uint32_t length)
+CAResult_t CASendMulticastData(void *data, uint32_t length)
 {
     OIC_LOG(DEBUG, TAG, "Send multicast data to enabled interface..");
 
@@ -315,7 +320,7 @@ CAResult_t CASendMulticastData(void* data, uint32_t length)
 
     for (i = 0; i < u_arraylist_length(list); i++)
     {
-        type = *(int*) u_arraylist_get(list, i);
+        type = *(uint8_t*) u_arraylist_get(list, i);
 
         index = CAGetAdapterIndex(type);
 
@@ -327,10 +332,11 @@ CAResult_t CASendMulticastData(void* data, uint32_t length)
 
         if (gAdapterHandler[index].sendDataToAll != NULL)
         {
-            res = gAdapterHandler[index].sendDataToAll(data, length);
+            void* payload = (void*) OICMalloc(length);
+            memcpy(payload, data, length);
+            res = gAdapterHandler[index].sendDataToAll(payload, length);
         }
     }
-
     return res;
 }
 
@@ -350,7 +356,7 @@ CAResult_t CAStartListeningServerAdapters()
 
     for (i = 0; i < u_arraylist_length(list); i++)
     {
-        type = *(int*) u_arraylist_get(list, i);
+        type = *(uint8_t*) u_arraylist_get(list, i);
 
         index = CAGetAdapterIndex(type);
 
@@ -385,7 +391,7 @@ CAResult_t CAStartDiscoveryServerAdapters()
 
     for (i = 0; i < u_arraylist_length(list); i++)
     {
-        type = *(int*) u_arraylist_get(list, i);
+        type = *(uint8_t*) u_arraylist_get(list, i);
 
         index = CAGetAdapterIndex(type);
 
diff --git a/resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c b/resource/csdk/connectivity/src/cainterfacecontroller_singlethread.c
new file mode 100644 (file)
index 0000000..dd559de
--- /dev/null
@@ -0,0 +1,467 @@
+/******************************************************************
+ *
+ * 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 "cainterfacecontroller_singlethread.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+
+#include "cawifiadapter_singlethread.h"
+#include "caethernetadapter_singlethread.h"
+#include "caedradapter_singlethread.h"
+#include "caleadapter_singlethread.h"
+
+#include "canetworkconfigurator.h"
+#include "oic_malloc.h"
+#include "logger.h"
+
+#define TAG "CAIFCNT_ST"
+
+#define MEMORY_ALLOCK_CHECK(arg) { if (arg == NULL) {OIC_LOG_V(DEBUG, TAG, "Out of memory"); goto memory_error_exit;} }
+
+#define CA_CONNECTIVITY_TYPE_NUM   4
+
+static CAConnectivityHandler_t gAdapterHandler[CA_CONNECTIVITY_TYPE_NUM];
+
+static CANetworkPacketReceivedCallback gNetworkPacketReceivedCallback = NULL;
+
+static CANetworkChangeCallback gNetworkChangeCallback = NULL;
+
+static int8_t CAGetAdapterIndex(CAConnectivityType_t cType)
+{
+    //OIC_LOG(DEBUG, TAG, "IN");
+    switch (cType)
+    {
+        case CA_ETHERNET:
+            return 0;
+        case CA_WIFI:
+            return 1;
+        case CA_EDR:
+            return 2;
+        case CA_LE:
+            return 3;
+    }
+    //OIC_LOG(DEBUG, TAG, "OUT");
+    return -1;
+}
+
+static void CARegisterCallback(CAConnectivityHandler_t handler, CAConnectivityType_t cType)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    int8_t index = -1;
+
+    index = CAGetAdapterIndex(cType);
+
+    if (index == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        return;
+    }
+
+    memcpy(&gAdapterHandler[index], &handler, sizeof(CAConnectivityHandler_t));
+
+    OIC_LOG_V(DEBUG, TAG, "%d type adapter", cType);
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    // Call the callback.
+    if (gNetworkPacketReceivedCallback != NULL)
+    {
+        gNetworkPacketReceivedCallback(endpoint, data, dataLen);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    // Call the callback.
+    if (gNetworkChangeCallback != NULL)
+    {
+        gNetworkChangeCallback(info, status);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAInitializeAdapters()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    memset(gAdapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM);
+
+
+    // Initialize adapters and register callback.
+#ifdef ETHERNET_ADAPTER
+    CAInitializeEthernet(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+#endif /* ETHERNET_ADAPTER */
+
+#ifdef WIFI_ADAPTER
+    CAInitializeWifi(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+#endif /* WIFI_ADAPTER */
+
+#ifdef EDR_ADAPTER
+    CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+#endif /* EDR_ADAPTER */
+
+#ifdef LE_ADAPTER
+    CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback);
+#endif /* LE_ADAPTER */
+    OIC_LOG(DEBUG, TAG, "OUT");
+
+}
+
+void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    gNetworkPacketReceivedCallback = callback;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CASetNetworkChangeCallback(CANetworkChangeCallback callback)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    gNetworkChangeCallback = callback;
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAStartAdapter(CAConnectivityType_t cType)
+{
+    OIC_LOG_V(DEBUG, TAG, "cType[%d]", cType);
+
+    int8_t index = -1;
+
+    index = CAGetAdapterIndex(cType);
+
+    if (index == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        return;
+    }
+
+    if (gAdapterHandler[index].startAdapter != NULL)
+    {
+        gAdapterHandler[index].startAdapter();
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+void CAStopAdapter(CAConnectivityType_t cType)
+{
+    OIC_LOG_V(DEBUG, TAG, "cType[%d]", cType);
+
+    int8_t index = -1;
+
+    index = CAGetAdapterIndex(cType);
+
+    if (index == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        return;
+    }
+
+    if (gAdapterHandler[index].stopAdapter != NULL)
+    {
+        gAdapterHandler[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;
+
+    CALocalConnectivity_t *resInfo = NULL;
+    uint32_t resSize = 0;
+
+    CALocalConnectivity_t *tempInfo[CA_CONNECTIVITY_TYPE_NUM];
+    uint32_t tempSize[CA_CONNECTIVITY_TYPE_NUM];
+
+    memset(tempInfo, 0, sizeof(CALocalConnectivity_t *) * CA_CONNECTIVITY_TYPE_NUM);
+    memset(tempSize, 0, sizeof(int8_t) * CA_CONNECTIVITY_TYPE_NUM);
+
+    // #1. get information each adapter
+    for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+        if (gAdapterHandler[index].GetnetInfo != NULL)
+        {
+            res = gAdapterHandler[index].GetnetInfo(&tempInfo[index], &tempSize[index]);
+
+            OIC_LOG_V (DEBUG, TAG, "%d adapter network info size is %d", index, tempSize[index]);
+        }
+    }
+
+    resSize = 0;
+    for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+        // check information
+        if (tempInfo[index] == NULL || tempSize[index] <= 0)
+        {
+            continue;
+        }
+
+        // #2. total size
+        resSize += tempSize[index];
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "network info total size is %d!", resSize);
+
+    if (resSize <= 0)
+    {
+        return res;
+    }
+
+    // #3. add data into result
+    // memory allocation
+    resInfo = (CALocalConnectivity_t *) OICMalloc(sizeof(CALocalConnectivity_t) * resSize);
+    MEMORY_ALLOCK_CHECK(resInfo);
+    memset(resInfo, 0, sizeof(CALocalConnectivity_t) * resSize);
+
+    i = 0;
+    for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+        // check information
+        if (tempInfo[index] == NULL || tempSize[index] <= 0)
+        {
+            continue;
+        }
+
+        memcpy(resInfo + i, tempInfo[index], sizeof(CALocalConnectivity_t) * tempSize[index]);
+
+        i += tempSize[index];
+
+        // free adapter data
+        OICFree(tempInfo[index]);
+    }
+
+    // #5. save data
+    *info = resInfo;
+    *size = resSize;
+
+    OIC_LOG_V(DEBUG, TAG, "OUT");
+
+    return res;
+
+    // memory error label.
+memory_error_exit:
+
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+CAResult_t CASendUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t length)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    int8_t index = -1;
+    CAResult_t res = CA_STATUS_FAILED;
+
+    if (endpoint == NULL)
+    {
+        OIC_LOG_V(DEBUG, TAG, "RemoteEndpoint is NULL");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    CAConnectivityType_t type = endpoint->connectivityType;
+
+    index = CAGetAdapterIndex(type);
+
+    if (index == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+        return CA_STATUS_INVALID_PARAM;
+    }
+
+    if (gAdapterHandler[index].sendData != NULL)
+    {
+        res = gAdapterHandler[index].sendData(endpoint, data, length);
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return res;
+}
+
+CAResult_t CASendMulticastData(void *data, uint32_t length)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    uint8_t i, type;
+    int8_t index = -1;
+    CAResult_t res = CA_STATUS_FAILED;
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+
+    if (!list)
+    {
+        OIC_LOG(DEBUG, TAG, "No selected network");
+        return CA_STATUS_FAILED;
+    }
+
+    for (i = 0; i < u_arraylist_length(list); i++)
+    {
+        type = *(uint8_t *) u_arraylist_get(list, i);
+
+        index = CAGetAdapterIndex(type);
+
+        if (index == -1)
+        {
+            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+            continue;
+        }
+
+        if (gAdapterHandler[index].sendDataToAll != NULL)
+        {
+            res = gAdapterHandler[index].sendDataToAll(data, length);
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return res;
+}
+
+CAResult_t CAStartListeningServerAdapters()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    uint8_t i, type;
+    int8_t index = -1;
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+
+    if (!list)
+    {
+        OIC_LOG(DEBUG, TAG, "No selected network");
+        return CA_STATUS_FAILED;
+    }
+
+    for (i = 0; i < u_arraylist_length(list); i++)
+    {
+        type = *(uint8_t *) u_arraylist_get(list, i);
+
+        index = CAGetAdapterIndex(type);
+
+        if (index == -1)
+        {
+            OIC_LOG(DEBUG, TAG, "unknown connectivity type!");
+            continue;
+        }
+
+        if (gAdapterHandler[index].startListenServer != NULL)
+        {
+            gAdapterHandler[index].startListenServer();
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartDiscoveryServerAdapters()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    uint8_t i, type;
+    int8_t index = -1;
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+
+    if (!list)
+    {
+        OIC_LOG(DEBUG, TAG, "No selected network");
+        return CA_STATUS_FAILED;
+    }
+
+    for (i = 0; i < u_arraylist_length(list); i++)
+    {
+        type = *(uint8_t *) u_arraylist_get(list, i);
+
+        index = CAGetAdapterIndex(type);
+
+        if (index == -1)
+        {
+            OIC_LOG_V(DEBUG, TAG, "unknown connectivity type!");
+            continue;
+        }
+
+        if (gAdapterHandler[index].startDiscoverServer != NULL)
+        {
+            gAdapterHandler[index].startDiscoverServer();
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateAdapters()
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+
+    uint8_t index;
+
+    for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++)
+    {
+        if (gAdapterHandler[index].terminate != NULL)
+        {
+            gAdapterHandler[index].terminate();
+        }
+    }
+    OIC_LOG(DEBUG, TAG, "OUT");
+}
+
+CAResult_t CAReadData()
+{
+    //OIC_LOG(DEBUG, TAG, "IN");
+
+    uint8_t i, type;
+    int8_t index = -1;
+
+    u_arraylist_t *list = CAGetSelectedNetworkList();
+
+    if (!list)
+    {
+        OIC_LOG(DEBUG, TAG, "No selected network");
+        return CA_STATUS_FAILED;
+    }
+
+    for (i = 0; i < u_arraylist_length(list); i++)
+    {
+        type = *(uint8_t *) u_arraylist_get(list, i);
+
+        index = CAGetAdapterIndex(type);
+
+        if (-1 == index)
+        {
+            OIC_LOG_V(DEBUG, TAG, "unknown connectivity type!");
+            continue;
+        }
+
+        if (gAdapterHandler[index].readData != NULL)
+        {
+            gAdapterHandler[index].readData();
+        }
+    }
+
+    //OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
index f27d95f..c1481f9 100644 (file)
@@ -51,10 +51,10 @@ typedef enum
 typedef struct
 {
     CASendDataType_t type;
-    CARemoteEndpoint_tremoteEndpoint;
-    CARequestInfo_trequestInfo;
-    CAResponseInfo_tresponseInfo;
-    CAHeaderOption_toptions;
+    CARemoteEndpoint_t *remoteEndpoint;
+    CARequestInfo_t *requestInfo;
+    CAResponseInfo_t *responseInfo;
+    CAHeaderOption_t *options;
     uint8_t numOptions;
 } CAData_t;
 
@@ -69,16 +69,16 @@ static CAQueueingThread_t gReceiveThread;
 static CARequestCallback gRequestHandler = NULL;
 static CAResponseCallback gResponseHandler = NULL;
 
-static void CAReceiveThreadProcess(voidthreadData)
+static void CAReceiveThreadProcess(void *threadData)
 {
     // TODO
     // currently not support.
     // CAHandleRequestResponseCallbacks codes will move to this function.
 }
 
-static void CASendThreadProcess(voidthreadData)
+static void CASendThreadProcess(void *threadData)
 {
-    CAData_t* data = (CAData_t*) threadData;
+    CAData_t *data = (CAData_t *) threadData;
 
     if (data == NULL)
     {
@@ -98,21 +98,21 @@ static void CASendThreadProcess(void* threadData)
 
     if (type == SEND_TYPE_UNICAST)
     {
-        coap_pdu_tpdu = NULL;
+        coap_pdu_t *pdu = NULL;
 
         if (data->requestInfo != NULL)
         {
             OIC_LOG_V(DEBUG, TAG, "requestInfo is available..");
 
-            pdu = (coap_pdu_t*) CAGeneratePdu(data->remoteEndpoint->resourceUri,
-                    data->requestInfo->method, data->requestInfo->info);
+            pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri,
+                                               data->requestInfo->method, data->requestInfo->info);
         }
         else if (data->responseInfo != NULL)
         {
             OIC_LOG_V(DEBUG, TAG, "responseInfo is available..");
 
-            pdu = (coap_pdu_t*) CAGeneratePdu(data->remoteEndpoint->resourceUri,
-                    data->responseInfo->result, data->responseInfo->info);
+            pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri,
+                                               data->responseInfo->result, data->responseInfo->info);
         }
         else
         {
@@ -136,14 +136,15 @@ static void CASendThreadProcess(void* threadData)
     {
         OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available");
 
-        coap_pdu_tpdu = NULL;
+        coap_pdu_t *pdu = NULL;
         CAInfo_t info;
         memset(&info, 0, sizeof(CAInfo_t));
 
         info.options = data->options;
         info.numOptions = data->numOptions;
+        info.token = data->requestInfo->info.token;
 
-        pdu = (coap_pdu_t*) CAGeneratePdu(data->remoteEndpoint->resourceUri, CA_GET, info);
+        pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri, CA_GET, info);
 
         if (NULL != pdu)
         {
@@ -155,6 +156,8 @@ static void CASendThreadProcess(void* threadData)
 
             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);
 
             res = CASendMulticastData(pdu->hdr, pdu->length);
@@ -164,10 +167,10 @@ static void CASendThreadProcess(void* threadData)
     {
         OIC_LOG(DEBUG, TAG, "unknown type!");
     }
-
+    OIC_LOG_V(DEBUG, TAG, " Result :%d",res);
 }
 
-static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
+static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
 {
     OIC_LOG(DEBUG, TAG, "receivedPacketCallback in message handler!!");
 
@@ -177,9 +180,9 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, u
         return;
     }
 
-    coap_pdu_tpdu;
+    coap_pdu_t *pdu;
     uint32_t code = CA_NOT_FOUND;
-    pdu = (coap_pdu_t*) CAParsePDU((const char*) data, &code);
+    pdu = (coap_pdu_t *) CAParsePDU((const char *) data, &code);
     OICFree(data);
 
     char uri[CA_MAX_URI_LENGTH] =
@@ -187,12 +190,12 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, u
 
     if (code == CA_GET || code == CA_POST || code == CA_PUT || code == CA_DELETE)
     {
-        CARequestInfo_tReqInfo;
-        ReqInfo = (CARequestInfo_t*) OICMalloc(sizeof(CARequestInfo_t));
+        CARequestInfo_t *ReqInfo;
+        ReqInfo = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
         memset(ReqInfo, 0, sizeof(CARequestInfo_t));
         CAGetRequestInfoFromPdu(pdu, ReqInfo, uri);
 
-        if (NULL != ReqInfo->info.options && NULL != endpoint)
+        if (NULL != ReqInfo->info.options)
         {
             uint32_t i;
             for (i = 0; i < ReqInfo->info.numOptions; i++)
@@ -201,20 +204,23 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, u
 
                 OIC_LOG_V(DEBUG, TAG, "Request- list: %s", ReqInfo->info.options[i].optionData);
             }
+        }
 
+        if (NULL != ReqInfo->info.payload)
+        {
             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- code: %d", ReqInfo->method);
-
-            endpoint->resourceUri = (char*) OICMalloc(strlen(uri) + 1);
+        if (NULL != endpoint)
+        {
+            endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
             memset(endpoint->resourceUri, 0, strlen(uri) + 1);
             memcpy(endpoint->resourceUri, uri, strlen(uri));
             OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
         }
-
         // store the data at queue.
-        CAData_tcadata = NULL;
-        cadata = (CAData_t*) OICMalloc(sizeof(CAData_t));
+        CAData_t *cadata = NULL;
+        cadata = (CAData_t *) OICMalloc(sizeof(CAData_t));
         memset(cadata, 0, sizeof(CAData_t));
 
         cadata->type = SEND_TYPE_UNICAST;
@@ -225,12 +231,12 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, u
     }
     else
     {
-        CAResponseInfo_tResInfo;
-        ResInfo = (CAResponseInfo_t*) OICMalloc(sizeof(CAResponseInfo_t));
+        CAResponseInfo_t *ResInfo;
+        ResInfo = (CAResponseInfo_t *) OICMalloc(sizeof(CAResponseInfo_t));
         memset(ResInfo, 0, sizeof(CAResponseInfo_t));
         CAGetResponseInfoFromPdu(pdu, ResInfo, uri);
 
-        if (NULL != ResInfo->info.options && NULL != endpoint)
+        if (NULL != ResInfo->info.options)
         {
             uint32_t i;
             for (i = 0; i < ResInfo->info.numOptions; i++)
@@ -239,20 +245,23 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, u
 
                 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);
+        }
 
-            OIC_LOG_V(DEBUG, TAG, "Response- payload: %s", ResInfo->info.payload);
-
-            OIC_LOG_V(DEBUG, TAG, "Response- code: %d", ResInfo->result);
-
-            endpoint->resourceUri = (char*) OICMalloc(strlen(uri) + 1);
+        if (NULL != endpoint)
+        {
+            endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
             memset(endpoint->resourceUri, 0, strlen(uri) + 1);
             memcpy(endpoint->resourceUri, uri, strlen(uri));
             OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri);
         }
 
         // store the data at queue.
-        CAData_tcadata = NULL;
-        cadata = (CAData_t*) OICMalloc(sizeof(CAData_t));
+        CAData_t *cadata = NULL;
+        cadata = (CAData_t *) OICMalloc(sizeof(CAData_t));
         memset(cadata, 0, sizeof(CAData_t));
 
         cadata->type = SEND_TYPE_UNICAST;
@@ -264,7 +273,7 @@ static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, u
     }
 }
 
-static void CANetworkChangedCallback(CALocalConnectivity_tinfo, CANetworkStatus_t status)
+static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
 {
     OIC_LOG(DEBUG, TAG, "networkChangeCallback in message handler!!");
 }
@@ -279,7 +288,7 @@ void CAHandleRequestResponseCallbacks()
 
     u_mutex_lock(gReceiveThread.threadMutex);
 
-    u_queue_message_titem = u_queue_get_element(gReceiveThread.dataQueue);
+    u_queue_message_t *item = u_queue_get_element(gReceiveThread.dataQueue);
 
     u_mutex_unlock(gReceiveThread.threadMutex);
 
@@ -287,14 +296,14 @@ void CAHandleRequestResponseCallbacks()
         return;
 
     // get values
-    voidmsg = item->msg;
+    void *msg = item->msg;
 
     if (msg == NULL)
         return;
 
     // get endpoint
-    CAData_t* td = (CAData_t*) msg;
-    CARemoteEndpoint_trep = td->remoteEndpoint;
+    CAData_t *td = (CAData_t *) msg;
+    CARemoteEndpoint_t *rep = td->remoteEndpoint;
 
     if (rep == NULL)
         return;
@@ -306,17 +315,17 @@ void CAHandleRequestResponseCallbacks()
             gRequestHandler(rep, td->requestInfo);
         }
 
-        if(NULL != td->requestInfo->info.options)
+        if (NULL != td->requestInfo->info.options)
         {
             OICFree(td->requestInfo->info.options);
         }
 
-        if(NULL != td->requestInfo->info.payload)
+        if (NULL != td->requestInfo->info.payload)
         {
             OICFree(td->requestInfo->info.payload);
         }
 
-        if(NULL != td->requestInfo->info.token)
+        if (NULL != td->requestInfo->info.token)
         {
             OICFree(td->requestInfo->info.token);
         }
@@ -330,31 +339,31 @@ void CAHandleRequestResponseCallbacks()
             gResponseHandler(rep, td->responseInfo);
         }
 
-        if(NULL != td->responseInfo->info.options)
+        if (NULL != td->responseInfo->info.options)
         {
             OICFree(td->responseInfo->info.options);
         }
 
-        if(NULL != td->responseInfo->info.payload)
+        if (NULL != td->responseInfo->info.payload)
         {
             OICFree(td->responseInfo->info.payload);
         }
 
-        if(NULL != td->responseInfo->info.token)
+        if (NULL != td->responseInfo->info.token)
         {
             OICFree(td->responseInfo->info.token);
         }
         OICFree(td->responseInfo);
     }
 
-    if(NULL != rep->resourceUri)
+    if (NULL != rep->resourceUri)
     {
         OICFree(rep->resourceUri);
     }
     OICFree(rep);
 }
 
-CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequestInfo_t* request)
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
 {
     OIC_LOG_V(DEBUG, TAG, "CADetachRequestMessage");
 
@@ -363,18 +372,18 @@ CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequ
         return CA_STATUS_FAILED;
     }
 
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
+    CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
     MEMORY_ALLOCK_CHECK(data);
 
     // initialize
     memset(data, 0, sizeof(CAData_t));
 
     // clone remote endpoint
-    CARemoteEndpoint_tremoteEndpoint = CACloneRemoteEndpoint(object);
+    CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(object);
     MEMORY_ALLOCK_CHECK(remoteEndpoint);
 
     // clone request info
-    CARequestInfo_trequestInfo = CACloneRequestInfo(request);
+    CARequestInfo_t *requestInfo = CACloneRequestInfo(request);
     MEMORY_ALLOCK_CHECK(requestInfo);
 
     // save data
@@ -389,7 +398,7 @@ CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequ
     return CA_STATUS_OK;
 
     // memory error label.
-    memory_error_exit:
+memory_error_exit:
 
     CADestroyRemoteEndpointInternal(remoteEndpoint);
 
@@ -403,8 +412,8 @@ CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequ
     return CA_MEMORY_ALLOC_FAILED;
 }
 
-CAResult_t CADetachResponseMessage(const CARemoteEndpoint_tobject,
-        const CAResponseInfo_t* response)
+CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
+                                   const CAResponseInfo_t *response)
 {
     OIC_LOG_V(DEBUG, TAG, "CADetachResponseMessage");
 
@@ -413,18 +422,18 @@ CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t* object,
         return CA_STATUS_FAILED;
     }
 
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
+    CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
     MEMORY_ALLOCK_CHECK(data);
 
     // initialize
     memset(data, 0, sizeof(CAData_t));
 
     // clone remote endpoint
-    CARemoteEndpoint_tremoteEndpoint = CACloneRemoteEndpoint(object);
+    CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(object);
     MEMORY_ALLOCK_CHECK(remoteEndpoint);
 
     // clone response info
-    CAResponseInfo_tresponseInfo = CACloneResponseInfo(response);
+    CAResponseInfo_t *responseInfo = CACloneResponseInfo(response);
     MEMORY_ALLOCK_CHECK(responseInfo);
 
     // save data
@@ -439,7 +448,7 @@ CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t* object,
     return CA_STATUS_OK;
 
     // memory error label.
-    memory_error_exit:
+memory_error_exit:
 
     CADestroyRemoteEndpointInternal(remoteEndpoint);
 
@@ -453,15 +462,15 @@ CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t* object,
     return CA_MEMORY_ALLOC_FAILED;
 }
 
-CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAHeaderOption_t* options,
-        uint8_t numOptions)
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token,
+        const CAHeaderOption_t* options, uint8_t numOptions)
 {
     if (resourceUri == NULL)
     {
         return CA_STATUS_FAILED;
     }
 
-    CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t));
+    CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
     MEMORY_ALLOCK_CHECK(data);
 
     // initialize
@@ -469,13 +478,19 @@ CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAHeaderO
 
     CAAddress_t addr;
     memset(&addr, 0, sizeof(CAAddress_t));
-    CARemoteEndpoint_tremoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
-            CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE);
+    CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr,
+                                         CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE);
 
     // save data
     data->type = SEND_TYPE_MULTICAST;
     data->remoteEndpoint = remoteEndpoint;
-    data->requestInfo = NULL;
+    CARequestInfo_t* ReqInfo;
+    ReqInfo = (CARequestInfo_t*) OICMalloc(sizeof(CARequestInfo_t));
+    memset(ReqInfo, 0, sizeof(CARequestInfo_t));
+    ReqInfo->method = CA_GET;
+    ReqInfo->info.token = token;
+    data->requestInfo = ReqInfo;
+
     data->responseInfo = NULL;
     data->options = NULL;
     data->numOptions = 0;
@@ -483,8 +498,8 @@ CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAHeaderO
     if (options != NULL && numOptions > 0)
     {
         // copy data
-        CAHeaderOption_t* temp = (CAHeaderOption_t*) OICMalloc(
-                sizeof(CAHeaderOption_t) * numOptions);
+        CAHeaderOption_t *temp = (CAHeaderOption_t *) OICMalloc(
+                                     sizeof(CAHeaderOption_t) * numOptions);
 
         MEMORY_ALLOCK_CHECK(temp);
 
@@ -501,7 +516,7 @@ CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAHeaderO
     return CA_STATUS_OK;
 
     // memory error label.
-    memory_error_exit:
+memory_error_exit:
 
     CADestroyRemoteEndpointInternal(remoteEndpoint);
 
@@ -523,7 +538,7 @@ void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallb
 
 CAResult_t CAInitializeMessageHandler()
 {
-       OIC_LOG(DEBUG, TAG, "CAInitializeMessageHandler - Entry");
+    OIC_LOG(DEBUG, TAG, "CAInitializeMessageHandler - Entry");
     CASetPacketReceivedCallback(CAReceivedPacketCallback);
 
     CASetNetworkChangeCallback(CANetworkChangedCallback);
@@ -582,12 +597,11 @@ void CATerminateMessageHandler()
 
     // stop thread
     // delete thread data
-    CAQueueingThreadStop(&gReceiveThread);
     CAQueueingThreadDestroy(&gReceiveThread);
 
     // destroy thread pool
     u_thread_pool_free(gThreadPoolHandle);
 
-    OIC_LOG_V(DEBUG, TAG, "message handler terminate completed!");
+    OIC_LOG_V(DEBUG, TAG, "message handler termination is complete!");
 }
 
diff --git a/resource/csdk/connectivity/src/camessagehandler_singlethread.c b/resource/csdk/connectivity/src/camessagehandler_singlethread.c
new file mode 100644 (file)
index 0000000..a51d007
--- /dev/null
@@ -0,0 +1,477 @@
+/******************************************************************
+ *
+ * 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 "camessagehandler_singlethread.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdint.h>
+
+#include "cainterface.h"
+#include "caremotehandler.h"
+#include "cainterfacecontroller_singlethread.h"
+#include "caprotocolmessage.h"
+#include "logger.h"
+#include "config.h" /* for coap protocol */
+#include "coap.h"
+#include "oic_malloc.h"
+#include "caadapterutils.h"
+
+#define TAG1 "CAMH_ST"
+
+#define MEMORY_ALLOCK_CHECK(arg) { if (arg == NULL) {OIC_LOG_V(DEBUG, TAG1, "Out of memory"); goto memory_error_exit;} }
+
+#define MAX_THREAD_POOL_SIZE    10
+
+typedef enum
+{
+    SEND_TYPE_MULTICAST = 0, SEND_TYPE_UNICAST
+} CASendDataType_t;
+
+typedef struct
+{
+    CASendDataType_t type;
+    CARemoteEndpoint_t *remoteEndpoint;
+    CARequestInfo_t *requestInfo;
+    CAResponseInfo_t *responseInfo;
+    CAHeaderOption_t *options;
+    uint8_t numOptions;
+} CAData_t;
+
+// message handler callback
+static CAMessageHandlerCallback gHandlerCallback = NULL;
+
+// handler field
+static CARequestCallback gRequestHandler = NULL;
+static CAResponseCallback gResponseHandler = NULL;
+
+static void CAProcessData(CAData_t *data)
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    VERIFY_NON_NULL_VOID(data, TAG1, "data");
+    VERIFY_NON_NULL_VOID(data->remoteEndpoint, TAG1, "remoteendpoint");
+
+    CAResult_t res = CA_STATUS_FAILED;
+
+    CASendDataType_t type = data->type;
+
+    if (type == SEND_TYPE_UNICAST)
+    {
+        coap_pdu_t *pdu = NULL;
+
+        if (data->requestInfo != NULL)
+        {
+            OIC_LOG_V(DEBUG, TAG1, "reqInfo avlbl");
+
+            pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri,
+                                               data->requestInfo->method, data->requestInfo->info);
+        }
+        else if (data->responseInfo != NULL)
+        {
+            OIC_LOG_V(DEBUG, TAG1, "resInfo avlbl");
+
+            pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri,
+                                               data->responseInfo->result, data->responseInfo->info);
+        }
+        else
+        {
+            OIC_LOG(DEBUG, TAG1, "request info, response info is empty");
+        }
+
+        // interface controller function call.
+        if (NULL != pdu)
+        {
+            OIC_LOG_V(DEBUG, TAG1, "payload: %s", pdu->data);
+
+            OIC_LOG_V(DEBUG, TAG1, "code: %d", pdu->hdr->code);
+
+            OIC_LOG_V(DEBUG, TAG1, "buffer: %s", pdu->hdr);
+
+            res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length);
+        }
+
+    }
+    else if (type == SEND_TYPE_MULTICAST)
+    {
+        OIC_LOG(DEBUG, TAG1, "both requestInfo & responseInfo is not available");
+
+        coap_pdu_t *pdu = NULL;
+        CAInfo_t info;
+        memset(&info, 0, sizeof(CAInfo_t));
+
+        info.options = data->options;
+        info.numOptions = data->numOptions;
+        info.token = data->requestInfo->info.token;
+
+        pdu = (coap_pdu_t *) CAGeneratePdu(data->remoteEndpoint->resourceUri, CA_GET, info);
+
+        if (NULL != pdu)
+        {
+            OIC_LOG_V(DEBUG, TAG1, "PDU Maker - payload : %s", pdu->data);
+
+            OIC_LOG_V(DEBUG, TAG1, "PDU Maker - type : %d", pdu->hdr->type);
+
+            OIC_LOG_V(DEBUG, TAG1, "PDU Maker - code : %d", pdu->hdr->code);
+
+            OIC_LOG_V(DEBUG, TAG1, "PDU Maker - id : %d", pdu->hdr->id);
+
+            OIC_LOG_V(DEBUG, TAG1, "PDU Maker - token : %s", pdu->hdr->token);
+            OIC_LOG_V(DEBUG, TAG1, "PDU Maker - buffer data : %s", pdu->hdr);
+
+            res = CASendMulticastData(pdu->hdr, pdu->length);
+        }
+    }
+    else
+    {
+        OIC_LOG(DEBUG, TAG1, "unknown type!");
+    }
+
+    if (gHandlerCallback != NULL)
+    {
+        gHandlerCallback("", res);
+    }
+    OIC_LOG(DEBUG, TAG1, "OUT");
+}
+
+static void CAReceivedPacketCallback(CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    VERIFY_NON_NULL_VOID(data, TAG1, "data");
+
+    coap_pdu_t *pdu;
+    uint32_t code = CA_NOT_FOUND;
+    pdu = (coap_pdu_t *) CAParsePDU((const char *) data, &code);
+    //OICFree(data);
+
+    char uri[CA_MAX_URI_LENGTH] = { 0, };
+
+    if (CA_GET == code || CA_POST == code  || CA_PUT == code  || CA_DELETE == code )
+    {
+        CARequestInfo_t *ReqInfo;
+        ReqInfo = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
+        VERIFY_NON_NULL_VOID(ReqInfo, TAG1, "reqInfo");
+        memset(ReqInfo, 0, sizeof(CARequestInfo_t));
+        CAGetRequestInfoFromPdu(pdu, ReqInfo, uri);
+
+        if (NULL != ReqInfo->info.options)
+        {
+            uint32_t i;
+            for (i = 0; i < ReqInfo->info.numOptions; i++)
+            {
+                OIC_LOG_V(DEBUG, TAG1, "Request- optionID: %d", ReqInfo->info.options[i].optionID);
+
+                OIC_LOG_V(DEBUG, TAG1, "Request- list: %s", ReqInfo->info.options[i].optionData);
+            }
+        }
+
+        if(NULL != ReqInfo->info.payload)
+        {
+            OIC_LOG_V(DEBUG, TAG1, "Request- payload: %s", ReqInfo->info.payload);
+        }
+
+        OIC_LOG_V(DEBUG, TAG1, "Request- code: %d", ReqInfo->method);
+        OIC_LOG_V(DEBUG, TAG1, "Request- token : %s", ReqInfo->info.token);
+
+        if (NULL != endpoint)
+        {
+            endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
+            memset(endpoint->resourceUri, 0, strlen(uri) + 1);
+            memcpy(endpoint->resourceUri, uri, strlen(uri));
+            OIC_LOG_V(DEBUG, TAG1, "URI : %s", endpoint->resourceUri);
+        }
+
+        if (ReqInfo)
+        {
+            if (gRequestHandler)
+            {
+                gRequestHandler(endpoint, ReqInfo);
+            }
+
+            CADestroyRequestInfoInternal(ReqInfo);
+        }
+    }
+    else
+    {
+        CAResponseInfo_t *ResInfo = (CAResponseInfo_t *) OICMalloc(sizeof(CAResponseInfo_t));
+        VERIFY_NON_NULL_VOID(ResInfo, TAG1, "ResInfo");
+        memset(ResInfo, 0, sizeof(CAResponseInfo_t));
+        CAGetResponseInfoFromPdu(pdu, ResInfo, uri);
+
+        if (NULL != ResInfo->info.options)
+        {
+            uint32_t i;
+            for (i = 0; i < ResInfo->info.numOptions; i++)
+            {
+                OIC_LOG_V(DEBUG, TAG1, "optionID: %d", ResInfo->info.options[i].optionID);
+
+                OIC_LOG_V(DEBUG, TAG1, "list: %s", ResInfo->info.options[i].optionData);
+            }
+
+            if(NULL != ResInfo->info.payload)
+            {
+                OIC_LOG_V(DEBUG, TAG1, "payload: %s", ResInfo->info.payload);
+            }
+
+            OIC_LOG_V(DEBUG, TAG1, "code: %d", ResInfo->result);
+        }
+
+        if (NULL != endpoint)
+        {
+            endpoint->resourceUri = (char *) OICMalloc(strlen(uri) + 1);
+            memset(endpoint->resourceUri, 0, strlen(uri) + 1);
+            memcpy(endpoint->resourceUri, uri, strlen(uri));
+            OIC_LOG_V(DEBUG, TAG1, "URI : %s", endpoint->resourceUri);
+        }
+
+        if (ResInfo != NULL)
+        {
+            if (gResponseHandler)
+            {
+                gResponseHandler(endpoint, ResInfo);
+            }
+            CADestroyResponseInfoInternal(ResInfo);
+        }
+    }
+
+    if (endpoint && endpoint->resourceUri)
+    {
+        OICFree(endpoint->resourceUri);
+    }
+    OIC_LOG(DEBUG, TAG1, "OUT");
+}
+
+static void CANetworkChangedCallback(CALocalConnectivity_t *info, CANetworkStatus_t status)
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    OIC_LOG(DEBUG, TAG1, "OUT");
+}
+
+void CAHandleRequestResponseCallbacks()
+{
+    //OIC_LOG(DEBUG, TAG1, "IN");
+
+    CAReadData();
+
+    //OIC_LOG(DEBUG, TAG1, "OUT");
+}
+
+CAResult_t CADetachRequestMessage(const CARemoteEndpoint_t *object, const CARequestInfo_t *request)
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+
+    VERIFY_NON_NULL(object, TAG1, "object");
+    VERIFY_NON_NULL(request, TAG1, "request");
+
+    CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
+    MEMORY_ALLOCK_CHECK(data);
+
+    // initialize
+    memset(data, 0, sizeof(CAData_t));
+
+    // clone remote endpoint
+    CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(object);
+    MEMORY_ALLOCK_CHECK(remoteEndpoint);
+
+    // clone request info
+    CARequestInfo_t *requestInfo = CACloneRequestInfo(request);
+    MEMORY_ALLOCK_CHECK(requestInfo);
+
+    // save data
+    data->type = SEND_TYPE_UNICAST;
+    data->remoteEndpoint = remoteEndpoint;
+    data->requestInfo = requestInfo;
+    data->responseInfo = NULL;
+
+    CAProcessData(data);
+    CADestroyRemoteEndpoint(remoteEndpoint);
+    CADestroyRequestInfoInternal(requestInfo);
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG1, "OUT");
+    return CA_STATUS_OK;
+
+    // memory error label.
+memory_error_exit:
+
+    CADestroyRemoteEndpointInternal(remoteEndpoint);
+
+    CADestroyRequestInfoInternal(requestInfo);
+
+    if (data != NULL)
+    {
+        OICFree(data);
+    }
+    OIC_LOG(DEBUG, TAG1, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+CAResult_t CADetachResponseMessage(const CARemoteEndpoint_t *object,
+                                   const CAResponseInfo_t *response)
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    VERIFY_NON_NULL(object, TAG1, "object");
+    VERIFY_NON_NULL(response, TAG1, "response");
+
+    CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
+    MEMORY_ALLOCK_CHECK(data);
+
+    // initialize
+    memset(data, 0, sizeof(CAData_t));
+
+    // clone remote endpoint
+    CARemoteEndpoint_t *remoteEndpoint = CACloneRemoteEndpoint(object);
+    MEMORY_ALLOCK_CHECK(remoteEndpoint);
+
+    // clone response info
+    CAResponseInfo_t *responseInfo = CACloneResponseInfo(response);
+    MEMORY_ALLOCK_CHECK(responseInfo);
+
+    // save data
+    data->type = SEND_TYPE_UNICAST;
+    data->remoteEndpoint = remoteEndpoint;
+    data->requestInfo = NULL;
+    data->responseInfo = responseInfo;
+
+    CAProcessData(data);
+    CADestroyRemoteEndpoint(remoteEndpoint);
+    CADestroyResponseInfoInternal(responseInfo);
+    OICFree(data);
+    OIC_LOG(DEBUG, TAG1, "OUT");
+    return CA_STATUS_OK;
+
+    // memory error label.
+memory_error_exit:
+
+    CADestroyRemoteEndpointInternal(remoteEndpoint);
+
+    CADestroyResponseInfoInternal(responseInfo);
+
+    if (data != NULL)
+    {
+        OICFree(data);
+    }
+    OIC_LOG(DEBUG, TAG1, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+CAResult_t CADetachMessageResourceUri(const CAURI_t resourceUri, const CAToken_t token, const CAHeaderOption_t* options,
+                                      uint8_t numOptions)
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    if (resourceUri == NULL)
+    {
+        return CA_STATUS_FAILED;
+    }
+
+    CAData_t *data = (CAData_t *) OICMalloc(sizeof(CAData_t));
+    MEMORY_ALLOCK_CHECK(data);
+
+    // initialize
+    memset(data, 0, sizeof(CAData_t));
+
+    CAAddress_t addr;
+    memset(&addr, 0, sizeof(CAAddress_t));
+    CARemoteEndpoint_t *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));
+    memset(ReqInfo, 0, sizeof(CARequestInfo_t));
+    ReqInfo->method = CA_GET;
+    ReqInfo->info.token = token;
+    data->requestInfo = ReqInfo;
+
+    data->responseInfo = NULL;
+    data->options = NULL;
+    data->numOptions = 0;
+
+    if (options != NULL && numOptions > 0)
+    {
+        // copy data
+        CAHeaderOption_t *temp = (CAHeaderOption_t *) OICMalloc(
+                                     sizeof(CAHeaderOption_t) * numOptions);
+
+        MEMORY_ALLOCK_CHECK(temp);
+
+        memset(temp, 0, sizeof(CAHeaderOption_t) * numOptions);
+        memcpy(temp, options, sizeof(CAHeaderOption_t) * numOptions);
+
+        data->options = temp;
+        data->numOptions = numOptions;
+    }
+
+    CAProcessData(data);
+    CADestroyRemoteEndpoint(remoteEndpoint);
+    OICFree(data);
+    OICFree(ReqInfo);
+    OIC_LOG(DEBUG, TAG1, "OUT");
+    return CA_STATUS_OK;
+
+    // memory error label.
+memory_error_exit:
+
+    CADestroyRemoteEndpointInternal(remoteEndpoint);
+
+    if (data != NULL)
+    {
+        OICFree(data);
+    }
+    OIC_LOG(DEBUG, TAG1, "OUT");
+    return CA_MEMORY_ALLOC_FAILED;
+}
+
+void CASetMessageHandlerCallback(CAMessageHandlerCallback callback)
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    gHandlerCallback = callback;
+    OIC_LOG(DEBUG, TAG1, "OUT");
+}
+
+void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler)
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    gRequestHandler = ReqHandler;
+    gResponseHandler = RespHandler;
+    OIC_LOG(DEBUG, TAG1, "OUT");
+}
+
+CAResult_t CAInitializeMessageHandler()
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    CASetPacketReceivedCallback(CAReceivedPacketCallback);
+
+    CASetNetworkChangeCallback(CANetworkChangedCallback);
+
+    CAInitializeAdapters();
+    OIC_LOG(DEBUG, TAG1, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateMessageHandler()
+{
+    OIC_LOG(DEBUG, TAG1, "IN");
+    // terminate interface adapters by controller
+    CATerminateAdapters();
+
+    OIC_LOG(DEBUG, TAG1, "OUT");
+}
+
index d374ebc..72b0d07 100644 (file)
 #define TAG PCF("CA")
 
 static u_arraylist_t *gSelectedNetworkList = 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)
 {
@@ -96,6 +101,9 @@ CAResult_t CAAddNetworkType(uint32_t ConnectivityType)
 
 CAResult_t CARemoveNetworkType(uint32_t ConnectivityType)
 {
+    uint8_t index;
+    uint32_t type;
+
     if (gSelectedNetworkList == NULL)
     {
         OIC_LOG_V(DEBUG, TAG, "Selected network not found");
@@ -103,77 +111,85 @@ CAResult_t CARemoveNetworkType(uint32_t ConnectivityType)
         return CA_STATUS_FAILED;
     }
 
-    switch (ConnectivityType)
+    for (index = 0; index < u_arraylist_length(gSelectedNetworkList); index++)
     {
-        case CA_ETHERNET:
+        type = *(uint32_t*) u_arraylist_get(gSelectedNetworkList, index);
+
+        if(ConnectivityType == type)
+        {
+            switch (ConnectivityType)
+            {
+                case CA_ETHERNET:
 
 #ifndef ETHERNET_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(ETHERNET) - Not Supported");
-            return CA_NOT_SUPPORTED;
+                    OIC_LOG_V(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, &NETWORK_ETHERNET);
+                    OIC_LOG_V(DEBUG, TAG, "Remove network type(ETHERNET)");
+                    u_arraylist_remove(gSelectedNetworkList, index);
 #endif /* ETHERNET_ADAPTER */
-            break;
+                    break;
 
-        case CA_WIFI:
+                case CA_WIFI:
 
 #ifndef WIFI_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(WIFI) - Not Supported");
-            return CA_NOT_SUPPORTED;
+                    OIC_LOG_V(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, &NETWORK_WIFI);
+                    OIC_LOG_V(DEBUG, TAG, "Remove network type(WIFI)");
+                    u_arraylist_remove(gSelectedNetworkList, index);
 #endif /* WIFI_ADAPTER */
 
-            break;
+                    break;
 
-        case CA_EDR:
+                case CA_EDR:
 
 #ifndef EDR_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(EDR) - Not Supported");
-            return CA_NOT_SUPPORTED;
+                    OIC_LOG_V(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, &NETWORK_EDR);
+                    OIC_LOG_V(DEBUG, TAG, "Remove network type(EDR)");
+                    u_arraylist_remove(gSelectedNetworkList, index);
 #endif /* EDR_ADAPTER */
 
-            break;
+                    break;
 
-        case CA_LE:
+                case CA_LE:
 
 #ifdef LE_ADAPTER
-            OIC_LOG_V(DEBUG, TAG, "Remove network type(LE) - Not Supported");
-            return CA_NOT_SUPPORTED;
+                    OIC_LOG_V(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, &NETWORK_LE);
+                    OIC_LOG_V(DEBUG, TAG, "Remove network type(LE)");
+                    u_arraylist_remove(gSelectedNetworkList, index);
 #endif /* LE_ADAPTER */
 
-            break;
-    }
+                    break;
+            }
 
-    // stop selected interface adapter
-    CAStopAdapter(ConnectivityType);
+            // stop selected interface adapter
+            CAStopAdapter(ConnectivityType);
+        }
+    }
 
     return CA_STATUS_OK;
 }
 
-u_arraylist_tCAGetSelectedNetworkList()
+u_arraylist_t *CAGetSelectedNetworkList()
 {
-    OIC_LOG(DEBUG, TAG, "IN");
+    OIC_LOG(DEBUG, TAG, "CAGetSelectedNetworkList IN");
     if (gSelectedNetworkList == NULL)
     {
         OIC_LOG_V(DEBUG, TAG, "Selected network not found");
 
         return NULL;
     }
-    OIC_LOG(DEBUG, TAG, "OUT");
+    OIC_LOG(DEBUG, TAG, "CAGetSelectedNetworkList OUT");
     return gSelectedNetworkList;
 }
 
-CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_tsize)
+CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size)
 {
     OIC_LOG_V(DEBUG, TAG, "get network information.");
 
diff --git a/resource/csdk/connectivity/src/canetworkconfigurator_singlethread.c b/resource/csdk/connectivity/src/canetworkconfigurator_singlethread.c
new file mode 100644 (file)
index 0000000..7a61234
--- /dev/null
@@ -0,0 +1,194 @@
+/******************************************************************
+ *
+ * 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 "cainterfacecontroller_singlethread.h"
+
+#include <stdlib.h>
+
+#include "canetworkconfigurator.h"
+#include "uarraylist.h"
+#include "logger.h"
+
+#define TAG "CANW_ST"
+
+static u_arraylist_t *gSelectedNetworkList = 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)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    if (gSelectedNetworkList == NULL)
+    {
+        gSelectedNetworkList = u_arraylist_create();
+    }
+
+    switch (ConnectivityType)
+    {
+        case CA_ETHERNET:
+
+#ifndef ETHERNET_ADAPTER
+            OIC_LOG_V(DEBUG, TAG, "Add network type(ETHERNET) - Not Supported");
+            return CA_NOT_SUPPORTED;
+#endif /* ETHERNET_ADAPTER */
+
+            OIC_LOG_V(DEBUG, TAG, "Add network type(ETHERNET)");
+            u_arraylist_add(gSelectedNetworkList, &NETWORK_ETHERNET);
+
+            break;
+
+        case CA_WIFI:
+
+#ifndef WIFI_ADAPTER
+            OIC_LOG_V(DEBUG, TAG, "Add network type(WIFI) - Not Supported");
+            return CA_NOT_SUPPORTED;
+#endif /* WIFI_ADAPTER */
+
+            OIC_LOG_V(DEBUG, TAG, "Add network type(WIFI)");
+            u_arraylist_add(gSelectedNetworkList, &NETWORK_WIFI);
+
+            break;
+
+        case CA_EDR:
+
+#ifndef EDR_ADAPTER
+            OIC_LOG_V(DEBUG, TAG, "Add network type(EDR) - Not Supported");
+            return CA_NOT_SUPPORTED;
+#endif /* EDR_ADAPTER */
+
+            OIC_LOG_V(DEBUG, TAG, "Add network type(EDR)");
+            u_arraylist_add(gSelectedNetworkList, &NETWORK_EDR);
+            break;
+
+        case CA_LE:
+
+#ifndef LE_ADAPTER
+            OIC_LOG_V(DEBUG, TAG, "Add network type(LE) - Not Supported");
+            return CA_NOT_SUPPORTED;
+#endif /* LE_ADAPTER */
+
+            OIC_LOG_V(DEBUG, TAG, "Add network type(LE)");
+            u_arraylist_add(gSelectedNetworkList, &NETWORK_LE);
+            break;
+
+    }
+
+    // start selected interface adapter
+    CAStartAdapter(ConnectivityType);
+    OIC_LOG(DEBUG, TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CARemoveNetworkType(uint32_t ConnectivityType)
+{
+    OIC_LOG(DEBUG, TAG, "IN");
+    uint8_t index;
+    uint32_t type;
+    if (gSelectedNetworkList == NULL)
+    {
+        OIC_LOG_V(DEBUG, TAG, "Selected network not found");
+
+        return CA_STATUS_FAILED;
+    }
+
+    for (index = 0; index < u_arraylist_length(gSelectedNetworkList); index++)
+    {
+        type = *(uint32_t*) u_arraylist_get(gSelectedNetworkList, index);
+
+        if(ConnectivityType == type)
+        {
+            switch (ConnectivityType)
+            {
+                case CA_ETHERNET:
+
+#ifndef ETHERNET_ADAPTER
+                    OIC_LOG_V(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);
+#endif /* ETHERNET_ADAPTER */
+                    break;
+
+                case CA_WIFI:
+
+#ifndef WIFI_ADAPTER
+                    OIC_LOG_V(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);
+#endif /* WIFI_ADAPTER */
+
+                    break;
+
+                case CA_EDR:
+
+#ifndef EDR_ADAPTER
+                    OIC_LOG_V(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);
+#endif /* EDR_ADAPTER */
+
+                    break;
+
+                case CA_LE:
+
+#ifdef LE_ADAPTER
+                    OIC_LOG_V(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);
+#endif /* LE_ADAPTER */
+
+                    break;
+            }
+
+            // stop selected interface adapter
+            CAStopAdapter(ConnectivityType);
+        }
+    }
+
+    return CA_STATUS_OK;
+}
+
+u_arraylist_t *CAGetSelectedNetworkList()
+{
+    //OIC_LOG(DEBUG, TAG, "IN");
+    if (gSelectedNetworkList == NULL)
+    {
+        OIC_LOG_V(DEBUG, TAG, "Selected network not found");
+
+        return NULL;
+    }
+    //OIC_LOG(DEBUG, TAG, "OUT");
+    return gSelectedNetworkList;
+}
+
+CAResult_t CAGetNetworkInformationInternal(CALocalConnectivity_t **info, uint32_t *size)
+{
+    return CAGetNetworkInfo(info, size);
+}
index deb988f..b50c432 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 
+
 #include "caprotocolmessage.h"
 #include "logger.h"
 #include "oic_malloc.h"
 
-#define TAG PCF("CA")
+#define TAG "CA"
 
 #define CA_MAX_TOKEN_LEN   (8)
 #define CA_FLAGS_BLOCK 0x01
 #define CA_BUFSIZE 128
 #define CA_COAP_MESSAGE_CON 0
 
-uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t* outReqInfo, char* outUri)
+#ifdef __ARDUINO__
+#include "util.h"
+#else
+#include <time.h>
+#endif //#ifdef __ARDUINO__
+
+uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t *outReqInfo, char *outUri)
 {
-    OIC_LOG(DEBUG, TAG, "get request info from PDU");
+    OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu IN");
     if (NULL == pdu)
         return 0;
 
     uint32_t code = CA_NOT_FOUND;
     CAGetRequestPDUInfo(pdu, &code, &(outReqInfo->info), outUri);
     outReqInfo->method = code;
+    OIC_LOG(DEBUG, TAG, "CAGetRequestInfoFromPdu OUT");
     return 1;
 }
 
-uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t* outResInfo, char* outUri)
+uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo, char *outUri)
 {
-    OIC_LOG(DEBUG, TAG, "get response info from PDU");
+    OIC_LOG(DEBUG, TAG, "CAGetResponseInfoFromPdu IN");
     if (NULL == pdu)
         return 0;
 
     uint32_t code = CA_NOT_FOUND;
     CAGetRequestPDUInfo(pdu, &code, &(outResInfo->info), outUri);
     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)
+coap_pdu_t *CAGeneratePdu(const char *uri, const uint32_t code, const CAInfo_t info)
 {
-    OIC_LOG(DEBUG, TAG, "generate PDU");
+    OIC_LOG(DEBUG, TAG, "CAGeneratePdu IN");
 
     coap_pdu_t *pdu;
-    charcoapUri = NULL;
+    char *coapUri = NULL;
     uint32_t coapHeaderLength = 12;
     uint32_t length;
     coap_list_t *optlist = NULL;
@@ -78,7 +86,7 @@ coap_pdu_t* CAGeneratePdu(const char* uri, const uint32_t code, const CAInfo_t i
         return NULL;
     }
 
-    coapUri = (char*) OICMalloc(length + coapHeaderLength + 1);
+    coapUri = (char *) OICMalloc(length + coapHeaderLength + 1);
     memset(coapUri, 0, length + coapHeaderLength + 1);
 
     if (NULL != coapUri)
@@ -97,39 +105,37 @@ coap_pdu_t* CAGeneratePdu(const char* uri, const uint32_t code, const CAInfo_t i
 
     if (NULL != info.payload) // payload is include in request / response
     {
-        if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload)))
+        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)))
+        if (!(pdu = CACreatePDUforRequest((code_t) code, optlist, info)))
             return NULL;
     }
 
     // pdu print method : coap_show_pdu(pdu);
-
+    OIC_LOG(DEBUG, TAG, "CAGeneratePdu OUT");
     return pdu;
 }
 
-coap_pdu_t* CAParsePDU(const char* data, uint32_t* outCode)
+coap_pdu_t *CAParsePDU(const char *data, uint32_t *outCode)
 {
-    coap_pdu_t* outpdu = coap_new_pdu();
+    OIC_LOG(DEBUG, TAG, "CAParsePDU IN");
+    coap_pdu_t *outpdu = coap_new_pdu();
     coap_pdu_parse((unsigned char *) data, strlen(data), outpdu);
     (*outCode) = (uint32_t) outpdu->hdr->code;
-
+    OIC_LOG(DEBUG, TAG, "CAParsePDU OUT");
     return outpdu;
 }
 
-coap_pdu_tCACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options,
-        const char* payload)
+coap_pdu_t *CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options,
+        const char* payload, const CAInfo_t info)
 {
-    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload");
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload IN");
 
     coap_pdu_t *pdu;
     coap_list_t *opt;
-    unsigned char _token_data[8];
-    str the_token =
-    { 0, _token_data };
 
     uint32_t CAFlags = 0;
     coap_block_t CABlock =
@@ -143,11 +149,12 @@ coap_pdu_t* CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *opt
     prng((unsigned char * )&message_id, sizeof(unsigned short));
 
     pdu->hdr->type = CA_COAP_MESSAGE_CON;
-    pdu->hdr->id = htons(++message_id);
+    ++message_id;
+    pdu->hdr->id = htons(message_id);
     pdu->hdr->code = code;
 
-    pdu->hdr->token_length = the_token.length;
-    if (!coap_add_token(pdu, the_token.length, the_token.s))
+    pdu->hdr->token_length = strlen(info.token);
+    if (!coap_add_token(pdu, strlen(info.token),(unsigned char*)info.token))
     {
         OIC_LOG(DEBUG, TAG, "cannot add token to request");
     }
@@ -155,8 +162,8 @@ coap_pdu_t* CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *opt
     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));
+                        COAP_OPTION_LENGTH(*(coap_option * )opt->data),
+                        COAP_OPTION_DATA(*(coap_option * )opt->data));
     }
 
     if (NULL != payload)
@@ -173,32 +180,35 @@ coap_pdu_t* CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *opt
             coap_add_block(pdu, len, (const unsigned char *) payload, CABlock.num, CABlock.szx);
         }
     }
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload OUT");
     return pdu;
 }
 
-coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options)
+coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options, const CAInfo_t info)
 {
-    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest");
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest IN");
 
     coap_pdu_t *pdu;
     coap_list_t *opt;
-    unsigned char _token_data[8];
-    str the_token =
-    { 0, _token_data };
 
     if (!(pdu = coap_new_pdu()))
+    {
+        OIC_LOG(DEBUG, TAG, "Out of memory");
         return NULL;
+    }
 
     /* initialize message id */
     unsigned short message_id;
     prng((unsigned char * )&message_id, sizeof(unsigned short));
 
     pdu->hdr->type = CA_COAP_MESSAGE_CON;
-    pdu->hdr->id = htons(++message_id);
+    ++message_id;
+    pdu->hdr->id = htons(message_id);
     pdu->hdr->code = code;
 
-    pdu->hdr->token_length = the_token.length;
-    if (!coap_add_token(pdu, the_token.length, the_token.s))
+    OIC_LOG_V(DEBUG, TAG, "token info : %s, %d", info.token, strlen(info.token));
+    pdu->hdr->token_length = strlen(info.token);
+    if (!coap_add_token(pdu, strlen(info.token),(unsigned char*) info.token))
     {
         OIC_LOG(DEBUG, TAG, "cannot add token to request");
     }
@@ -206,16 +216,16 @@ coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options)
     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));
+                        COAP_OPTION_LENGTH(*(coap_option * )opt->data),
+                        COAP_OPTION_DATA(*(coap_option * )opt->data));
     }
-
+    OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest OUT");
     return pdu;
 }
 
-void CAParseURI(const charuriInfo, coap_list_t **optlist)
+void CAParseURI(const char *uriInfo, coap_list_t **optlist)
 {
-    OIC_LOG(DEBUG, TAG, "parse URI");
+    OIC_LOG(DEBUG, TAG, "CAParseURI IN");
 
     unsigned char portbuf[2];
     unsigned char _buf[CA_BUFSIZE];
@@ -232,8 +242,8 @@ void CAParseURI(const char* uriInfo, coap_list_t **optlist)
     if (uri.port != COAP_DEFAULT_PORT)
     {
         coap_insert(optlist,
-                CACreateNewOptionNode(COAP_OPTION_URI_PORT,
-                        coap_encode_var_bytes(portbuf, uri.port), portbuf), CAOrderOpts);
+                    CACreateNewOptionNode(COAP_OPTION_URI_PORT,
+                                          coap_encode_var_bytes(portbuf, uri.port), portbuf), CAOrderOpts);
     }
 
     if (uri.path.length)
@@ -244,8 +254,8 @@ void CAParseURI(const char* uriInfo, coap_list_t **optlist)
         while (res--)
         {
             coap_insert(optlist,
-                    CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf),
-                            COAP_OPT_VALUE(buf)), CAOrderOpts);
+                        CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf),
+                                              COAP_OPT_VALUE(buf)), CAOrderOpts);
             buf += COAP_OPT_SIZE(buf);
         }
     }
@@ -259,17 +269,18 @@ void CAParseURI(const char* uriInfo, coap_list_t **optlist)
         while (res--)
         {
             coap_insert(optlist,
-                    CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf),
-                            COAP_OPT_VALUE(buf)), CAOrderOpts);
+                        CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf),
+                                              COAP_OPT_VALUE(buf)), CAOrderOpts);
 
             buf += COAP_OPT_SIZE(buf);
         }
     }
-
+    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;
@@ -287,20 +298,26 @@ void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **o
             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);
+                        CACreateNewOptionNode(info.options[i].optionID, info.options[i].optionLength,
+                                              info.options[i].optionData), CAOrderOpts);
         }
     }
+    OIC_LOG(DEBUG, TAG, "CAParseHeadOption OUT");
 }
 
-coap_list_tCACreateNewOptionNode(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)
 {
+    OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode IN");
     coap_option *option;
     coap_list_t *node;
 
     option = coap_malloc(sizeof(coap_option) + length);
     if (!option)
-        goto error;
+    {
+        OIC_LOG(DEBUG, TAG, "Out of memory");
+        return NULL;
+    }
+    memset(option, 0, sizeof(coap_option)+length);
 
     COAP_OPTION_KEY(*option) = key;
     COAP_OPTION_LENGTH(*option) = length;
@@ -309,41 +326,56 @@ coap_list_t* CACreateNewOptionNode(const uint16_t key, const uint32_t length, co
     /* we can pass NULL here as delete function since option is released automatically  */
     node = coap_new_listnode(option, NULL);
 
-    if (node)
-        return node;
-
-    error: perror("new_option_node: malloc");
-    coap_free(option);
-    return NULL;
+    if (!node)
+    {
+        OIC_LOG(DEBUG, TAG, "coap_new_listnode returns NULL");
+        coap_free(option);
+        return NULL;
+    }
+    //coap_free(option);
+    OIC_LOG(DEBUG, TAG, "CACreateNewOptionNode OUT");
+    return node;
 }
 
-int32_t CAOrderOpts(void *a, void *b)
+int CAOrderOpts(void *a, void *b)
 {
+    OIC_LOG(DEBUG, TAG, "CAOrderOpts IN");
     if (!a || !b)
+    {
         return a < b ? -1 : 1;
+    }
 
     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);
 }
 
-uint32_t getOptionCount(coap_opt_iterator_t opt_iter)
+uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
 {
+    OIC_LOG(DEBUG, TAG, "CAGetOptionCount IN");
     uint32_t count = 0;
     coap_opt_t *option;
 
     while ((option = coap_option_next(&opt_iter)))
     {
-        count++;
-    }
+        if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
+        {
 
+        } else {
+            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 CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t *outCode, CAInfo_t *outInfo, char *outUri)
 {
-    unsigned char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */
+    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;
@@ -357,22 +389,25 @@ void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t* outCode, CAInfo_t* out
 
     memset(optionResult, 0, sizeof(optionResult));
 
-    count = getOptionCount(opt_iter);
-
     // set code
     (*outCode) = (uint32_t) pdu->hdr->code;
 
     // init HeaderOption list
+    count = CAGetOptionCount(opt_iter);
+
     memset(outInfo, 0, sizeof(CAInfo_t));
     outInfo->numOptions = count;
-    outInfo->options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t) * count);
-    memset(outInfo->options, 0, sizeof(CAHeaderOption_t) * count);
+    if(count > 0)
+    {
+    outInfo->options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t) * count);
+        memset(outInfo->options, 0, sizeof(CAHeaderOption_t) * count);
+    }
 
     while ((option = coap_option_next(&opt_iter)))
     {
 
-        if (print_readable(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), buf, sizeof(buf),
-                encode))
+        if (CAGetOptionData((uint8_t*)(COAP_OPT_VALUE(option)), COAP_OPT_LENGTH(option), (uint8_t*)buf, sizeof(buf),
+                           encode))
         {
             if (COAP_OPTION_URI_PATH == opt_iter.type || COAP_OPTION_URI_QUERY == opt_iter.type)
             {
@@ -398,18 +433,20 @@ void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t* outCode, CAInfo_t* out
                     memcpy(optionResult + optionLength, buf, strlen((const char *) buf));
                     optionLength += strlen((const char *) buf);
                 }
-            }
+            } else {
 
-            if (idx < count)
-            {
-                uint32_t length = (uint32_t) strlen((const char *) buf);
-
-                if(length <= CA_MAX_HEADER_OPTION_DATA_LENGTH) {
-                    outInfo->options[idx].optionID = opt_iter.type;
-                    outInfo->options[idx].optionLength = length;
-                    outInfo->options[idx].protocolID = CA_COAP_ID;
-                    memcpy(outInfo->options[idx].optionData, buf, length);
-                    idx++;
+                if (idx < count)
+                {
+                    uint32_t length = (uint32_t) strlen((const char *) buf);
+
+                if (length <= CA_MAX_HEADER_OPTION_DATA_LENGTH)
+                {
+                        outInfo->options[idx].optionID = opt_iter.type;
+                        outInfo->options[idx].optionLength = length;
+                        outInfo->options[idx].protocolID = CA_COAP_ID;
+                        memcpy(outInfo->options[idx].optionData, buf, length);
+                        idx++;
+                    }
                 }
             }
         }
@@ -418,30 +455,35 @@ void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t* outCode, CAInfo_t* out
     // set token data
     if (pdu->hdr->token_length > 0)
     {
-        outInfo->token = (char*) OICMalloc(pdu->hdr->token_length);
+        OIC_LOG(DEBUG, TAG, "inside pdu->hdr->token_length");
+        outInfo->token = (char *) OICMalloc(pdu->hdr->token_length);
         memcpy(outInfo->token, pdu->hdr->token, pdu->hdr->token_length);
     }
 
     // set payload data
     if (NULL != pdu->data)
     {
-        outInfo->payload = (char*) OICMalloc(strlen((const char *) pdu->data) + 1);
+        OIC_LOG(DEBUG, TAG, "inside pdu->data");
+        outInfo->payload = (char *) OICMalloc(strlen((const char *) pdu->data) + 1);
         memcpy(outInfo->payload, pdu->data, strlen((const char *) pdu->data) + 1);
     }
 
+    OIC_LOG_V(DEBUG, TAG, "made URL : %s\n", optionResult);
     // set uri info
     memcpy(outUri, optionResult, strlen(optionResult));
+    OIC_LOG(DEBUG, TAG, "CAGetRequestPDUInfo OUT");
 }
 
-CAResult_t CAGenerateTokenInternal(CAToken_ttoken)
+CAResult_t CAGenerateTokenInternal(CAToken_t *token)
 {
+    OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal IN");
     if (token == NULL)
     {
         return CA_STATUS_FAILED;
     }
 
     // memory allocation
-    char* temp = (char*) OICMalloc(sizeof(char) * (CA_MAX_TOKEN_LEN + 1));
+    char *temp = (char *) OICMalloc(sizeof(char) * (CA_MAX_TOKEN_LEN + 1));
 
     if (temp == NULL)
     {
@@ -451,32 +493,40 @@ CAResult_t CAGenerateTokenInternal(CAToken_t* token)
 
     // set random byte
     uint32_t index;
+
+#ifndef __ARDUINO__
+    srand(time(NULL));
+#endif //#ifndef __ARDUINO__
     for (index = 0; index < CA_MAX_TOKEN_LEN; index++)
     {
-        temp[index] = rand() & 0xFF;
+        // use valid characters
+        temp[index] = (rand() % 94 + 33) & 0xFF;
     }
 
+    temp[index] = '\0';
     // save token
     *token = temp;
 
     OIC_LOG_V(DEBUG, TAG, "generate the token(%s)!!", *token);
-
+    OIC_LOG(DEBUG, TAG, "CAGenerateTokenInternal OUT");
     return CA_STATUS_OK;
 }
 
 void CADestroyTokenInternal(CAToken_t token)
 {
+    OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal IN");
     if (token != NULL)
     {
         OIC_LOG_V(DEBUG, TAG, "destroy the token(%s)!!", token);
 
         OICFree(token);
     }
+    OIC_LOG(DEBUG, TAG, "CADestroyTokenInternal OUT");
 }
 
-void CADeinitialize(CAInfo_tinfo)
+void CADeinitialize(CAInfo_t *info)
 {
-    OIC_LOG(DEBUG, TAG, "CADeinitialize!!");
+    OIC_LOG(DEBUG, TAG, "CADeinitialize IN");
 
     if (NULL != info)
     {
@@ -498,4 +548,46 @@ void CADeinitialize(CAInfo_t* info)
             OICFree(info->payload);
         }
     }
+    OIC_LOG(DEBUG, TAG, "CADeinitialize OUT");
+}
+
+uint32_t CAGetOptionData(const uint8_t *data, uint32_t len, uint8_t *result,
+        uint32_t buflen, uint32_t encode_always)
+{
+    const unsigned char hex[] = "0123456789ABCDEF";
+    uint32_t cnt = 0;
+    assert(data || len == 0);
+
+    if (buflen == 0 || len == 0)
+        return 0;
+
+    while (len)
+    {
+        if (!encode_always)
+        {
+            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;
+        }
+
+        ++data;
+        --len;
+    }
+
+    *result = '\0';
+    return cnt;
 }
index 0bd08eb..11fbee2 100644 (file)
@@ -21,6 +21,9 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <unistd.h>
+#include <sys/syscall.h>
+#include <sys/types.h>
 
 #include "caqueueingthread.h"
 #include "oic_malloc.h"
 
 #define TAG PCF("CA")
 
-static void CAQueueingThreadBaseRoutine(void* treadValue)
+static void CAQueueingThreadBaseRoutine(void *threadValue)
 {
     OIC_LOG_V(DEBUG, TAG, "message handler main thread start..");
 
-    CAQueueingThread_t* thread = (CAQueueingThread_t*) treadValue;
+    CAQueueingThread_t *thread = (CAQueueingThread_t *) threadValue;
 
     if (thread == NULL)
     {
@@ -64,9 +67,9 @@ static void CAQueueingThreadBaseRoutine(void* treadValue)
             continue;
 
         // get data
-        u_queue_message_tmessage = u_queue_get_element(thread->dataQueue);
+        u_queue_message_t *message = u_queue_get_element(thread->dataQueue);
 
-        voiddata = message->msg;
+        void *data = message->msg;
 
         // process data
         thread->threadTask(data);
@@ -74,11 +77,13 @@ static void CAQueueingThreadBaseRoutine(void* treadValue)
         // free
     }
 
+    u_cond_signal(thread->threadCond);
+
     OIC_LOG_V(DEBUG, TAG, "message handler main thread end..");
 }
 
-CAResult_t CAQueueingThreadInitialize(CAQueueingThread_tthread, u_thread_pool_t handle,
-        CAThreadTask task)
+CAResult_t CAQueueingThreadInitialize(CAQueueingThread_t *thread, u_thread_pool_t handle,
+                                      CAThreadTask task)
 {
     if (thread == NULL)
     {
@@ -110,7 +115,7 @@ CAResult_t CAQueueingThreadInitialize(CAQueueingThread_t* thread, u_thread_pool_
     return CA_STATUS_OK;
 }
 
-CAResult_t CAQueueingThreadStart(CAQueueingThread_tthread)
+CAResult_t CAQueueingThreadStart(CAQueueingThread_t *thread)
 {
     if (thread == NULL)
     {
@@ -125,7 +130,7 @@ CAResult_t CAQueueingThreadStart(CAQueueingThread_t* thread)
     }
 
     CAResult_t res = u_thread_pool_add_task(thread->threadPool, CAQueueingThreadBaseRoutine,
-            thread);
+                                            thread);
 
     if (res != CA_STATUS_OK)
     {
@@ -136,7 +141,7 @@ CAResult_t CAQueueingThreadStart(CAQueueingThread_t* thread)
     return res;
 }
 
-CAResult_t CAQueueingThreadAddData(CAQueueingThread_t* thread, void* data, uint32_t size)
+CAResult_t CAQueueingThreadAddData(CAQueueingThread_t *thread, void *data, uint32_t size)
 {
     if (thread == NULL)
     {
@@ -152,7 +157,7 @@ CAResult_t CAQueueingThreadAddData(CAQueueingThread_t* thread, void* data, uint3
     }
 
     // create thread data
-    u_queue_message_t* message = (u_queue_message_t*) OICMalloc(sizeof(u_queue_message_t));
+    u_queue_message_t *message = (u_queue_message_t *) OICMalloc(sizeof(u_queue_message_t));
 
     if (message == NULL)
     {
@@ -179,7 +184,7 @@ CAResult_t CAQueueingThreadAddData(CAQueueingThread_t* thread, void* data, uint3
     return CA_STATUS_OK;
 }
 
-CAResult_t CAQueueingThreadDestroy(CAQueueingThread_tthread)
+CAResult_t CAQueueingThreadDestroy(CAQueueingThread_t *thread)
 {
     if (thread == NULL)
     {
@@ -190,13 +195,14 @@ CAResult_t CAQueueingThreadDestroy(CAQueueingThread_t* thread)
     OIC_LOG_V(DEBUG, TAG, "thread destroy..");
 
     u_mutex_free(thread->threadMutex);
+    thread->threadMutex = NULL;
     u_cond_free(thread->threadCond);
     u_queue_delete(thread->dataQueue);
 
     return CA_STATUS_OK;
 }
 
-CAResult_t CAQueueingThreadStop(CAQueueingThread_tthread)
+CAResult_t CAQueueingThreadStop(CAQueueingThread_t *thread)
 {
     if (thread == NULL)
     {
@@ -215,6 +221,8 @@ CAResult_t CAQueueingThreadStop(CAQueueingThread_t* thread)
     // notity the thread
     u_cond_signal(thread->threadCond);
 
+    u_cond_wait(thread->threadCond, thread->threadMutex);    
+
     // mutex unlock
     u_mutex_unlock(thread->threadMutex);
 
index a79d43e..9538eb8 100644 (file)
 #include "caremotehandler.h"
 #include "logger.h"
 
-#define TAG PCF("CA")
+#define TAG "CA"
 
-CARemoteEndpoint_t* CACloneRemoteEndpoint(const CARemoteEndpoint_t* rep)
+CARemoteEndpoint_t *CACloneRemoteEndpoint(const CARemoteEndpoint_t *rep)
 {
-    chartemp = NULL;
+    char *temp = NULL;
     int len = 0;
 
     if (rep == NULL)
         return NULL;
 
     // allocate the remote end point structure.
-    CARemoteEndpoint_t* clone = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t));
+    CARemoteEndpoint_t *clone = (CARemoteEndpoint_t *) OICMalloc(sizeof(CARemoteEndpoint_t));
     if (clone == NULL)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+        OIC_LOG_V(DEBUG, TAG, "CACloneRemoteEndpoint Out of memory");
         return NULL;
     }
     memset(clone, 0, sizeof(CARemoteEndpoint_t));
@@ -47,10 +47,10 @@ CARemoteEndpoint_t* CACloneRemoteEndpoint(const CARemoteEndpoint_t* rep)
         // allocate reference uri field
         len = strlen(rep->resourceUri);
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
+        temp = (char *) OICMalloc(sizeof(char) * (len + 1));
         if (temp == NULL)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            OIC_LOG_V(DEBUG, TAG, "CACloneRemoteEndpoint Out of memory");
 
             CADestroyRemoteEndpointInternal(clone);
 
@@ -71,7 +71,7 @@ CARemoteEndpoint_t* CACloneRemoteEndpoint(const CARemoteEndpoint_t* rep)
 
 // return 1 : ip
 // return 0 : mac
-static int32_t getCAAddress(const char* pAddress, CAAddress_t* outAddress)
+static int32_t getCAAddress(const char *pAddress, CAAddress_t *outAddress)
 {
     if (pAddress == NULL || outAddress == NULL)
         return -1;
@@ -120,7 +120,7 @@ static int32_t getCAAddress(const char* pAddress, CAAddress_t* outAddress)
     return isIp;
 }
 
-CARemoteEndpoint_tCACreateRemoteEndpointUriInternal(const CAURI_t uri)
+CARemoteEndpoint_t *CACreateRemoteEndpointUriInternal(const CAURI_t uri)
 {
     // support URI type
     // coap://10.11.12.13:4545/resource_uri
@@ -140,7 +140,7 @@ CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri)
     }
 
     // #2. copy uri for parse
-    charcloneUri = NULL;
+    char *cloneUri = NULL;
     int32_t len = strlen(uri) - startIndex;
 
     if (len <= 0)
@@ -149,10 +149,10 @@ CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri)
         return NULL;
     }
 
-    cloneUri = (char*) OICMalloc(sizeof(char) * (len + 1));
+    cloneUri = (char *) OICMalloc(sizeof(char) * (len + 1));
     if (cloneUri == NULL)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory error!!");
+        OIC_LOG_V(DEBUG, TAG, "CACreateRemoteEndpointUriInternal Out of memory");
         return NULL;
     }
     memset(cloneUri, 0, sizeof(char) * (len + 1));
@@ -160,8 +160,8 @@ CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri)
 
     // #3. parse address
     // #4. parse resource uri
-    charpAddress = cloneUri;
-    charpResourceUri = NULL;
+    char *pAddress = cloneUri;
+    char *pResourceUri = NULL;
 
     int32_t i = 0;
     for (i = 0; i < len; i++)
@@ -210,17 +210,17 @@ CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri)
         type = CA_EDR;
     }
 
-    CARemoteEndpoint_tremoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address, type);
+    CARemoteEndpoint_t *remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address, type);
 
     OICFree(cloneUri);
 
     return remoteEndpoint;
 }
 
-CARemoteEndpoint_tCACreateRemoteEndpointInternal(const CAURI_t resourceUri,
+CARemoteEndpoint_t *CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
         const CAAddress_t addr, const CAConnectivityType_t type)
 {
-    chartemp = NULL;
+    char *temp = NULL;
     int len = 0;
 
     if (resourceUri == NULL)
@@ -230,11 +230,11 @@ CARemoteEndpoint_t* CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
     }
 
     // allocate the remote end point structure.
-    CARemoteEndpoint_t* rep = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t));
+    CARemoteEndpoint_t *rep = (CARemoteEndpoint_t *) OICMalloc(sizeof(CARemoteEndpoint_t));
 
     if (rep == NULL)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error");
+        OIC_LOG_V(DEBUG, TAG, "CACreateRemoteEndpointInternal of memory");
         return NULL;
     }
     memset(rep, 0, sizeof(CARemoteEndpoint_t));
@@ -242,10 +242,10 @@ CARemoteEndpoint_t* CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
     // allocate reference uri field
     len = strlen(resourceUri);
 
-    temp = (char*) OICMalloc(sizeof(char) * (len + 1));
+    temp = (char *) OICMalloc(sizeof(char) * (len + 1));
     if (temp == NULL)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error");
+        OIC_LOG_V(DEBUG, TAG, "CACreateRemoteEndpointInternal Out of memory");
 
         CADestroyRemoteEndpointInternal(rep);
 
@@ -266,19 +266,19 @@ CARemoteEndpoint_t* CACreateRemoteEndpointInternal(const CAURI_t resourceUri,
     return rep;
 }
 
-CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep)
+CARequestInfo_t *CACloneRequestInfo(const CARequestInfo_t *rep)
 {
-    chartemp = NULL;
+    char *temp = NULL;
     int len = 0;
 
     if (rep == NULL)
         return NULL;
 
     // allocate the request info structure.
-    CARequestInfo_t* clone = (CARequestInfo_t*) OICMalloc(sizeof(CARequestInfo_t));
+    CARequestInfo_t *clone = (CARequestInfo_t *) OICMalloc(sizeof(CARequestInfo_t));
     if (clone == NULL)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+        OIC_LOG_V(DEBUG, TAG, "CACloneRequestInfo Out of memory");
         return NULL;
     }
     memset(clone, 0, sizeof(CARequestInfo_t));
@@ -289,10 +289,10 @@ CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep)
         // allocate token field
         len = strlen(rep->info.token);
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
+        temp = (char *) OICMalloc(sizeof(char) * (len + 1));
         if (temp == NULL)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            OIC_LOG_V(DEBUG, TAG, "CACloneRequestInfo Out of memory");
 
             CADestroyRequestInfoInternal(clone);
 
@@ -308,7 +308,7 @@ CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep)
     if (rep->info.options != NULL)
     {
         // save the options
-        clone->info.options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t));
+        clone->info.options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t));
         memset(clone->info.options, 0, sizeof(CAHeaderOption_t));
         memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t));
     }
@@ -318,10 +318,10 @@ CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep)
         // allocate payload field
         len = strlen(rep->info.payload);
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
+        temp = (char *) OICMalloc(sizeof(char) * (len + 1));
         if (temp == NULL)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            OIC_LOG_V(DEBUG, TAG, "CACloneRequestInfo Out of memory");
 
             CADestroyRequestInfoInternal(clone);
 
@@ -337,19 +337,19 @@ CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep)
     return clone;
 }
 
-CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep)
+CAResponseInfo_t *CACloneResponseInfo(const CAResponseInfo_t *rep)
 {
-    chartemp = NULL;
+    char *temp = NULL;
     int len = 0;
 
     if (rep == NULL)
         return NULL;
 
     // allocate the response info structure.
-    CAResponseInfo_t* clone = (CAResponseInfo_t*) OICMalloc(sizeof(CAResponseInfo_t));
+    CAResponseInfo_t *clone = (CAResponseInfo_t *) OICMalloc(sizeof(CAResponseInfo_t));
     if (clone == NULL)
     {
-        OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+        OIC_LOG_V(DEBUG, TAG, "CACloneResponseInfo Out of memory");
         return NULL;
     }
     memset(clone, 0, sizeof(CAResponseInfo_t));
@@ -360,10 +360,10 @@ CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep)
         // allocate token field
         len = strlen(rep->info.token);
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
+        temp = (char *) OICMalloc(sizeof(char) * (len + 1));
         if (temp == NULL)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            OIC_LOG_V(DEBUG, TAG, "CACloneResponseInfo Out of memory");
 
             CADestroyResponseInfoInternal(clone);
 
@@ -379,7 +379,7 @@ CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep)
     if (rep->info.options != NULL)
     {
         // save the options
-        clone->info.options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t));
+        clone->info.options = (CAHeaderOption_t *) OICMalloc(sizeof(CAHeaderOption_t));
         memset(clone->info.options, 0, sizeof(CAHeaderOption_t));
         memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t));
     }
@@ -389,10 +389,10 @@ CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep)
         // allocate payload field
         len = strlen(rep->info.payload);
 
-        temp = (char*) OICMalloc(sizeof(char) * (len + 1));
+        temp = (char *) OICMalloc(sizeof(char) * (len + 1));
         if (temp == NULL)
         {
-            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            OIC_LOG_V(DEBUG, TAG, "CACloneResponseInfo Out of memory");
 
             CADestroyResponseInfoInternal(clone);
 
@@ -408,7 +408,7 @@ CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep)
     return clone;
 }
 
-void CADestroyRemoteEndpointInternal(CARemoteEndpoint_trep)
+void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t *rep)
 {
     if (rep == NULL)
         return;
@@ -416,14 +416,14 @@ void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t* rep)
     // free uri field
     if (rep->resourceUri != NULL)
     {
-        OICFree((char*) rep->resourceUri);
+        OICFree((char *) rep->resourceUri);
     }
 
     // free remote end point structure.
     OICFree(rep);
 }
 
-void CADestroyRequestInfoInternal(CARequestInfo_trep)
+void CADestroyRequestInfoInternal(CARequestInfo_t *rep)
 {
     if (rep == NULL)
         return;
@@ -431,25 +431,25 @@ void CADestroyRequestInfoInternal(CARequestInfo_t* rep)
     // 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)
     {
-        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);
 }
 
-void CADestroyResponseInfoInternal(CAResponseInfo_trep)
+void CADestroyResponseInfoInternal(CAResponseInfo_t *rep)
 {
     if (rep == NULL)
         return;
@@ -457,19 +457,19 @@ void CADestroyResponseInfoInternal(CAResponseInfo_t* rep)
     // 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)
     {
-        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);
diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/README.txt b/resource/csdk/connectivity/src/ethernet_adapter/arduino/README.txt
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapter.c b/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapter.c
new file mode 100644 (file)
index 0000000..6e482a2
--- /dev/null
@@ -0,0 +1,276 @@
+/******************************************************************
+ *
+ * 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 "caethernetadapter_singlethread.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include "caadapterutils.h"
+#include "logger.h"
+
+#include "caethernetadapterutils.h"
+
+/**
+ * @def ETHERNET_ADAPTER_TAG
+ * @brief Logging tag for module name
+ */
+#define ETHERNET_ADAPTER_TAG "EA"
+
+/**
+ * @def CA_PORT
+ * @brief Port to listen for incoming data
+ */
+#define CA_PORT   5383
+
+#define CA_MCAST_PORT   5683
+
+/**
+ * @def CA_MULTICAST_IP
+ * @brief Multicast IP Address
+ */
+#define CA_MULTICAST_IP "224.0.1.187"
+
+/**
+ * @var gNetworkCallback
+ * @brief Network callback
+ */
+static CANetworkChangeCallback gNetworkCallback = NULL;
+
+/**
+ * @var gIsMulticastServerStarted
+ * @brief Flag to check if multicast server is started
+ */
+static int gIsMulticastServerStarted = 0;
+
+int CAEthernetRegisterNetworkNotifications(CANetworkChangeCallback netCallback)
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+
+    gNetworkCallback = netCallback;
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback,
+                                CANetworkPacketReceivedCallback networkPacketCallback, CANetworkChangeCallback netCallback)
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+    VERIFY_NON_NULL(registerCallback, ETHERNET_ADAPTER_TAG, "registercallback");
+    VERIFY_NON_NULL(networkPacketCallback, ETHERNET_ADAPTER_TAG, "networkpacketcallback");
+    VERIFY_NON_NULL(netCallback, ETHERNET_ADAPTER_TAG, "netcallback");
+
+    CAConnectivityHandler_t ethernetHandler;
+    ethernetHandler.startAdapter = CAStartEthernet;
+    ethernetHandler.startListenServer = CAStartEthernetListeningServer;
+    ethernetHandler.startDiscoverServer = CAStartEthernetDiscoveryServer;
+    ethernetHandler.sendData = CASendEthernetUnicastData;
+    ethernetHandler.sendDataToAll = CASendEthernetMulticastData;
+    ethernetHandler.GetnetInfo = CAGetEthernetInterfaceInformation;
+    ethernetHandler.readData = CAReadEthernetData;
+    ethernetHandler.stopAdapter = CAStopEthernet;
+    ethernetHandler.terminate = CATerminateEthernet;
+    registerCallback(ethernetHandler, CA_ETHERNET);
+
+    CASetEthernetNetworkPacketCallback(networkPacketCallback);
+    CAEthernetRegisterNetworkNotifications(netCallback);
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartEthernet()
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+    int16_t unicastPort = CA_PORT;
+    CAResult_t ret = CA_STATUS_OK;
+
+    /*Address is hardcoded as we are using Single Interface*/
+    ret = CAStartUnicastServer("0.0.0.0", &unicastPort);
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartEthernetListeningServer()
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+
+    CAResult_t ret = CA_STATUS_OK;
+    int16_t multicastPort = CA_MCAST_PORT;
+
+    if (gIsMulticastServerStarted == 1)
+    {
+        OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Already started");
+        return CA_SERVER_STARTED_ALREADY;
+    }
+
+    ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort);
+    if (ret == CA_STATUS_OK)
+    {
+        OIC_LOG(INFO, ETHERNET_ADAPTER_TAG, "success");
+        gIsMulticastServerStarted = 1;
+    }
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartEthernetDiscoveryServer()
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return CAStartEthernetListeningServer();
+}
+
+uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+                                   uint32_t dataLen)
+{
+    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);
+
+    if (dataLen <= 0)
+    {
+        OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "data");
+        return dataSize;
+
+    }
+
+    dataSize = CAEthernetSendData(remoteEndpoint->addressInfo.IP.ipAddress,
+                                  remoteEndpoint->addressInfo.IP.port, data, dataLen, 0);
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return dataSize;
+}
+
+uint32_t CASendEthernetMulticastData(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);
+
+    if (dataLength <= 0)
+    {
+        OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "data");
+        return 0;
+
+    }
+    dataSize = CAEthernetSendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, 1);
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return dataSize;
+}
+
+CAResult_t CAStartEthernetNotifyRecvServers()
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+uint32_t CASendEthernetNotification(const CARemoteEndpoint_t *endpoint, void *data,
+                                    uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(info, ETHERNET_ADAPTER_TAG, "info");
+    char localIpAddress[CA_IPADDR_SIZE];
+    int32_t localIpAddressLen = sizeof(localIpAddress);
+
+    CAArduinoGetInterfaceAddress(localIpAddress, localIpAddressLen);
+    /**
+     * Create local endpoint using util function
+     */
+    (*info) = CAAdapterCreateLocalEndpoint(CA_ETHERNET, localIpAddress, "Ethernet");
+    if (NULL == (*info))
+    {
+        OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "Out of memory");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    (*size) = 1;
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAReadEthernetData()
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+    CAArduoinoCheckServerData();
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopEthernet()
+{
+    CAResult_t result = CA_STATUS_FAILED;
+    result = CAStopUnicastServer();
+    if (result != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "unicast");
+        return result;
+    }
+
+    result = CAStopMulticastServer();
+    if (result != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "multicast");
+        return result;
+    }
+    else
+    {
+        gIsMulticastServerStarted = 0;
+    }
+    return CA_STATUS_OK;
+}
+
+void CATerminateEthernet()
+{
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
+    CAResult_t result = CA_STATUS_FAILED;
+
+    CASetEthernetNetworkPacketCallback(NULL);
+    result = CAEthernetRegisterNetworkNotifications(NULL);
+    if (result != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, ETHERNET_ADAPTER_TAG, "register failed");
+    }
+
+    OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
+    return;
+}
+
diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.cpp b/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.cpp
new file mode 100644 (file)
index 0000000..6883241
--- /dev/null
@@ -0,0 +1,480 @@
+/******************************************************************
+*
+* 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 "caethernetadapterutils.h"
+
+#include <Arduino.h>
+#include <Ethernet.h>
+#include <socket.h>
+#include <w5100.h>
+#include <EthernetUdp.h>
+#include <IPAddress.h>
+#include <TimedAction.h>
+
+#include "logger.h"
+#include "cacommon.h"
+#include "cainterface.h"
+#include "caadapterinterface.h"
+#include "caadapterutils.h"
+#include "oic_malloc.h"
+
+#define COAP_MAX_PDU_SIZE 320
+#define MOD_NAME "EAU"
+
+/// Length of the IP address decimal notation string
+#define IPNAMESIZE (16)
+
+static CANetworkPacketReceivedCallback gNetworkPacketCallback;
+static int32_t gUnicastSocket = 0;
+static int32_t gMulticastSocket = 0;
+static bool gServerRunning = false;
+static TimedAction gRcvAction = TimedAction(3000, CACheckData);
+
+// Retrieves a empty socket and bind it for UDP with the input port
+/**
+ * @brief API to start unicast server.
+ * @param localAddress - Local Unicast IP address to bind the socket.
+ * @param port - Local port number where socket will listen for incoming request.
+ * @return - Error Code
+ */
+CAResult_t CAStartUnicastServer(const char *localAddress, int16_t *port)
+{
+    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, "cant connect:%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, &gUnicastSocket) != CA_STATUS_OK)
+    {
+        OIC_LOG(DEBUG, MOD_NAME, "failed");
+        return CA_STATUS_FAILED;
+    }
+
+    // start thread to monitor socket here
+    if (!gServerRunning)
+    {
+        gRcvAction.enable();
+        gServerRunning = true;
+    }
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+// Retrieves the IP address assigned to Arduino Ethernet shield
+CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    VERIFY_NON_NULL(address, MOD_NAME, "address");
+
+    //TODO : Fix this for scenarios when this API is invoked when device is not connected
+    uint8_t rawIPAddr[4];
+    if (addrLen < IPNAMESIZE)
+    {
+        OIC_LOG(ERROR, MOD_NAME, "Invalid addrLen");
+        return CA_STATUS_FAILED;
+    }
+
+    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);
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAArduinoInitUdpSocket(int16_t *port, int32_t *socketID)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    VERIFY_NON_NULL(socketID, MOD_NAME, "socket");
+    uint8_t state;
+    //Is any socket available to work with ?
+    int32_t 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;
+            break;
+        }
+    }
+
+    if (sockID == 0)
+    {
+        OIC_LOG(ERROR, MOD_NAME, "failed");
+        return CA_STATUS_FAILED;
+    }
+
+    //Create a datagram socket on which to recv/send.
+    if (!socket(sockID, SnMR::UDP, *port, 0))
+    {
+        OIC_LOG(ERROR, MOD_NAME, "failed");
+        return CA_STATUS_FAILED;
+    }
+
+    *socketID = sockID;
+    OIC_LOG_V(DEBUG, MOD_NAME, "socketId:%d", sockID);
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, const int16_t *port,
+        int32_t *socketID)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    VERIFY_NON_NULL(mcastAddress, MOD_NAME, "address");
+    VERIFY_NON_NULL(socketID, MOD_NAME, "socket");
+    VERIFY_NON_NULL(port, 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))
+    {
+        OIC_LOG(ERROR, MOD_NAME, "failed");
+        return CA_STATUS_FAILED;
+    }
+
+    int32_t sockID = 0;
+    //Is any socket available to work with ?
+    sockID = -1;
+    for (int i = 1; i < MAX_SOCK_NUM; i++)
+    {
+        state = W5100.readSnSR(i);
+        if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT)
+        {
+            sockID = i;
+            break;
+        }
+    }
+
+    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, *port);
+
+    //Create a datagram socket on which to recv/send.
+    if (!socket(sockID, SnMR::UDP, *port, SnMR::MULTI))
+    {
+        OIC_LOG(ERROR, MOD_NAME, "failed");
+        return CA_STATUS_FAILED;
+    }
+
+    *socketID = sockID;
+    OIC_LOG_V(DEBUG, MOD_NAME, "socketId:%d", sockID);
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+/**
+ * @brief API to start multicast server.
+ * @param mcastAddress - IP address to join multicast group.
+ * @param localAddress - Local Unicast IP address to bind the socket.
+ * @param port - multicast port number where socket will listen for incoming request.
+ * @return - Error Code
+ */
+CAResult_t CAStartMulticastServer(const char *mcastAddress, const char *localAddress,
+                                  const int16_t *port)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    if (CAArduinoInitMulticastUdpSocket(mcastAddress, port, &gMulticastSocket) != CA_STATUS_OK)
+    {
+        OIC_LOG(DEBUG, MOD_NAME, "failed");
+        return CA_STATUS_FAILED;
+    }
+
+    // start thread to monitor socket here
+    if (!gServerRunning)
+    {
+        gRcvAction.enable();
+        gServerRunning = true;
+    }
+
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopUnicastServer()
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    // terminate server thread
+    // Stop thread if both server stopped
+    if (gMulticastSocket == 0)
+    {
+        gRcvAction.disable();
+        gServerRunning = false;
+    }
+
+    close(gUnicastSocket);
+    gUnicastSocket = 0;
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAArduoinoCheckServerData()
+{
+    gRcvAction.check();
+}
+
+CAResult_t CAStopMulticastServer()
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    // terminate server thread
+    // Stop thread if both server stopped
+    if (gUnicastSocket == 0)
+    {
+        gRcvAction.disable();
+        gServerRunning = false;
+    }
+
+    close(gMulticastSocket);
+    gMulticastSocket = 0;
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+uint32_t CAEthernetSendData(const char *remoteIpAddress, const int16_t port, const char *buf,
+                            uint32_t bufLen,
+                            int16_t isMulticast)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    int32_t socketID = 0;
+    if (isMulticast)
+    {
+        if (CAArduinoInitMulticastUdpSocket(remoteIpAddress, &port, &socketID) != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, MOD_NAME, "multicast");
+            return 0;
+        }
+    }
+    else
+    {
+        if (CAArduinoInitUdpSocket((int16_t *)&port, &socketID) != CA_STATUS_OK)
+        {
+            OIC_LOG(ERROR, MOD_NAME, "unicast");
+            return 0;
+        }
+    }
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CAArduinoSendData(socketID, (uint8_t *)buf, bufLen, remoteIpAddress, port);
+}
+
+/// Send data to requested end-point using UDP socket
+uint32_t CAArduinoSendData(int32_t sockFd, const uint8_t *buf, uint32_t bufLen,
+                           const char *ipAddress,
+                           int32_t port)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    uint32_t ret;
+    VERIFY_NON_NULL_RET(buf, MOD_NAME, "buffer", 0);
+    VERIFY_NON_NULL_RET(ipAddress, MOD_NAME, "address", 0);
+
+    uint8_t ipAddr[4] = { 0 };
+    uint16_t parsedPort = 0;
+    if (!CAParseIPv4AddressLocal((unsigned char *) ipAddress, ipAddr, &parsedPort))
+    {
+        OIC_LOG(ERROR, MOD_NAME, "failed");
+        return 0;
+    }
+
+    ret = sendto(sockFd, buf, bufLen, (uint8_t *)ipAddr, port);
+    delay(10);
+    close(sockFd);
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return ret;
+}
+
+void CACheckData()
+{
+    void *data = OICMalloc(COAP_MAX_PDU_SIZE);
+    memset(data, 0, COAP_MAX_PDU_SIZE);
+    int32_t dataLen = 0;
+    uint8_t senderAddr[4] = { 0 };
+    char addr[IPNAMESIZE] = {0};
+    uint16_t senderPort = 0;
+
+    if (gUnicastSocket)
+    {
+        dataLen = CAArduinoRecvData(gUnicastSocket, (uint8_t *)data, COAP_MAX_PDU_SIZE, senderAddr,
+                                    &senderPort);
+        if (dataLen < 0)
+        {
+            OIC_LOG(ERROR, MOD_NAME, "unicast");
+            CAStopUnicastServer();
+        }
+        else if (dataLen > 0)
+        {
+            OIC_LOG(DEBUG, MOD_NAME, "unicast data rcvd");
+            sprintf(addr, "%d.%d.%d.%d", senderAddr[0], senderAddr[1], senderAddr[2], senderAddr[3]);
+            CANotifyCallback(data, dataLen, addr, senderPort);
+        }
+    }
+
+    if (gMulticastSocket)
+    {
+        dataLen = CAArduinoRecvData(gMulticastSocket, (uint8_t *)data, COAP_MAX_PDU_SIZE, senderAddr,
+                                    &senderPort);
+        if (dataLen < 0)
+        {
+            OIC_LOG(ERROR, MOD_NAME, "multicast");
+            CAStopMulticastServer();
+        }
+        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]);
+            CANotifyCallback(data, dataLen, addr, senderPort);
+        }
+    }
+    OICFree(data);
+}
+
+void CANotifyCallback(void *data, int32_t dataLen, const char *senderIp, int32_t senderPort)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    if (gNetworkPacketCallback)
+    {
+        CARemoteEndpoint_t endPoint;
+        endPoint.resourceUri = NULL;     // will be filled by upper layer
+        endPoint.connectivityType = CA_ETHERNET;
+        strncpy(endPoint.addressInfo.IP.ipAddress, senderIp, strlen(senderIp));
+        endPoint.addressInfo.IP.port = senderPort;
+        gNetworkPacketCallback(&endPoint, data, dataLen);
+    }
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+}
+
+/// 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)
+{
+    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_RET(buf, MOD_NAME, "buffer", 0);
+    VERIFY_NON_NULL_RET(senderAddr, MOD_NAME, "address", 0);
+    VERIFY_NON_NULL_RET(senderPort, MOD_NAME, "port", 0);
+    int32_t ret = 0;
+    uint16_t recvLen = W5100.getRXReceivedSize(sockFd);
+    if (recvLen == 0)
+    {
+        OIC_LOG_V(DEBUG, MOD_NAME, "rcvd %d", recvLen);
+        return recvLen;
+    }
+
+    // Read available data.
+    ret = recvfrom(sockFd, buf, bufLen, senderAddr, senderPort);
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return ret;
+}
+
+void CASetEthernetNetworkPacketCallback(CANetworkPacketReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    gNetworkPacketCallback = callback;
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+}
+
+int16_t CAParseIPv4AddressLocal(unsigned char *ipAddrStr, uint8_t *ipAddr, uint16_t *port)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    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;
+    }
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return 0;
+}
diff --git a/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.h b/resource/csdk/connectivity/src/ethernet_adapter/arduino/caethernetadapterutils.h
new file mode 100644 (file)
index 0000000..f5fccc9
--- /dev/null
@@ -0,0 +1,83 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+#ifndef _ETHERNET_ADAPTER_ARDUINO_H_
+#define _ETHERNET_ADAPTER_ARDUINO_H_
+
+#include "caadapterinterface.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAResult_t CAStartUnicastServer(const char *localAddress, int16_t *port);
+
+// Retrieves the IP address assigned to Arduino Ethernet shield
+CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen);
+
+CAResult_t CAArduinoInitUdpSocket(int16_t *port, int32_t *socketID);
+
+CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, int16_t *port,
+        int32_t *socketID);
+
+/**
+ * @brief API to start multicast server.
+ * @param mcastAddress - IP address to join multicast group.
+ * @param localAddress - Local Unicast IP address to bind the socket.
+ * @param port - multicast port number where socket will listen for incoming request.
+ * @return - Error Code
+ */
+CAResult_t CAStartMulticastServer(const char *mcastAddress, const char *localAddress,
+                                  const int16_t *port);
+
+CAResult_t CAStopUnicastServer();
+
+void CAArduoinoCheckServerData();
+
+CAResult_t CAStopMulticastServer();
+
+uint32_t CAEthernetSendData(const char *remoteIpAddress, const int16_t port, const char *buf,
+                            uint32_t bufLen,
+                            int16_t isMulticast);
+
+/// Send data to requested end-point using UDP socket
+uint32_t CAArduinoSendData(int32_t sockFd, const uint8_t *buf, uint32_t bufLen,
+                           const char *ipAddress,
+                           int32_t port);
+
+void CACheckData();
+
+void CANotifyCallback(void *data, int32_t dataLen, const char *senderIp, int32_t senderPort);
+
+/// 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);
+
+void CASetEthernetNetworkPacketCallback(CANetworkPacketReceivedCallback callback);
+
+int16_t CAParseIPv4AddressLocal(unsigned char *ipAddrStr, uint8_t *ipAddr, uint16_t *port);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif
+
+
index 7e90a34..ff6e1c1 100644 (file)
 static CANetworkPacketReceivedCallback gEthernetReceivedCallback = NULL;
 static u_thread_pool_t gThreadPoolHandle = NULL;
 
-static void CAEthernetPacketReceiveCallback(const char* address, const char* data)
+static void CAEthernetPacketReceiveCallback(char* address, const char* data)
 {
-    OIC_LOG_V(DEBUG, TAG, "CAethernetPacketReceiveCallback, from: %s, data: %s", address, data);
+    OIC_LOG_V(DEBUG, TAG,
+            "CAethernetPacketReceiveCallback, from: %s, data: %s", address, data);
 
     // call the callback
     if (gEthernetReceivedCallback != NULL)
@@ -47,11 +48,10 @@ static void CAEthernetPacketReceiveCallback(const char* address, const char* dat
 
         // set address
         memset((void*) endpoint->addressInfo.IP.ipAddress, 0, CA_IPADDR_SIZE);
-        if (CA_IPADDR_SIZE > strlen(address))
-        {
+        if (CA_IPADDR_SIZE > strlen(address)) {
             strcpy((char*) endpoint->addressInfo.IP.ipAddress, address);
         }
-        free(address);
+        OICFree(address);
 
         // set connectivity type
         endpoint->connectivityType = CA_ETHERNET;
@@ -78,8 +78,6 @@ CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback,
     handler.startDiscoverServer = CAStartEthernetDiscoveryServer;
     handler.sendData = CASendEthernetUnicastData;
     handler.sendDataToAll = CASendEthernetMulticastData;
-    handler.startNotifyServer = CAStartEthernetNotifyRecvServers;
-    handler.sendNotification = CASendEthernetNotification;
     handler.GetnetInfo = CAGetEthernetInterfaceInformation;
     handler.readData = CAReadEthernetData;
     handler.stopAdapter = CAStopEthernet;
@@ -165,30 +163,11 @@ uint32_t CASendEthernetMulticastData(void* data, uint32_t dataLen)
     return 0;
 }
 
-CAResult_t CAStartEthernetNotifyRecvServers()
-{
-    OIC_LOG(DEBUG, TAG, "StartEthernetNotifyRecvServers");
-
-    // ToDo:
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendEthernetNotification(const CARemoteEndpoint_t* endpoint, void* data,
-        uint32_t dataLen)
-{
-    OIC_LOG(DEBUG, TAG, "SendEthernetNotification");
-
-    // ToDo:
-
-    return 0;
-}
-
 CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivity_t** info, uint32_t* size)
 {
     OIC_LOG(DEBUG, TAG, "GetEthernetInterfaceInformation");
 
-    // ToDo:
+    CAGetEthernetInterfaceInfo(info, size);
 
     return CA_STATUS_OK;
 }
index 394674f..1151663 100644 (file)
@@ -10,6 +10,8 @@
 #include <netinet/in.h>
 #include <string.h>
 #include <arpa/inet.h>
+#include <sys/ioctl.h>
+#include <net/if.h>
 
 #include "caethernetcore.h"
 #include "logger.h"
@@ -20,6 +22,7 @@
 
 #define TAG PCF("CA")
 
+#define REQ_CNT 20
 #define CA_MAX_BUFFER_SIZE 512  // Max length of buffer
 #define CA_UNICAST_PORT 5383 // The port on which to listen for incoming data
 #define CA_MULTICAST_ADDR "224.0.1.187"
@@ -128,8 +131,7 @@ static void CAUnicastListenThread(void* threadData)
 
         // print details of the client/peer and the data received
         OIC_LOG_V(DEBUG, TAG, "CAUnicastListenThread, Received packet from %s:%d",
-                inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
-        OIC_LOG_V(DEBUG, TAG, "CAUnicastListenThread, Data: %s", buf);
+                inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));OIC_LOG_V(DEBUG, TAG, "CAUnicastListenThread, Data: %s", buf);
 
         // store the data at queue.
         CAThreadData_t* td = NULL;
@@ -219,7 +221,6 @@ static void CAMulticastListenThread(void* threadData)
 
     OIC_LOG(DEBUG, TAG, "end of CAMulticastListenThread");
 }
-
 void CAEthernetInitialize(u_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, TAG, "CAEthernetInitialize");
@@ -246,7 +247,7 @@ void CAEthernetInitialize(u_thread_pool_t handle)
     if (res != CA_STATUS_OK)
     {
         OIC_LOG(DEBUG, TAG, "thread start is error (receive thread)");
-        // return res;
+
         return;
     }
 
@@ -267,7 +268,6 @@ void CAEthernetInitialize(u_thread_pool_t handle)
     if ((unicast_receive_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
     {
         OIC_LOG_V(DEBUG, TAG, "CAEthernetInit, creating socket failed");
-
         return;
     }
 
@@ -386,7 +386,7 @@ void CAEthernetTerminate()
 
 }
 
-int32_t CAEthernetSendUnicastMessage(const char* address, const char* data, int lengh)
+int32_t CAEthernetSendUnicastMessage(const char* address, char* data, int lengh)
 {
     // store the data at queue.
     CAThreadData_t* td = NULL;
@@ -419,7 +419,7 @@ int32_t CAEthernetSendUnicastMessage(const char* address, const char* data, int
     return 0;
 }
 
-int32_t CAEthernetSendMulticastMessage(const char* m_address, const char* data)
+int32_t CAEthernetSendMulticastMessage(const char* m_address, char* data)
 {
     // store the data at queue.
     CAThreadData_t* td = NULL;
@@ -620,3 +620,86 @@ int32_t CAEthernetSendMulticastMessageImpl(const char* msg)
 
     return 0;
 }
+
+CAResult_t CAGetEthernetInterfaceInfo(CALocalConnectivity_t **info, uint32_t* size)
+{
+    uint32_t cnt, req_cnt = REQ_CNT;
+    int32_t fd;
+    uint32_t cmd = SIOCGIFCONF;
+    uint32_t resSize = 0;
+    char* localIPAddress;
+    struct sockaddr_in *sock;
+    struct ifconf ifc;
+    struct ifreq *ifr;
+
+    memset((void *) &ifc, 0, sizeof(struct ifconf));
+    ifc.ifc_len = sizeof(struct ifconf) * req_cnt;
+    ifc.ifc_buf = NULL;
+    ifc.ifc_buf = malloc(ifc.ifc_len);
+
+    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
+    {
+        OIC_LOG(DEBUG, TAG, "create socket error!");
+        return CA_STATUS_FAILED;
+    }
+
+    if (ioctl(fd, cmd, &ifc) < 0)
+    {
+        OIC_LOG(DEBUG, TAG, "SIOCGIFCONF fail");
+        close(fd);
+        return CA_STATUS_FAILED;
+    }
+
+    close(fd);
+
+    if (ifc.ifc_len > (sizeof(struct ifreq) * req_cnt))
+    {
+        req_cnt = ifc.ifc_len;
+        ifc.ifc_buf = realloc(ifc.ifc_buf, req_cnt);
+    }
+
+    ifr = ifc.ifc_req;
+    for (cnt = 0; cnt < ifc.ifc_len; cnt += sizeof(struct ifreq), ifr++)
+    {
+        sock = (struct sockaddr_in *) &ifr->ifr_addr;
+
+        // except loopback address
+        if (ntohl(sock->sin_addr.s_addr) == INADDR_LOOPBACK)
+            continue;
+
+        // get local address
+        localIPAddress = inet_ntoa(sock->sin_addr);
+
+        CALocalConnectivity_t* localInfo;
+
+        // memory allocation
+        localInfo = (CALocalConnectivity_t*) OICMalloc(sizeof(CALocalConnectivity_t));
+        if (localInfo == NULL)
+        {
+            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            free(localInfo);
+            return CA_STATUS_FAILED;
+        }
+        memset(localInfo, 0, sizeof(CALocalConnectivity_t));
+
+        if (strlen(localIPAddress) > CA_IPADDR_SIZE)
+        {
+            OIC_LOG_V(DEBUG, TAG, "address size is wrong!!");
+            free(localInfo);
+            return CA_STATUS_FAILED;
+        }
+        // set local ip address
+        strncpy(localInfo->addressInfo.IP.ipAddress, localIPAddress, strlen(localIPAddress));
+
+        // set network type
+        localInfo->type = CA_ETHERNET;
+
+        *info = localInfo;
+
+        resSize++;
+    }
+
+    *size = resSize;
+
+    return CA_STATUS_OK;
+}
diff --git a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapter.c b/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapter.c
new file mode 100644 (file)
index 0000000..3eac4a2
--- /dev/null
@@ -0,0 +1,294 @@
+/******************************************************************
+ *
+ * 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 "cawifiadapter_singlethread.h"
+
+#include <stdio.h>
+#include <stdint.h>
+#include "caadapterutils.h"
+#include "logger.h"
+
+#include "cawifiadapterutils.h"
+
+/**
+ * @def WIFI_ETHERNET_ADAPTER_TAG
+ * @brief Logging tag for module name
+ */
+#define WIFI_ADAPTER_TAG "WIFIADAP"
+
+/**
+ * @def CA_PORT
+ * @brief Port to listen for incoming data
+ */
+#define CA_PORT   5383
+
+#define CA_MCAST_PORT   5683
+
+/**
+ * @def CA_MULTICAST_IP
+ * @brief Multicast IP Address
+ */
+#define CA_MULTICAST_IP "224.0.1.187"
+
+/**
+ * @var gNetworkCallback
+ * @brief Network callback
+ */
+static CANetworkChangeCallback gNetworkCallback = NULL;
+
+/**
+ * @var gIsMulticastServerStarted
+ * @brief Flag to check if multicast server is started
+ */
+static bool gIsMulticastServerStarted = false;
+
+CAResult_t CAWIFIRegisterNetworkNotifications(CANetworkChangeCallback netCallback)
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+    gNetworkCallback = netCallback;
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
+                            CANetworkPacketReceivedCallback networkPacketCallback, CANetworkChangeCallback netCallback)
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+    VERIFY_NON_NULL(registerCallback, WIFI_ADAPTER_TAG, "registerCallback");
+    VERIFY_NON_NULL(networkPacketCallback, WIFI_ADAPTER_TAG, "networkPacketCallback");
+    VERIFY_NON_NULL(netCallback, WIFI_ADAPTER_TAG, "netCallback");
+
+    CAConnectivityHandler_t wifiHandler;
+    wifiHandler.startAdapter = CAStartWIFI;
+    wifiHandler.startListenServer = CAStartWIFIListeningServer;
+    wifiHandler.startDiscoverServer = CAStartWIFIDiscoveryServer;
+    wifiHandler.sendData = CASendWIFIUnicastData;
+    wifiHandler.sendDataToAll = CASendWIFIMulticastData;
+    wifiHandler.GetnetInfo = CAGetWIFIInterfaceInformation;
+    wifiHandler.readData = CAReadWIFIData;
+    wifiHandler.stopAdapter = CAStopWIFI;
+    wifiHandler.terminate = CATerminateWIfI;
+    registerCallback(wifiHandler, CA_WIFI);
+
+    CASetWIFINetworkPacketCallback(networkPacketCallback);
+    CAWIFIRegisterNetworkNotifications(netCallback);
+
+    OIC_LOG(INFO, WIFI_ADAPTER_TAG, "IntializeWifi is Success");
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartWIFI()
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+    int16_t unicastPort = CA_PORT;
+    CAResult_t ret = CA_STATUS_OK;
+
+    /*Address is hardcoded as we are using Single Interface*/
+    ret = CAStartUnicastServer("0.0.0.0", &unicastPort);
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartWIFIListeningServer()
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+    CAResult_t ret = CA_STATUS_OK;
+    int16_t multicastPort = CA_MCAST_PORT;
+
+    if (gIsMulticastServerStarted == true)
+    {
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Server is already Started");
+        return CA_SERVER_STARTED_ALREADY;
+    }
+
+    ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort);
+    if (ret == CA_STATUS_OK)
+    {
+        OIC_LOG(INFO, WIFI_ADAPTER_TAG, "Multicast Server is Started Successfully");
+        gIsMulticastServerStarted = true;
+    }
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return ret;
+}
+
+CAResult_t CAStartWIFIDiscoveryServer()
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+    CAResult_t ret = CA_STATUS_OK;
+    int16_t multicastPort = CA_MCAST_PORT;
+
+    if (gIsMulticastServerStarted == true)
+    {
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Server is already Started");
+        return CA_SERVER_STARTED_ALREADY;
+    }
+
+    ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort);
+    if (ret == CA_STATUS_OK)
+    {
+        OIC_LOG(INFO, WIFI_ADAPTER_TAG, "Multicast Server is Started Successfully");
+        gIsMulticastServerStarted = true;
+    }
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return ret;
+}
+
+uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
+                               uint32_t dataLen)
+{
+    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);
+
+    if (dataLen == 0)
+    {
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "DataLen is 0");
+        return dataSize;
+
+    }
+
+    dataSize = CAWIFISendData(remoteEndpoint->addressInfo.IP.ipAddress,
+                              remoteEndpoint->addressInfo.IP.port, data, dataLen, 0);
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return dataSize;
+}
+
+uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLength)
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+    VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "data", 0);
+
+    uint32_t dataSize = 0;
+    if (dataLength == 0)
+    {
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "DataLen is 0");
+        return 0;
+
+    }
+    dataSize = CAWIFISendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, 1);
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return dataSize;
+}
+
+CAResult_t CAStartWIFINotifyRecvServers()
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+uint32_t CASendWIFINotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+    VERIFY_NON_NULL(info, WIFI_ADAPTER_TAG, "info");
+    char localIpAddress[CA_IPADDR_SIZE];
+    int32_t localIpAddressLen = sizeof(localIpAddress);
+
+    CAArduinoGetInterfaceAddress(localIpAddress, localIpAddressLen);
+    /**
+     * Create local endpoint using util function
+     */
+    (*info) = CAAdapterCreateLocalEndpoint(CA_WIFI, localIpAddress, "WiFi");
+    if (NULL == (*info))
+    {
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Out of memory");
+        return CA_MEMORY_ALLOC_FAILED;
+    }
+
+    (*size) = 1;
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAReadWIFIData()
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+    CAArduoinoCheckServerData();
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStopWIFI()
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+    CAResult_t result = CA_STATUS_FAILED;
+    result = CAStopUnicastServer();
+    if (result != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Error");
+        return result;
+    }
+
+    result = CAStopMulticastServer();
+    if (result != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Error");
+        return result;
+    }
+    else
+    {
+        gIsMulticastServerStarted = false;
+    }
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CATerminateWIfI()
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+    CASetWIFINetworkPacketCallback(NULL);
+    CAResult_t result = CAWIFIRegisterNetworkNotifications(NULL);
+    if (result != CA_STATUS_OK)
+    {
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Error");
+    }
+
+    OIC_LOG(INFO, WIFI_ADAPTER_TAG, "TerminateWifi Success");
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return;
+}
diff --git a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapterutils.cpp b/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapterutils.cpp
new file mode 100644 (file)
index 0000000..7025dd1
--- /dev/null
@@ -0,0 +1,365 @@
+/******************************************************************
+*
+* 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 "cawifiadapterutils.h"
+
+#include <Arduino.h>
+#include <WiFi.h>
+#include <SPI.h>
+#include <utility/server_drv.h>
+#include <utility/wifi_drv.h>
+#include <IPAddress.h>
+#include <TimedAction.h>
+
+#include "logger.h"
+#include "cacommon.h"
+#include "cainterface.h"
+#include "caadapterinterface.h"
+#include "caadapterutils.h"
+#include "oic_malloc.h"
+
+#define COAP_MAX_PDU_SIZE 320
+#define MOD_NAME "WAU"
+
+char ssid[] = "network_ssid";     //  your network SSID (name)
+char pass[] = "network_pswd";  // 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)
+/// This is the max buffer size between Arduino and WiFi Shield
+#define ARDUINO_WIFI_SPI_RECV_BUFFERSIZE (64)
+
+// Start offsets based on end of received data buffer
+#define WIFI_RECBUF_IPADDR_OFFSET  (6)
+#define WIFI_RECBUF_PORT_OFFSET    (2)
+
+#define WIFI_RECBUF_IPADDR_SIZE    (WIFI_RECBUF_IPADDR_OFFSET - WIFI_RECBUF_PORT_OFFSET)
+#define WIFI_RECBUF_PORT_SIZE      (WIFI_RECBUF_PORT_OFFSET - 0)
+#define WIFI_RECBUF_FOOTER_SIZE    (WIFI_RECBUF_IPADDR_SIZE + WIFI_RECBUF_PORT_SIZE)
+
+static CANetworkPacketReceivedCallback gNetworkPacketCallback;
+static int32_t gUnicastSocket = 0;
+static bool gServerRunning = false;
+static TimedAction gRcvAction = TimedAction(3000, CACheckData);
+static WiFiUDP Udp;
+
+CAResult_t CAArduinoInitUdpSocket(const int16_t *port, int32_t *socketID)
+{
+    uint8_t sock;
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    VERIFY_NON_NULL(port, MOD_NAME, "port");
+    VERIFY_NON_NULL(socketID, MOD_NAME, "socket");
+
+    //Is any socket available to work with ?
+    *socketID = -1;
+
+    sock = WiFiClass::getSocket();
+    if (sock != NO_SOCKET_AVAIL)
+    {
+        *socketID = (int32_t)sock;
+        OIC_LOG_V(ERROR, MOD_NAME, "Set SOCKETID=%d", *socketID);
+    }
+    else
+    {
+        OIC_LOG(DEBUG, MOD_NAME, "Error");
+        return CA_STATUS_FAILED;
+    }
+
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartUnicastServer(const char *localAddress, const int16_t *port)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    VERIFY_NON_NULL(port, MOD_NAME, "port");
+
+    // WiFiClass WiFi;
+    if (WiFi.status() == WL_NO_SHIELD)
+    {
+        OIC_LOG(DEBUG, MOD_NAME, "Error");
+        return CA_STATUS_FAILED;
+    }
+
+    while (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);
+    }
+
+    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((unsigned int16_t)*port);
+
+    // start thread to monitor socket here
+    if (!gServerRunning)
+    {
+        gRcvAction.enable();
+        gServerRunning = true;
+    }
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+/// Retrieves the IP address assigned to Arduino Ethernet shield
+CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    VERIFY_NON_NULL(address, MOD_NAME, "address");
+    if (addrLen < IPNAMESIZE)
+    {
+        OIC_LOG_V(ERROR, MOD_NAME, "min addrLen %d", IPNAMESIZE);
+        return CA_STATUS_FAILED;
+    }
+
+    IPAddress ip = WiFi.localIP();
+    sprintf(address, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+
+    OIC_LOG_V(DEBUG, MOD_NAME, "address: %s", address);
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+CAResult_t CAStartMulticastServer(const char *mcastAddress, const char *localAddress, int16_t *port)
+{
+    // wifi shield do not support multicast
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    if (gServerRunning)
+    {
+        // already running
+        OIC_LOG(DEBUG, MOD_NAME, "failed");
+        return CA_STATUS_FAILED;
+    }
+    return CAStartUnicastServer(localAddress, port);
+}
+
+CAResult_t CAStopUnicastServer()
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    if (gUnicastSocket >= MAX_SOCK_NUM)
+    {
+        OIC_LOG(DEBUG, MOD_NAME, "Invalid sockfd");
+        return CA_STATUS_FAILED;
+    }
+
+    ServerDrv::stopClient(gUnicastSocket);
+    WiFiClass::_server_port[gUnicastSocket] = 0;
+    WiFiClass::_state[gUnicastSocket] = NA_STATE;
+    gUnicastSocket = 0;
+
+    // Terminate server thread
+    gRcvAction.disable();
+    gServerRunning = false;
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return CA_STATUS_OK;
+}
+
+void CAArduoinoCheckServerData()
+{
+    gRcvAction.check();
+}
+
+CAResult_t CAStopMulticastServer()
+{
+    return CAStopUnicastServer();
+}
+
+uint32_t CAWIFISendData(const char *remoteIpAddress, const int16_t port, const char *buf,
+                        uint32_t bufLen,
+                        int16_t isMulticast)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    int32_t ret = 1;
+    OIC_LOG_V(DEBUG, MOD_NAME, "remoteip: %s, port: %d", remoteIpAddress, port);
+    Udp.beginPacket(remoteIpAddress, port);
+    ret = (int32_t)Udp.write((char *)buf);
+    Udp.endPacket();
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return ret;
+}
+
+void CACheckData()
+{
+    char *data = (char *)OICMalloc(COAP_MAX_PDU_SIZE);
+    int32_t dataLen = 0;
+    char addr[IPNAMESIZE] = {0};
+    uint16_t senderPort = 0;
+    int16_t packetSize = Udp.parsePacket();
+    OIC_LOG_V(DEBUG, MOD_NAME, "Rcv packet of size:%d ", packetSize);
+    if (packetSize)
+    {
+        IPAddress remoteIp = Udp.remoteIP();
+        senderPort = Udp.remotePort();
+        sprintf(addr, "%d.%d.%d.%d", remoteIp[0], remoteIp[1], remoteIp[2], remoteIp[3]);
+        OIC_LOG_V(DEBUG, MOD_NAME, "remoteip: %s, port: %d", addr, senderPort);
+        // read the packet into packetBufffer
+        int16_t len = Udp.read(data, COAP_MAX_PDU_SIZE);
+        if (len > 0)
+        {
+            data[len] = 0;
+        }
+        CANotifyCallback(data, len, addr, senderPort);
+    }
+    OICFree(data);
+}
+
+void CANotifyCallback(void *data, int32_t dataLen, char *senderIp, int32_t senderPort)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    if (gNetworkPacketCallback)
+    {
+        CARemoteEndpoint_t endPoint;
+        endPoint.resourceUri = NULL;     // will be filled by upper layer
+        endPoint.connectivityType = CA_WIFI;
+        strncpy(endPoint.addressInfo.IP.ipAddress, senderIp, strlen(senderIp));
+        endPoint.addressInfo.IP.port = senderPort;
+        gNetworkPacketCallback(&endPoint, data, dataLen);
+    }
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+}
+
+/// 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)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    VERIFY_NON_NULL(buf, MOD_NAME, "buf");
+    VERIFY_NON_NULL(senderAddr, MOD_NAME, "senderAddr");
+    VERIFY_NON_NULL(senderPort, MOD_NAME, "senderPort");
+
+    uint16_t recvLen = 0;
+    if (sockFd >= MAX_SOCK_NUM)
+    {
+        OIC_LOG(ERROR, MOD_NAME, "Invalid sockfd");
+        return -1;
+    }
+
+    recvLen = (int32_t)ServerDrv::availData((uint8_t)sockFd);
+    if (recvLen == 0)
+    {
+        return recvLen;
+    }
+
+    // Make sure buf is large enough for received data
+    if ((uint32_t)recvLen > bufLen)
+    {
+        OIC_LOG(ERROR, MOD_NAME, "Receive buffer too small");
+        return -1;
+    }
+
+    if (!ServerDrv::getDataBuf((uint8_t)sockFd, (uint8_t *)buf, &recvLen))
+    {
+        OIC_LOG(ERROR, MOD_NAME, "getDataBuf error");
+        return -1;
+    }
+
+    // Read IP Address and Port from end of receive buffer
+    memcpy(senderAddr, &buf[recvLen - WIFI_RECBUF_IPADDR_OFFSET], WIFI_RECBUF_IPADDR_SIZE);
+    // Change the endianness of the port number
+    *((uint8_t *)senderPort) = buf[recvLen - (WIFI_RECBUF_PORT_OFFSET - 1)];
+    *((uint8_t *)senderPort + 1) = buf[recvLen - (WIFI_RECBUF_PORT_OFFSET)];
+
+    recvLen -= WIFI_RECBUF_FOOTER_SIZE;
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+    return (int32_t)recvLen;
+}
+
+
+void CASetWIFINetworkPacketCallback(CANetworkPacketReceivedCallback callback)
+{
+    OIC_LOG(DEBUG, MOD_NAME, "IN");
+    gNetworkPacketCallback = callback;
+    OIC_LOG(DEBUG, MOD_NAME, "OUT");
+}
+
+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;
+}
diff --git a/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapterutils.h b/resource/csdk/connectivity/src/wifi_adapter/arduino/cawifiadapterutils.h
new file mode 100644 (file)
index 0000000..934ff24
--- /dev/null
@@ -0,0 +1,109 @@
+/******************************************************************
+*
+* 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.
+*
+******************************************************************/
+
+#ifndef _WIFI_ADAPTER_ARDUINO_H_
+#define _WIFI_ADAPTER_ARDUINO_H_
+
+#include "caadapterinterface.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CAResult_t CAStartUnicastServer(const char *localAddress, const int16_t *port);
+
+// Retrieves the IP address assigned to Arduino Ethernet shield
+CAResult_t CAArduinoGetInterfaceAddress(char *address, int32_t addrLen);
+
+CAResult_t CAArduinoInitUdpSocket(const int16_t *port, int32_t *socketID);
+
+CAResult_t CAArduinoInitMulticastUdpSocket(const char *mcastAddress, const int16_t *port,
+        int32_t *socketID);
+
+/**
+ * @brief API to start multicast server.
+ * @param mcastAddress - IP address to join multicast group.
+ * @param localAddress - Local Unicast IP address to bind the socket.
+ * @param port - multicast port number where socket will listen for incoming request.
+ * @return - Error Code
+ */
+CAResult_t CAStartMulticastServer(const char *mcastAddress, const char *localAddress,
+                                  int16_t *port);
+
+CAResult_t CAStopUnicastServer();
+
+void CAArduoinoCheckServerData();
+
+CAResult_t CAStopMulticastServer();
+
+/**
+ * @brief API to send data.
+ * @param remoteIpAddress - IP address to send wifi data.
+ * @param port - port on which remote device will be listening for data.
+ * @param buf - data buffer to be sent.
+ * @param bufLen - Length of buffer.
+ * @param isMulticast - flag to check if it's a multicast send.
+ * @return - Error Code
+ */
+uint32_t CAWIFISendData(const char *remoteIpAddress, const int16_t port, const char *buf,
+                        uint32_t bufLen,
+                        int16_t isMulticast);
+
+/// Send data to requested end-point using UDP socket
+/**
+ * @brief API to arduino send data.
+ * @param sockFd - socket ID.
+ * @param buf - data buffer to be sent.
+ * @param bufLen - Length of buffer.
+ * @param ipAddress - Ip of remote device.
+ * @param port - Port of remote device.
+ * @return - Error Code
+ */
+uint32_t CAArduinoSendData(int32_t sockFd, const uint8_t *buf, uint32_t bufLen,
+                           const char *ipAddress,
+                           int32_t port);
+
+void CACheckData();
+
+void CANotifyCallback(void *data, int32_t dataLen, char *senderIp, int32_t senderPort);
+
+/// Retrieve any available data from UDP socket. This is a non-blocking call.
+/**
+ * @brief API to arduino receive data.
+ * @param sockFd - socket ID.
+ * @param buf - data buffer to read.
+ * @param bufLen - Length of buffer.
+ * @param senderAddr - Ip of remote device.
+ * @param senderPort - Port of remote device.
+ * @return - Error Code
+ */
+int32_t CAArduinoRecvData(int32_t sockFd, uint8_t *buf, uint32_t bufLen, uint8_t *senderAddr,
+                          uint16_t *senderPort);
+
+void CASetWIFINetworkPacketCallback(CANetworkPacketReceivedCallback callback);
+
+int16_t CAParseIPv4AddressLocal(unsigned char *ipAddrStr, uint8_t *ipAddr, uint16_t *port);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif
+
index 7ddf382..20be707 100644 (file)
 static CANetworkPacketReceivedCallback gWifiReceivedCallback = NULL;
 static u_thread_pool_t gThreadPoolHandle = NULL;
 
-static void CAWiFiPacketReceiveCallback(char* address, const char* data)
+static void CAWiFiPacketReceiveCallback(char* address, const int port, const char* data)
 {
     OIC_LOG_V(DEBUG, TAG,
-            "CAWiFiPacketReceiveCallback, from: %s, data: %s", address, data);
+            "CAWiFiPacketReceiveCallback, from: %s:%d, data: %s", address, port, data);
 
     // call the callback
     if (gWifiReceivedCallback != NULL)
@@ -48,11 +48,15 @@ static void CAWiFiPacketReceiveCallback(char* address, const char* data)
 
         // set address
         memset((void*) endpoint->addressInfo.IP.ipAddress, 0, CA_IPADDR_SIZE);
-        if (CA_IPADDR_SIZE > strlen(address)) {
+        if (CA_IPADDR_SIZE > strlen(address))
+        {
             strcpy((char*) endpoint->addressInfo.IP.ipAddress, address);
         }
         OICFree(address);
 
+        // set port
+        endpoint->addressInfo.IP.port = port;
+
         // set connectivity type
         endpoint->connectivityType = CA_WIFI;
 
@@ -78,8 +82,6 @@ CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
     handler.startDiscoverServer = CAStartWIFIDiscoveryServer;
     handler.sendData = CASendWIFIUnicastData;
     handler.sendDataToAll = CASendWIFIMulticastData;
-    handler.startNotifyServer = CAStartWIFINotifyRecvServers;
-    handler.sendNotification = CASendWIFINotification;
     handler.GetnetInfo = CAGetWIFIInterfaceInformation;
     handler.readData = CAReadWIFIData;
     handler.stopAdapter = CAStopWIFI;
@@ -89,6 +91,10 @@ CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
 
     CAWiFiSetCallback(CAWiFiPacketReceiveCallback);
 
+    CAWiFiInitMutex();
+
+    CAWiFiInitialize(gThreadPoolHandle);
+
     return CA_STATUS_OK;
 }
 
@@ -96,14 +102,15 @@ void CATerminateWIfI()
 {
     OIC_LOG(DEBUG, TAG, "TerminateWifi");
 
+    OIC_LOG(DEBUG, TAG, "[ToDo] call CAStopWIFI in TerminateWifi");
+    CAStopWIFI();
+
     CAWiFiTerminate();
 }
 
 CAResult_t CAStartWIFI()
 {
     OIC_LOG(DEBUG, TAG, "CAStartWIFI");
-    //CAWiFiInitialize();
-    CAWiFiInitialize(gThreadPoolHandle);
 
     OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer");
     int32_t res = CAWiFiStartUnicastServer("0.0.0.0", atoi("5283"));
@@ -118,7 +125,9 @@ CAResult_t CAStopWIFI()
 {
     OIC_LOG(DEBUG, TAG, "CAStopWIFI");
 
-    // ToDo:
+    CAWiFiStopUnicastServer(0);
+
+    CAWiFiStopMulticastServer(0);
 
     return CA_STATUS_OK;
 }
@@ -151,7 +160,8 @@ uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t* endpoint, void* data, u
 {
     OIC_LOG(DEBUG, TAG, "SendWIFIUnicastData");
 
-    CAWiFiSendUnicastMessage(endpoint->addressInfo.IP.ipAddress, data, dataLen);
+    CAWiFiSendUnicastMessage(endpoint->addressInfo.IP.ipAddress, endpoint->addressInfo.IP.port,
+            data, dataLen);
 
     return 0;
 }
@@ -165,29 +175,11 @@ uint32_t CASendWIFIMulticastData(void* data, uint32_t dataLen)
     return 0;
 }
 
-CAResult_t CAStartWIFINotifyRecvServers()
-{
-    OIC_LOG(DEBUG, TAG, "StartWIFINotifyRecvServers");
-
-    // ToDo:
-
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen)
-{
-    OIC_LOG(DEBUG, TAG, "SendWIFINotification");
-
-    // ToDo:
-
-    return 0;
-}
-
 CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivity_t** info, uint32_t* size)
 {
     OIC_LOG(DEBUG, TAG, "GetWIFIInterfaceInformation");
 
-    // ToDo:
+    CAGetWIFIInterfaceInfo(info, size);
 
     return CA_STATUS_OK;
 }
index 81137c3..7f107e1 100644 (file)
-#include <stdio.h>\r
-#include <sys/socket.h>\r
-#include <arpa/inet.h>\r
-#include <string.h>\r
-#include <pthread.h>\r
-#include <unistd.h>\r
-#include <errno.h>\r
-#include <sys/types.h>\r
-#include <ifaddrs.h>\r
-#include <netinet/in.h>\r
-#include <string.h>\r
-#include <arpa/inet.h>\r
-\r
-#include "cawificore.h"\r
-#include "logger.h"\r
-#include "uthreadpool.h" /* for thread pool */\r
-#include "umutex.h"\r
-#include "caqueueingthread.h"\r
-#include "oic_malloc.h"\r
-\r
-#define TAG PCF("CA")\r
-\r
-#define CA_MAX_BUFFER_SIZE 512  // Max length of buffer\r#define CA_UNICAST_PORT 5383 // The port on which to listen for incoming data\r#define CA_MULTICAST_ADDR "224.0.1.187"\r
-#define CA_MULTICAST_PORT 5683\r
-\r
-typedef enum\r
-{\r
-    CA_UNICAST = 1, CA_MULTICAST\r
-} CATransmissionType_t;\r
-\r
-typedef struct\r
-{\r
-    CATransmissionType_t transmissionType; // 0: none, 1: unicast, 2: multicast\r
-    char* address;\r
-    int port;\r
-    void* data;\r
-} CAThreadData_t;\r
-\r
-typedef struct\r
-{\r
-    u_mutex threadMutex;\r
-    u_cond threadCond;\r
-    int32_t isStop;\r
-    int32_t status; // 0: stopped, 1: running\r
-} CATask_t;\r
-\r
-int32_t unicast_receive_socket;\r
-struct sockaddr_in multicast_send_interface_addr;\r
-int32_t multicast_receive_socket;\r
-struct sockaddr_in multicast_receive_interface_addr;\r
-\r
-static CAPacketReceiveCallback gPacketReceiveCallback = NULL;\r
-\r
-static u_thread_pool_t gThreadPoolHandle = NULL;\r
-\r
-// message handler main thread\r
-static CAQueueingThread_t gSendThread;\r
-static CAQueueingThread_t gReceiveThread;\r
-\r
-CATask_t unicastListenTask;\r
-CATask_t multicastListenTask;\r
-\r
-static void CASendProcess(void* threadData)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CASendThreadProcess");\r
-\r
-    CAThreadData_t* data = (CAThreadData_t*) threadData;\r
-    if (data == NULL)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "thread data is error!");\r
-        return;\r
-    }\r
-\r
-    if (data->transmissionType == CA_UNICAST)\r
-    {\r
-        // unicast\r
-        CASendUnicastMessageImpl(data->address, (char*) (data->data));\r
-    }\r
-    else if (data->transmissionType == CA_MULTICAST)\r
-    {\r
-        // multicast\r
-        CASendMulticastMessageImpl((char*) (data->data));\r
-    }\r
-}\r
-\r
-static void CAReceiveProcess(void* threadData)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAReceiveProcess");\r
-\r
-    CAThreadData_t* data = (CAThreadData_t*) threadData;\r
-    if (data == NULL)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "thread data is error!");\r
-        return;\r
-    }\r
-\r
-    if (gPacketReceiveCallback != NULL)\r
-    {\r
-        gPacketReceiveCallback(data->address, (char*) (data->data));\r
-    }\r
-}\r
-\r
-static void CAUnicastListenThread(void* threadData)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAUnicastListenThread");\r
-\r
-    char buf[CA_MAX_BUFFER_SIZE];\r
-    int32_t recv_len;\r
-\r
-    struct sockaddr_in si_other;\r
-    int32_t slen = sizeof(si_other);\r
-\r
-    while (!unicastListenTask.isStop)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAUnicastListenThread, Waiting for data...");\r
-        fflush(stdout);\r
-\r
-        memset(buf, 0, sizeof(char) * CA_MAX_BUFFER_SIZE);\r
-\r
-        // try to receive some data, this is a blocking call\r
-        if ((recv_len = recvfrom(unicast_receive_socket, buf, CA_MAX_BUFFER_SIZE, 0,\r
-                (struct sockaddr *) &si_other, (socklen_t *) &slen)) == -1)\r
-        {\r
-            OIC_LOG(DEBUG, TAG, "CAUnicastListenThread, recv_len() error");\r
-            continue;\r
-        }\r
-\r
-        // print details of the client/peer and the data received\r
-        OIC_LOG_V(DEBUG, TAG, "CAUnicastListenThread, Received packet from %s:%d",\r
-                inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));\r
-        OIC_LOG_V(DEBUG, TAG, "CAUnicastListenThread, Data: %s", buf);\r
-\r
-        // store the data at queue.\r
-        CAThreadData_t* td = NULL;\r
-        td = (CAThreadData_t*) OICMalloc(sizeof(CAThreadData_t));\r
-        memset(td, 0, sizeof(CAThreadData_t));\r
-        td->transmissionType = 1; // unicast\r
-\r
-        char* _address = inet_ntoa(si_other.sin_addr);\r
-        int len = strlen(_address);\r
-        td->address = (char*) OICMalloc(sizeof(char) * (len + 1));\r
-        memset(td->address, 0, len + 1);\r
-        memcpy(td->address, _address, len);\r
-        td->port = ntohs(si_other.sin_port);\r
-\r
-        td->data = (void*) OICMalloc(sizeof(void) * CA_MAX_BUFFER_SIZE);\r
-        memset(td->data, 0, CA_MAX_BUFFER_SIZE);\r
-        memcpy(td->data, buf, sizeof(buf));\r
-\r
-        CAQueueingThreadAddData(&gReceiveThread, td, sizeof(CAThreadData_t));\r
-    }\r
-\r
-    OIC_LOG(DEBUG, TAG, "end of CAUnicastListenThread");\r
-}\r
-\r
-static void CAMulticastListenThread(void* threadData)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAMulticastListenThread");\r
-\r
-    char msgbuf[CA_MAX_BUFFER_SIZE];\r
-\r
-    struct sockaddr_in client;\r
-    int32_t addrlen = sizeof(client);\r
-\r
-    OIC_LOG(DEBUG, TAG, "CAMulticastListenThread, waiting for input...");\r
-\r
-    while (!multicastListenTask.isStop)\r
-    {\r
-        int32_t recv_bytes = recvfrom(multicast_receive_socket, msgbuf, CA_MAX_BUFFER_SIZE, 0,\r
-                (struct sockaddr *) &client, (socklen_t *) &addrlen);\r
-        if (recv_bytes < 0)\r
-        {\r
-            if (errno != EAGAIN)\r
-            {\r
-                OIC_LOG(DEBUG, TAG, "CAMulticastListenThread, error recvfrom");\r
-\r
-                return;\r
-            }\r
-\r
-            continue;\r
-        }\r
-\r
-        msgbuf[recv_bytes] = 0;\r
-\r
-        OIC_LOG_V(DEBUG, TAG, "Received msg: %s, size: %d", msgbuf, recv_bytes);\r
-\r
-        char* sender = inet_ntoa(client.sin_addr);\r
-        char local[INET_ADDRSTRLEN];\r
-        CAGetLocalAddress(local);\r
-        if (strcmp(sender, local) == 0)\r
-        {\r
-            OIC_LOG_V(DEBUG, TAG, "skip the local request (via multicast)");\r
-        }\r
-        else\r
-        {\r
-            // store the data at queue.\r
-            CAThreadData_t* td = NULL;\r
-            td = (CAThreadData_t*) OICMalloc(sizeof(CAThreadData_t));\r
-            memset(td, 0, sizeof(CAThreadData_t));\r
-            td->transmissionType = 2; // multicast\r
-\r
-            char* _address = inet_ntoa(client.sin_addr);\r
-            int len = strlen(_address);\r
-            td->address = (char*) OICMalloc(sizeof(char) * (len + 1));\r
-            memset(td->address, 0, len + 1);\r
-            memcpy(td->address, _address, len);\r
-            td->port = ntohs(client.sin_port);\r
-\r
-            td->data = (void*) OICMalloc(sizeof(void) * CA_MAX_BUFFER_SIZE);\r
-            memset(td->data, 0, CA_MAX_BUFFER_SIZE);\r
-            memcpy(td->data, msgbuf, sizeof(msgbuf));\r
-\r
-            CAQueueingThreadAddData(&gReceiveThread, td, sizeof(CAThreadData_t));\r
-        }\r
-\r
-    }\r
-\r
-    OIC_LOG(DEBUG, TAG, "end of CAMulticastListenThread");\r
-}\r
-\r
-void CAWiFiInitialize(u_thread_pool_t handle)\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAWiFiInitialize");\r
-\r
-    gThreadPoolHandle = handle;\r
-\r
-    // unicast/multicast send queue\r
-    CAQueueingThreadInitialize(&gSendThread, gThreadPoolHandle, CASendProcess);\r
-\r
-    // start send thread\r
-    CAResult_t res = CAQueueingThreadStart(&gSendThread);\r
-    if (res != CA_STATUS_OK)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "thread start is error (send thread)");\r
-        // return res;\r
-        return;\r
-    }\r
-\r
-    // unicast/multicast receive queue\r
-    CAQueueingThreadInitialize(&gReceiveThread, gThreadPoolHandle, CAReceiveProcess);\r
-\r
-    // start send thread\r
-    res = CAQueueingThreadStart(&gReceiveThread);\r
-    if (res != CA_STATUS_OK)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "thread start is error (receive thread)");\r
-        // return res;\r
-        return;\r
-    }\r
-\r
-    unicastListenTask.threadMutex = u_mutex_new();\r
-    unicastListenTask.threadCond = u_cond_new();\r
-    unicastListenTask.isStop = FALSE;\r
-    unicastListenTask.status = 0; // stopped\r
-\r
-    multicastListenTask.threadMutex = u_mutex_new();\r
-    multicastListenTask.threadCond = u_cond_new();\r
-    multicastListenTask.isStop = FALSE;\r
-    multicastListenTask.status = 0; // stopped\r
-\r
-    // [UDP Server]\r
-    struct sockaddr_in si_me;\r
-\r
-    // create a UDP socket\r
-    if ((unicast_receive_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)\r
-    {\r
-        OIC_LOG_V(DEBUG, TAG, "CAWiFiInit, creating socket failed");\r
-\r
-        return;\r
-    }\r
-\r
-    OIC_LOG_V(DEBUG, TAG, "CAWiFiInit, socket created");\r
-\r
-    // [multicast sender]\r
-    uint32_t multiTTL = 1;\r
-\r
-    // zero out the structure\r
-    memset((char *) &si_me, 0, sizeof(si_me));\r
-\r
-    si_me.sin_family = AF_INET;\r
-    si_me.sin_port = htons(CA_UNICAST_PORT);\r
-    si_me.sin_addr.s_addr = htonl(INADDR_ANY);\r
-\r
-    int32_t ret_val = setsockopt(unicast_receive_socket, SOL_SOCKET, SO_REUSEADDR, &multiTTL,\r
-            sizeof(multiTTL));\r
-    if (ret_val < 0)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to set REUSEADDR");\r
-    }\r
-\r
-    // bind socket to port\r
-    if (bind(unicast_receive_socket, (struct sockaddr*) &si_me, sizeof(si_me)) == -1)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, binding socket failed");\r
-\r
-        return;\r
-    }\r
-\r
-    OIC_LOG(DEBUG, TAG, "CAWiFiInit, socket binded");\r
-\r
-    memset(&multicast_send_interface_addr, 0, sizeof(multicast_send_interface_addr));\r
-    multicast_send_interface_addr.sin_family = AF_INET;\r
-    multicast_send_interface_addr.sin_addr.s_addr = inet_addr(CA_MULTICAST_ADDR);\r
-    multicast_send_interface_addr.sin_port = htons(CA_MULTICAST_PORT);\r
-\r
-    // [multicast receiver]\r
-    // 1. Create a typical UDP socket and set Non-blocking for reading\r
-    multicast_receive_socket = socket(AF_INET, SOCK_DGRAM, 0);\r
-    if (multicast_receive_socket < 0)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Socket error");\r
-\r
-        return;\r
-    }\r
-\r
-    // 2. Allow multiple sockets to use the same port number\r
-    ret_val = setsockopt(multicast_receive_socket, SOL_SOCKET, SO_REUSEADDR, &multiTTL,\r
-            sizeof(multiTTL));\r
-    if (ret_val < 0)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to set REUSEADDR");\r
-    }\r
-\r
-    // 3. Set up the interface\r
-    memset(&multicast_receive_interface_addr, 0, sizeof(multicast_receive_interface_addr));\r
-    multicast_receive_interface_addr.sin_family = AF_INET;\r
-    multicast_receive_interface_addr.sin_addr.s_addr = htonl(INADDR_ANY);\r
-    multicast_receive_interface_addr.sin_port = htons(CA_MULTICAST_PORT);\r
-\r
-    // 4. Bind to the interface\r
-    ret_val = bind(multicast_receive_socket, (struct sockaddr *) &multicast_receive_interface_addr,\r
-            sizeof(multicast_receive_interface_addr));\r
-    if (ret_val < 0)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to bind socket");\r
-\r
-        return;\r
-    }\r
-\r
-    // 5. Join the multicast group\r
-    struct ip_mreq mreq;\r
-    memset(&mreq, 0, sizeof(mreq));\r
-    mreq.imr_multiaddr.s_addr = inet_addr(CA_MULTICAST_ADDR);\r
-    mreq.imr_interface.s_addr = htonl(INADDR_ANY);\r
-    ret_val = setsockopt(multicast_receive_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,\r
-            sizeof(mreq));\r
-    if (ret_val < 0)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to join multicast group");\r
-\r
-        return;\r
-    }\r
-}\r
-\r
-void CAWiFiTerminate()\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAWiFiTerminate");\r
-\r
-    close(unicast_receive_socket);\r
-    close(multicast_receive_socket);\r
-\r
-    shutdown(unicast_receive_socket, 2);\r
-    shutdown(multicast_receive_socket, 2);\r
-\r
-    CAWiFiStopUnicastServer(0);\r
-\r
-    CAWiFiStopMulticastServer(0);\r
-\r
-    // stop thread\r
-    CAQueueingThreadStop(&gSendThread);\r
-    // delete thread data\r
-    CAQueueingThreadDestroy(&gSendThread);\r
-\r
-    // stop thread\r
-    CAQueueingThreadStop(&gReceiveThread);\r
-    // delete thread data\r
-    CAQueueingThreadDestroy(&gReceiveThread);\r
-\r
-    u_mutex_free(unicastListenTask.threadMutex);\r
-    u_cond_free(unicastListenTask.threadCond);\r
-\r
-    u_mutex_free(multicastListenTask.threadMutex);\r
-    u_cond_free(multicastListenTask.threadCond);\r
-\r
-}\r
-\r
-int32_t CAWiFiSendUnicastMessage(const char* address, const char* data, int lengh)\r
-{\r
-    // store the data at queue.\r
-    CAThreadData_t* td = NULL;\r
-    td = (CAThreadData_t*) OICMalloc(sizeof(CAThreadData_t));\r
-    if (td == NULL)\r
-    {\r
-        return 0;\r
-    }\r
-    memset(td, 0, sizeof(CAThreadData_t));\r
-    td->transmissionType = CA_UNICAST; // unicast type\r
-    int len = strlen(address);\r
-    td->address = (char*) OICMalloc(sizeof(char) * (len + 1));\r
-    if (td->address != NULL)\r
-    {\r
-        memset(td->address, 0, len + 1);\r
-        memcpy(td->address, address, len);\r
-    }\r
-    else\r
-    {\r
-        OIC_LOG_V(DEBUG, TAG, "Memory Full");\r
-        OICFree(td);\r
-        return 0;\r
-    }\r
-\r
-    td->data = data;\r
-\r
-    CAQueueingThreadAddData(&gSendThread, td, sizeof(CAThreadData_t));\r
-\r
-    return 0;\r
-}\r
-\r
-int32_t CAWiFiSendMulticastMessage(const char* m_address, const char* data)\r
-{\r
-    // store the data at queue.\r
-    CAThreadData_t* td = NULL;\r
-    td = (CAThreadData_t*) OICMalloc(sizeof(CAThreadData_t));\r
-    if (td == NULL)\r
-    {\r
-        OICFree(data);\r
-        return 0;\r
-    }\r
-    memset(td, 0, sizeof(CAThreadData_t));\r
-    td->transmissionType = CA_MULTICAST; // multicast type\r
-    td->address = NULL;\r
-    td->data = data;\r
-\r
-    CAQueueingThreadAddData(&gSendThread, td, sizeof(CAThreadData_t));\r
-\r
-    return 0;\r
-}\r
-\r
-int32_t CAWiFiStartUnicastServer()\r
-{\r
-    OIC_LOG_V(DEBUG, TAG, "CAWiFiStartUnicastServer(%s, %d)", "0.0.0.0", CA_UNICAST_PORT);\r
-\r
-    // check the server status\r
-    if (unicastListenTask.status == 1)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer, already running");\r
-\r
-        return 0;\r
-    }\r
-\r
-    // unicast listen thread\r
-    CAResult_t res = u_thread_pool_add_task(gThreadPoolHandle, CAUnicastListenThread, NULL);\r
-    if (res != CA_STATUS_OK)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "adding task to thread pool is error (unicast listen thread)");\r
-        return res;\r
-    }\r
-\r
-    unicastListenTask.status = 1; // running\r
-\r
-    return 0;\r
-}\r
-\r
-int32_t CAWiFiStartMulticastServer()\r
-{\r
-    OIC_LOG_V(DEBUG, TAG, "CAWiFiStartMulticastServer(%s, %d)", "0.0.0.0", CA_MULTICAST_PORT);\r
-\r
-    // check the server status\r
-    if (multicastListenTask.status == 1)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CAWiFiStartMulticastServer, already running");\r
-\r
-        return 0;\r
-    }\r
-\r
-    // multicast listen thread\r
-    CAResult_t res = u_thread_pool_add_task(gThreadPoolHandle, CAMulticastListenThread, NULL);\r
-    if (res != CA_STATUS_OK)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "adding task to thread pool is error (multicast listen thread)");\r
-        return res;\r
-    }\r
-\r
-    multicastListenTask.status = 1;\r
-\r
-    return 0;\r
-}\r
-\r
-int32_t CAWiFiStopUnicastServer()\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAWiFiStopUnicastServer");\r
-\r
-    // mutex lock\r
-    u_mutex_lock(unicastListenTask.threadMutex);\r
-\r
-    // set stop flag\r
-    unicastListenTask.isStop = TRUE;\r
-\r
-    // notity the thread\r
-    u_cond_signal(unicastListenTask.threadCond);\r
-\r
-    // mutex unlock\r
-    u_mutex_unlock(unicastListenTask.threadMutex);\r
-\r
-    unicastListenTask.status = 0; // stopped\r
-\r
-    return 0;\r
-}\r
-\r
-int32_t CAWiFiStopMulticastServer()\r
-{\r
-    OIC_LOG(DEBUG, TAG, "CAWiFiStopMulticastServer");\r
-\r
-    // mutex lock\r
-    u_mutex_lock(multicastListenTask.threadMutex);\r
-\r
-    // set stop flag\r
-    multicastListenTask.isStop = TRUE;\r
-\r
-    // notity the thread\r
-    u_cond_signal(multicastListenTask.threadCond);\r
-\r
-    // mutex unlock\r
-    u_mutex_unlock(multicastListenTask.threadMutex);\r
-\r
-    multicastListenTask.status = 0; // stopped\r
-\r
-    return 0;\r
-}\r
-\r
-void CAWiFiSetCallback(CAPacketReceiveCallback callback)\r
-{\r
-    gPacketReceiveCallback = callback;\r
-}\r
-\r
-void CAGetLocalAddress(char* addressBuffer)\r
-{\r
-    //char addressBuffer[INET_ADDRSTRLEN];\r
-    memset(addressBuffer, 0, INET_ADDRSTRLEN);\r
-\r
-    struct ifaddrs* ifAddrStruct = NULL;\r
-    struct ifaddrs* ifa = NULL;\r
-    void* tmpAddrPtr = NULL;\r
-\r
-    getifaddrs(&ifAddrStruct);\r
-\r
-    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)\r
-    {\r
-        if (!ifa->ifa_addr)\r
-        {\r
-            continue;\r
-        }\r
-\r
-        if (ifa->ifa_addr->sa_family == AF_INET)\r
-        { // check it is IP4\r
-          // is a valid IP4 Address\r
-            tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;\r
-\r
-            memset(addressBuffer, 0, INET_ADDRSTRLEN);\r
-            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);\r
-\r
-            if (strcmp(addressBuffer, "127.0.0.1") == 0)\r
-                continue;\r
-        }\r
-    }\r
-\r
-    if (ifAddrStruct != NULL)\r
-        freeifaddrs(ifAddrStruct);\r
-}\r
-\r
-int32_t CASendUnicastMessageImpl(const char* address, const char* data)\r
-{\r
-    OIC_LOG_V(DEBUG, TAG, "CASendUnicastMessageImpl, address: %s, data: %s", address, data);\r
-\r
-    // [UDP Client]\r
-\r
-    struct sockaddr_in si_other;\r
-    int32_t slen = sizeof(si_other);\r
-\r
-    memset((char *) &si_other, 0, sizeof(si_other));\r
-\r
-    si_other.sin_family = AF_INET;\r
-    si_other.sin_port = htons(CA_UNICAST_PORT);\r
-    if (inet_aton(address, &si_other.sin_addr) == 0)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CASendUnicastMessageImpl, inet_aton, error...");\r
-        return 0;\r
-    }\r
-\r
-    OIC_LOG_V(DEBUG, TAG, "CASendUnicastMessageImpl, sendto, to: %s, data: %s", address, data);\r
-    if (sendto(unicast_receive_socket, data, strlen(data), 0, (struct sockaddr *) &si_other, slen)\r
-            == -1)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CASendUnicastMessageImpl, sendto, error...");\r
-\r
-        return 0;\r
-    }\r
-\r
-    return 0;\r
-}\r
-\r
-int32_t CASendMulticastMessageImpl(const char* msg)\r
-{\r
-    OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, sendto, data: %s", msg);\r
-\r
-    int32_t result = sendto(unicast_receive_socket, msg, strlen(msg), 0,\r
-            (struct sockaddr *) &multicast_send_interface_addr,\r
-            sizeof(multicast_send_interface_addr));\r
-    if (result < 0)\r
-    {\r
-        OIC_LOG(DEBUG, TAG, "CASendMulticastMessageImpl, sending message error...");\r
-\r
-        return -1;\r
-    }\r
-\r
-    return 0;\r
-}\r
+#include <stdio.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <string.h>
+#include <pthread.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <ifaddrs.h>
+#include <netinet/in.h>
+#include <string.h>
+#include <arpa/inet.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <net/if.h>
+
+#include "cawificore.h"
+#include "logger.h"
+#include "uthreadpool.h" /* for thread pool */
+#include "umutex.h"
+#include "caqueueingthread.h"
+#include "oic_malloc.h"
+
+#define TAG PCF("CA")
+
+#define REQ_CNT 20
+#define CA_MAX_BUFFER_SIZE 512  // Max length of buffer
+#define CA_UNICAST_PORT 5000 // The port on which to listen for incoming data
+#define CA_MULTICAST_ADDR "224.0.1.187"
+#define CA_MULTICAST_PORT 5683
+
+typedef enum
+{
+    CA_UNICAST = 1, CA_MULTICAST
+} CATransmissionType_t;
+
+typedef struct
+{
+    CATransmissionType_t transmissionType; // 0: none, 1: unicast, 2: multicast
+    char* address;
+    int port;
+    void* data;
+} CAThreadData_t;
+
+typedef struct
+{
+    u_mutex threadMutex;
+    u_cond threadCond;
+    int32_t isStop;
+    int32_t status; // 0: stopped, 1: running
+} CATask_t;
+
+static int gUnicastPort = 0;
+
+int32_t unicast_receive_socket; // unicast server, unicast client, multicast client
+struct sockaddr_in multicast_send_interface_addr;
+
+int32_t multicast_receive_socket; // multicast server
+struct sockaddr_in multicast_receive_interface_addr;
+
+static CAPacketReceiveCallback gPacketReceiveCallback = NULL;
+
+static u_thread_pool_t gThreadPoolHandle = NULL;
+
+// message handler main thread
+static CAQueueingThread_t gSendThread;
+static CAQueueingThread_t gReceiveThread;
+
+static CATask_t unicastListenTask;
+static CATask_t multicastListenTask;
+
+static void CASendProcess(void* threadData)
+{
+    OIC_LOG(DEBUG, TAG, "CASendThreadProcess");
+
+    CAThreadData_t* data = (CAThreadData_t*) threadData;
+    if (data == NULL)
+    {
+        OIC_LOG(DEBUG, TAG, "thread data is error!");
+        return;
+    }
+
+    if (data->transmissionType == CA_UNICAST)
+    {
+        // unicast
+        CASendUnicastMessageImpl(data->address, data->port, (char*) (data->data));
+    }
+    else if (data->transmissionType == CA_MULTICAST)
+    {
+        // multicast
+        CASendMulticastMessageImpl((char*) (data->data));
+    }
+}
+
+static void CAReceiveProcess(void* threadData)
+{
+    OIC_LOG(DEBUG, TAG, "CAReceiveProcess");
+
+    CAThreadData_t* data = (CAThreadData_t*) threadData;
+    if (data == NULL)
+    {
+        OIC_LOG(DEBUG, TAG, "thread data is error!");
+        return;
+    }
+
+    if (gPacketReceiveCallback != NULL)
+    {
+        gPacketReceiveCallback(data->address, data->port, (char*) (data->data));
+    }
+}
+
+void CAWiFiSetCallback(CAPacketReceiveCallback callback)
+{
+    gPacketReceiveCallback = callback;
+}
+
+void CAWiFiInitMutex()
+{
+    OIC_LOG(DEBUG, TAG, "CAWiFiInitMutex");
+
+    unicastListenTask.threadMutex = u_mutex_new();
+    unicastListenTask.threadCond = u_cond_new();
+    unicastListenTask.isStop = FALSE;
+    unicastListenTask.status = 0; // stopped
+
+    multicastListenTask.threadMutex = u_mutex_new();
+    multicastListenTask.threadCond = u_cond_new();
+    multicastListenTask.isStop = FALSE;
+    multicastListenTask.status = 0; // stopped
+}
+
+static void CAUnicastListenThread(void* threadData)
+{
+    OIC_LOG(DEBUG, TAG, "CAUnicastListenThread");
+
+    char buf[CA_MAX_BUFFER_SIZE];
+    uint32_t recv_len;
+
+    int32_t ret = 0;
+
+    struct sockaddr_in si_other;
+    socklen_t slen = sizeof(si_other);
+
+    fd_set reads;
+    struct timeval timeout;
+
+    while (1)
+    {
+        u_mutex_lock(unicastListenTask.threadMutex);
+        int32_t isStop = unicastListenTask.isStop;
+        u_mutex_unlock(unicastListenTask.threadMutex);
+        if (isStop)
+            break;
+
+        // OIC_LOG(DEBUG, TAG, "CAUnicastListenThread, Waiting for data...");
+
+        memset(buf, 0, sizeof(char) * CA_MAX_BUFFER_SIZE);
+
+        timeout.tv_sec = 1;
+        timeout.tv_usec = 0;
+
+        FD_ZERO(&reads);
+
+        // Use select for polling the socket fd
+        FD_SET(unicast_receive_socket, &reads);
+
+        ret = select(unicast_receive_socket + 1, &reads, NULL, NULL, &timeout);
+        if (ret < 0)
+        {
+            // OIC_LOG(DEBUG, TAG, "CAUnicastListenThread, select API failed");
+
+            continue;
+        }
+        if (!FD_ISSET(unicast_receive_socket, &reads))
+        {
+            // OIC_LOG(DEBUG, TAG, "CAUnicastListenThread, No data to read");
+            continue;
+        }
+
+        // try to receive some data
+        if ((recv_len = recvfrom(unicast_receive_socket, buf, CA_MAX_BUFFER_SIZE, 0,
+                (struct sockaddr *) &si_other, &slen)) == -1)
+        {
+            OIC_LOG_V(DEBUG, TAG, "%s\n", strerror(errno));
+            continue;
+        }
+        else if (0 == recv_len)
+        {
+            OIC_LOG(DEBUG, TAG, "Unicast socket is shutdown, returning from thread\n");
+            return;
+        }
+
+        // print details of the client/peer and the data received
+        OIC_LOG_V(DEBUG, TAG, "CAUnicastListenThread, Received packet from %s:%d",
+                inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port));
+        OIC_LOG_V(DEBUG, TAG, "CAUnicastListenThread, Data: %s", buf);
+
+        // store the data at queue.
+        CAThreadData_t* td = NULL;
+        td = (CAThreadData_t*) OICMalloc(sizeof(CAThreadData_t));
+        memset(td, 0, sizeof(CAThreadData_t));
+        td->transmissionType = 1; // unicast
+
+        char* _address = inet_ntoa(si_other.sin_addr);
+        int len = strlen(_address);
+        td->address = (char*) OICMalloc(sizeof(char) * (len + 1));
+        memset(td->address, 0, len + 1);
+        memcpy(td->address, _address, len);
+
+        td->port = ntohs(si_other.sin_port);
+
+        td->data = (void*) OICMalloc(sizeof(void) * CA_MAX_BUFFER_SIZE);
+        memset(td->data, 0, CA_MAX_BUFFER_SIZE);
+        memcpy(td->data, buf, sizeof(buf));
+
+        CAQueueingThreadAddData(&gReceiveThread, td, sizeof(CAThreadData_t));
+    }
+
+    u_cond_signal(unicastListenTask.threadCond);
+    OIC_LOG(DEBUG, TAG, "end of CAUnicastListenThread");
+}
+
+static void CAMulticastListenThread(void* threadData)
+{
+    OIC_LOG(DEBUG, TAG, "CAMulticastListenThread");
+
+    char msgbuf[CA_MAX_BUFFER_SIZE];
+
+    struct sockaddr_in client;
+    int32_t addrlen = sizeof(client);
+
+    fd_set reads;
+    struct timeval timeout;
+
+    while (1)
+    {
+        u_mutex_lock(multicastListenTask.threadMutex);
+        int32_t isStop = multicastListenTask.isStop;
+        u_mutex_unlock(multicastListenTask.threadMutex);
+        if (isStop)
+            break;
+
+        timeout.tv_sec = 1;
+        timeout.tv_usec = 0;
+
+        FD_ZERO(&reads);
+
+        // Use select for polling the socket fd
+        FD_SET(multicast_receive_socket, &reads);
+
+        int32_t ret = select(multicast_receive_socket + 1, &reads, NULL, NULL, &timeout);
+        if (ret < 0)
+        {
+            // OIC_LOG_V(FATAL, TAG, "CAMulticastListenThread, select API failed");
+            continue;
+        }
+        if (!FD_ISSET(multicast_receive_socket, &reads))
+        {
+            // OIC_LOG_V(DEBUG, TAG, "CAMulticastListenThread, No data to read");
+            continue;
+        }
+
+        // try to receive some data
+        int32_t recv_bytes = 0;
+        if ((recv_bytes = recvfrom(multicast_receive_socket, msgbuf, CA_MAX_BUFFER_SIZE, 0,
+                (struct sockaddr *) &client, (socklen_t *) &addrlen)) == -1)
+        {
+            OIC_LOG_V(DEBUG, TAG, "%s\n", strerror(errno));
+            continue;
+        }
+        else if (0 == recv_bytes)
+        {
+            OIC_LOG_V(ERROR, TAG, "Multicast socket is shutdown, returning from thread\n");
+            OIC_LOG(DEBUG, TAG, "return here ");
+            return;
+        }
+
+        OIC_LOG_V(DEBUG, TAG, "Received msg: %s, size: %d", msgbuf, recv_bytes);
+
+        // store the data at queue.
+        CAThreadData_t* td = NULL;
+        td = (CAThreadData_t*) OICMalloc(sizeof(CAThreadData_t));
+        memset(td, 0, sizeof(CAThreadData_t));
+        td->transmissionType = 2; // multicast
+
+        char* _address = inet_ntoa(client.sin_addr);
+        int len = strlen(_address);
+        td->address = (char*) OICMalloc(sizeof(char) * (len + 1));
+        memset(td->address, 0, len + 1);
+        memcpy(td->address, _address, len);
+        td->port = ntohs(client.sin_port);
+
+        td->data = (void*) OICMalloc(sizeof(void) * CA_MAX_BUFFER_SIZE);
+        memset(td->data, 0, CA_MAX_BUFFER_SIZE);
+        memcpy(td->data, msgbuf, sizeof(msgbuf));
+
+        CAQueueingThreadAddData(&gReceiveThread, td, sizeof(CAThreadData_t));
+
+    }
+
+    // leave the group after you are done
+    int16_t result = setsockopt(multicast_receive_socket, IPPROTO_IP, IP_DROP_MEMBERSHIP,
+            (struct sockaddr *) &multicast_receive_interface_addr,
+            sizeof(multicast_receive_interface_addr));
+    if (result < 0)
+    {
+        OIC_LOG_V(DEBUG, TAG,
+                "CAWiFiStopMulticastServer, cannot leave multicast group, Error code: %s\n",
+                strerror(errno));
+    }
+    u_cond_signal(multicastListenTask.threadCond);
+
+    OIC_LOG(DEBUG, TAG, "end of CAMulticastListenThread");
+}
+
+void CAWiFiInitialize(u_thread_pool_t handle)
+{
+    OIC_LOG(DEBUG, TAG, "CAWiFiInitialize");
+
+    gThreadPoolHandle = handle;
+
+    // unicast/multicast send queue
+    CAQueueingThreadInitialize(&gSendThread, gThreadPoolHandle, CASendProcess);
+
+    // start send thread
+    CAResult_t res = CAQueueingThreadStart(&gSendThread);
+    if (res != CA_STATUS_OK)
+    {
+        OIC_LOG(DEBUG, TAG, "thread start is error (send thread)");
+        // return res;
+        return;
+    }
+
+    // unicast/multicast receive queue
+    CAQueueingThreadInitialize(&gReceiveThread, gThreadPoolHandle, CAReceiveProcess);
+
+    // start send thread
+    res = CAQueueingThreadStart(&gReceiveThread);
+    if (res != CA_STATUS_OK)
+    {
+        OIC_LOG(DEBUG, TAG, "thread start is error (receive thread)");
+        // return res;
+        return;
+    }
+}
+
+int32_t CABindUnicastSocket()
+{
+    int32_t i;
+    for (i = 0; i < 100; i++)
+    {
+        int32_t port = CA_UNICAST_PORT + i;
+
+        struct sockaddr_in si_me;
+        memset((char *) &si_me, 0, sizeof(si_me));
+        si_me.sin_family = AF_INET;
+        si_me.sin_port = htons(port);
+        si_me.sin_addr.s_addr = htonl(INADDR_ANY);
+
+        // bind socket to port
+        if (bind(unicast_receive_socket, (struct sockaddr*) &si_me, sizeof(si_me)) == 0)
+        {
+            OIC_LOG_V(DEBUG, TAG, "CABindUnicastSocket, socket binded, port: %d", port);
+
+            gUnicastPort = port;
+
+            return 0;
+        }
+
+    }
+
+    OIC_LOG(DEBUG, TAG, "CABindUnicastSocket, binding socket failed");
+
+    return -1;
+}
+
+void CAWiFiTerminate()
+{
+    OIC_LOG(DEBUG, TAG, "CAWiFiTerminate");
+
+    close(unicast_receive_socket);
+    close(multicast_receive_socket);
+
+    // stop thread
+    CAQueueingThreadStop(&gSendThread);
+    // delete thread data
+    CAQueueingThreadDestroy(&gSendThread);
+
+    // stop thread
+    CAQueueingThreadStop(&gReceiveThread);
+    // delete thread data
+    CAQueueingThreadDestroy(&gReceiveThread);
+
+    u_mutex_free(unicastListenTask.threadMutex);
+
+    u_mutex_free(multicastListenTask.threadMutex);
+
+    OIC_LOG(DEBUG, TAG, "end of CAWiFiTerminate");
+}
+
+int32_t CAWiFiSendUnicastMessage(const char* address, const int port, char* data, int lengh)
+{
+    // store the data at queue.
+    CAThreadData_t* td = NULL;
+    td = (CAThreadData_t*) OICMalloc(sizeof(CAThreadData_t));
+    if (td == NULL)
+    {
+        OICFree(data);
+        return 0;
+    }
+    memset(td, 0, sizeof(CAThreadData_t));
+    td->transmissionType = CA_UNICAST; // unicast type
+    int len = strlen(address);
+    td->address = (char*) OICMalloc(sizeof(char) * (len + 1));
+    if (td->address != NULL)
+    {
+        memset(td->address, 0, len + 1);
+        memcpy(td->address, address, len);
+    }
+    else
+    {
+        OIC_LOG_V(DEBUG, TAG, "Memory Full");
+        OICFree(td);
+        OICFree(data);
+        return 0;
+    }
+
+    td->port = port;
+    td->data = data;
+
+    CAQueueingThreadAddData(&gSendThread, td, sizeof(CAThreadData_t));
+
+    return 0;
+}
+
+int32_t CAWiFiSendMulticastMessage(const char* m_address, char* data)
+{
+    // store the data at queue.
+    CAThreadData_t* td = NULL;
+    td = (CAThreadData_t*) OICMalloc(sizeof(CAThreadData_t));
+    if (td == NULL)
+    {
+        OICFree(data);
+        return 0;
+    }
+    memset(td, 0, sizeof(CAThreadData_t));
+    td->transmissionType = CA_MULTICAST; // multicast type
+    td->address = NULL;
+    td->port = 0;
+    td->data = data;
+
+    CAQueueingThreadAddData(&gSendThread, td, sizeof(CAThreadData_t));
+
+    return 0;
+}
+
+int32_t CAWiFiStartUnicastServer()
+{
+    OIC_LOG_V(DEBUG, TAG, "CAWiFiStartUnicastServer");
+
+    // check the server status
+    if (unicastListenTask.status == 1)
+    {
+        OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer, already running");
+
+        return 0;
+    }
+
+    // 1. create a UDP socket
+    if ((unicast_receive_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
+    {
+        OIC_LOG_V(DEBUG, TAG, "CAWiFiInitialize, creating socket failed");
+
+        return -1;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CAWiFiInitialize, socket created");
+
+    // 2. Make the socket non-blocking
+    int16_t status = 0;
+    if ((status = fcntl(unicast_receive_socket, F_SETFL, O_NONBLOCK)) < 0)
+    {
+        OIC_LOG_V(ERROR, TAG,
+                "CAWiFiInitialize, fcntl to make the socket non-blocking failed, Error code: %s",
+                strerror(errno));
+
+        close(unicast_receive_socket);
+
+        return -1;
+    }
+
+    OIC_LOG(DEBUG, TAG, "CAWiFiInitialize, socket creation success");
+
+    // 3. set socket option // This is will allow server , client bining on same socket
+    /* uint32_t multiTTL = 1;
+     int32_t ret_val = setsockopt(unicast_receive_socket, SOL_SOCKET, SO_REUSEADDR, &multiTTL,
+     sizeof(multiTTL));
+     if (ret_val < 0)
+     {
+     OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to set REUSEADDR");
+     close(unicast_receive_socket);
+
+     return -1;
+     }*/
+
+    // 4. bind socket
+    if (CABindUnicastSocket() == -1)
+    {
+        close(unicast_receive_socket);
+
+        return -1;
+    }
+
+    // unicast listen thread
+    CAResult_t res = u_thread_pool_add_task(gThreadPoolHandle, CAUnicastListenThread, NULL);
+    if (res != CA_STATUS_OK)
+    {
+        OIC_LOG(DEBUG, TAG, "adding task to thread pool is error (unicast listen thread)");
+        return res;
+    }
+
+    unicastListenTask.status = 1; // running
+    OIC_LOG_V(DEBUG, TAG, "CAWiFiStartUnicastServer(%s, %d)", "Local Address", gUnicastPort);
+
+    return 0;
+}
+
+int32_t CAWiFiStartMulticastServer()
+{
+    OIC_LOG_V(DEBUG, TAG, "CAWiFiStartMulticastServer(%s, %d)", "0.0.0.0", CA_MULTICAST_PORT);
+
+    // check the server status
+    if (multicastListenTask.status == 1)
+    {
+        OIC_LOG(DEBUG, TAG, "CAWiFiStartMulticastServer, already running");
+
+        return 0;
+    }
+
+    memset(&multicast_send_interface_addr, 0, sizeof(multicast_send_interface_addr));
+    multicast_send_interface_addr.sin_family = AF_INET;
+    multicast_send_interface_addr.sin_addr.s_addr = inet_addr(CA_MULTICAST_ADDR);
+    multicast_send_interface_addr.sin_port = htons(CA_MULTICAST_PORT);
+
+    // 1. Create a typical UDP socket and set Non-blocking for reading
+    multicast_receive_socket = socket(AF_INET, SOCK_DGRAM, 0);
+    if (multicast_receive_socket == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Socket error");
+
+        return -1;
+    }
+
+    // 2. Make the socket non-blocking
+    int16_t status = 0;
+    if ((status = fcntl(multicast_receive_socket, F_SETFL, O_NONBLOCK)) < 0)
+    {
+        OIC_LOG_V(ERROR, TAG, "fcntl to make the socket non-blocking failed, Error code: %s",
+                strerror(errno));
+        close(multicast_receive_socket);
+
+        return -1;
+    }
+
+    // 2. Allow multiple sockets to use the same port number
+    uint32_t multiTTL = 1;
+    int32_t ret_val = setsockopt(multicast_receive_socket, SOL_SOCKET, SO_REUSEADDR, &multiTTL,
+            sizeof(multiTTL));
+    if (ret_val < 0)
+    {
+        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to set REUSEADDR");
+        close(multicast_receive_socket);
+
+        return -1;
+    }
+
+    // 3. Set up the interface
+    memset(&multicast_receive_interface_addr, 0, sizeof(multicast_receive_interface_addr));
+    multicast_receive_interface_addr.sin_family = AF_INET;
+    multicast_receive_interface_addr.sin_addr.s_addr = htonl(INADDR_ANY);
+    multicast_receive_interface_addr.sin_port = htons(CA_MULTICAST_PORT);
+
+    // 4. Bind to the interface
+    ret_val = bind(multicast_receive_socket, (struct sockaddr *) &multicast_receive_interface_addr,
+            sizeof(multicast_receive_interface_addr));
+    if (ret_val < 0)
+    {
+        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to bind socket");
+        close(multicast_receive_socket);
+
+        return -1;
+    }
+
+    // 5. Join the multicast group
+    struct ip_mreq mreq;
+    memset(&mreq, 0, sizeof(mreq));
+    mreq.imr_multiaddr.s_addr = inet_addr(CA_MULTICAST_ADDR);
+    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
+    ret_val = setsockopt(multicast_receive_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
+            sizeof(mreq));
+    if (ret_val < 0)
+    {
+        OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to join multicast group");
+        close(multicast_receive_socket);
+
+        return -1;
+    }
+
+    // multicast listen thread
+    CAResult_t res = u_thread_pool_add_task(gThreadPoolHandle, CAMulticastListenThread, NULL);
+    if (res != CA_STATUS_OK)
+    {
+        OIC_LOG(DEBUG, TAG, "adding task to thread pool is error (multicast listen thread)");
+        return res;
+    }
+
+    multicastListenTask.status = 1;
+
+    return 0;
+}
+
+int32_t CAWiFiStopUnicastServer()
+{
+    OIC_LOG(DEBUG, TAG, "CAWiFiStopUnicastServer");
+
+    // check the server status
+    if (unicastListenTask.status == 0)
+    {
+        OIC_LOG(DEBUG, TAG, "CAWiFiStopUnicastServer, already stopped");
+
+        return 0;
+    }
+
+    // mutex lock
+    u_mutex_lock(unicastListenTask.threadMutex);
+
+    // set stop flag
+    unicastListenTask.isStop = TRUE;
+
+    u_cond_wait(unicastListenTask.threadCond, unicastListenTask.threadMutex);
+
+    // notity the thread
+    // u_cond_signal(unicastListenTask.threadCond);
+
+    // mutex unlock
+    u_mutex_unlock(unicastListenTask.threadMutex);
+
+    unicastListenTask.status = 0; // stopped
+
+    // close(unicast_receive_socket);
+
+    return 0;
+}
+
+int32_t CAWiFiStopMulticastServer()
+{
+    OIC_LOG(DEBUG, TAG, "CAWiFiStopMulticastServer");
+
+    // check the server status
+    if (multicastListenTask.status == 0)
+    {
+        OIC_LOG(DEBUG, TAG, "CAWiFiStopMulticastServer, already stopped");
+
+        return 0;
+    }
+
+    // mutex lock
+    u_mutex_lock(multicastListenTask.threadMutex);
+
+    // set stop flag
+    multicastListenTask.isStop = TRUE;
+
+    u_cond_wait(multicastListenTask.threadCond, multicastListenTask.threadMutex);
+
+    // mutex unlock
+    u_mutex_unlock(multicastListenTask.threadMutex);
+
+    multicastListenTask.status = 0; // stopped
+
+    return 0;
+}
+
+void CAGetLocalAddress(char* addressBuffer)
+{
+    //char addressBuffer[INET_ADDRSTRLEN];
+    memset(addressBuffer, 0, INET_ADDRSTRLEN);
+
+    struct ifaddrs* ifAddrStruct = NULL;
+    struct ifaddrs* ifa = NULL;
+    void* tmpAddrPtr = NULL;
+
+    getifaddrs(&ifAddrStruct);
+
+    for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next)
+    {
+        if (!ifa->ifa_addr)
+        {
+            continue;
+        }
+
+        if (ifa->ifa_addr->sa_family == AF_INET)
+        { // check it is IP4
+          // is a valid IP4 Address
+            tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr;
+
+            memset(addressBuffer, 0, INET_ADDRSTRLEN);
+            inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
+
+            if (strcmp(addressBuffer, "127.0.0.1") == 0)
+                continue;
+        }
+    }
+
+    if (ifAddrStruct != NULL)
+        freeifaddrs(ifAddrStruct);
+}
+
+int32_t CASendUnicastMessageImpl(const char* address, const int port, const char* data)
+{
+    OIC_LOG_V(DEBUG, TAG, "CASendUnicastMessageImpl, address: %s:%d, data: %s", address, port,
+            data);
+
+    // [UDP Client]
+
+    struct sockaddr_in si_other;
+    int32_t slen = sizeof(si_other);
+
+    memset((char *) &si_other, 0, sizeof(si_other));
+
+    si_other.sin_family = AF_INET;
+    si_other.sin_port = htons(port);
+    if (inet_aton(address, &si_other.sin_addr) == 0)
+    {
+        OIC_LOG(DEBUG, TAG, "CASendUnicastMessageImpl, inet_aton, error...");
+        return 0;
+    }
+
+    OIC_LOG_V(DEBUG, TAG, "CASendUnicastMessageImpl, sendto, to: %s, data: %s", address, data);
+    if (sendto(unicast_receive_socket, data, strlen(data), 0, (struct sockaddr *) &si_other, slen)
+            == -1)
+    {
+        OIC_LOG(DEBUG, TAG, "CASendUnicastMessageImpl, sendto, error...");
+
+        return 0;
+    }
+
+    return 0;
+}
+
+int32_t CASendMulticastMessageImpl(const char* msg)
+{
+    OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, sendto, data: %s", msg);
+
+    int32_t result = sendto(unicast_receive_socket, msg, strlen(msg), 0,
+            (struct sockaddr *) &multicast_send_interface_addr,
+            sizeof(multicast_send_interface_addr));
+    if (result < 0)
+    {
+        OIC_LOG(DEBUG, TAG, "CASendMulticastMessageImpl, sending message error...");
+
+        return -1;
+    }
+
+    return 0;
+}
+
+CAResult_t CAGetWIFIInterfaceInfo(CALocalConnectivity_t **info, uint32_t* size)
+{
+    uint32_t cnt, req_cnt = REQ_CNT;
+    int32_t fd;
+    uint32_t cmd = SIOCGIFCONF;
+    uint32_t resSize = 0;
+    char* localIPAddress;
+    struct sockaddr_in *sock;
+    struct ifconf ifc;
+    struct ifreq *ifr;
+
+    memset((void *) &ifc, 0, sizeof(struct ifconf));
+    ifc.ifc_len = sizeof(struct ifconf) * req_cnt;
+    ifc.ifc_buf = NULL;
+    ifc.ifc_buf = malloc(ifc.ifc_len);
+
+    if ((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
+    {
+        OIC_LOG(DEBUG, TAG, "create socket error!");
+        return CA_STATUS_FAILED;
+    }
+
+    if (ioctl(fd, cmd, &ifc) < 0)
+    {
+        OIC_LOG(DEBUG, TAG, "SIOCGIFCONF fail");
+        close(fd);
+        return CA_STATUS_FAILED;
+    }
+    close(fd);
+
+    if (ifc.ifc_len > (sizeof(struct ifreq) * req_cnt))
+    {
+        req_cnt = ifc.ifc_len;
+        ifc.ifc_buf = realloc(ifc.ifc_buf, req_cnt);
+    }
+
+    ifr = ifc.ifc_req;
+    for (cnt = 0; cnt < ifc.ifc_len; cnt += sizeof(struct ifreq), ifr++)
+    {
+        sock = (struct sockaddr_in *) &ifr->ifr_addr;
+
+        // except loopback address
+        if (ntohl(sock->sin_addr.s_addr) == INADDR_LOOPBACK)
+            continue;
+
+        // get local address
+        localIPAddress = inet_ntoa(sock->sin_addr);
+
+        CALocalConnectivity_t* localInfo;
+
+        // memory allocation
+        localInfo = (CALocalConnectivity_t*) OICMalloc(sizeof(CALocalConnectivity_t));
+        if (localInfo == NULL)
+        {
+            OIC_LOG_V(DEBUG, TAG, "memory alloc error!!");
+            free(localInfo);
+            return CA_STATUS_FAILED;
+        }
+        memset(localInfo, 0, sizeof(CALocalConnectivity_t));
+
+        if (strlen(localIPAddress) > CA_IPADDR_SIZE)
+        {
+            OIC_LOG_V(DEBUG, TAG, "address size is wrong!!");
+            free(localInfo);
+            return CA_STATUS_FAILED;
+        }
+        // set local ip address
+        strncpy(localInfo->addressInfo.IP.ipAddress, localIPAddress, strlen(localIPAddress));
+
+        // set network type
+        localInfo->type = CA_WIFI;
+
+        *info = localInfo;
+
+        resSize++;
+    }
+
+    *size = resSize;
+
+    return CA_STATUS_OK;
+}
index 31c0501..ce9a390 100644 (file)
@@ -32,8 +32,8 @@
 #define ETHERNET_ADAPTER_TAG "ETHERNET_ADAPTER"
 
 CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback,
-                                CANetworkPacketReceivedCallback networkPacketCallback, CANetworkChangeCallback netCallback,
-                                u_thread_pool_t handle)
+                                CANetworkPacketReceivedCallback networkPacketCallback,
+                                CANetworkChangeCallback netCallback, u_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "IN");
     OIC_LOG(DEBUG, ETHERNET_ADAPTER_TAG, "OUT");
index 2aaa639..9eb0937 100644 (file)
@@ -96,31 +96,13 @@ void CAInitializeMutex()
 {
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
     u_mutex_init();
-    if (NULL == gMutexIsMulticastServerStarted)
+    if(NULL == gMutexIsMulticastServerStarted)
     {
         gMutexIsMulticastServerStarted = u_mutex_new();
     }
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
 }
 
-int CAWIFIRegisterNetworkNotifications(CANetworkChangeCallback netCallback)
-{
-    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
-
-    if (netCallback != NULL)
-    {
-        CAInitializeWIFIAdapter();
-        CASetWIFINetworkChangeCallback(netCallback);
-    }
-    else
-    {
-        CADeinitializeWIFIAdapter();
-    }
-
-    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
 CAResult_t CAInitializeQueueHandles()
 {
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
@@ -138,8 +120,8 @@ CAResult_t CAInitializeQueueHandles()
         return CA_STATUS_FAILED;
     }
     CASetRecvQueueHandle(gRecvQueueHandle);
-    return CA_STATUS_OK;
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
 }
 
 void CADeinitializeSendQueueHandle()
@@ -158,6 +140,24 @@ void CADeinitializeRecvQueueHandle()
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
 }
 
+int CAWIFIRegisterNetworkNotifications(CANetworkChangeCallback netCallback)
+{
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
+
+    if (NULL != netCallback)
+    {
+        CAInitializeWIFIAdapter();
+        CASetWIFINetworkChangeCallback(netCallback);
+    }
+    else
+    {
+        CADeinitializeWIFIAdapter();
+    }
+
+    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
+    return CA_STATUS_OK;
+}
+
 #if 0 /* Skip Queue */
 void CASetWIFINetworkPacketCallback(CANetworkPacketReceivedCallback callback)
 {
@@ -166,33 +166,33 @@ void CASetWIFINetworkPacketCallback(CANetworkPacketReceivedCallback callback)
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
 }
 #endif //#if 0
+
 CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback,
-        CANetworkPacketReceivedCallback networkPacketCallback, CANetworkChangeCallback netCallback,
-        u_thread_pool_t handle)
+                            CANetworkPacketReceivedCallback networkPacketCallback,
+                            CANetworkChangeCallback netCallback, u_thread_pool_t handle)
 {
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
     VERIFY_NON_NULL(registerCallback, WIFI_ADAPTER_TAG,
             "Invalid argument : registerCallback is NULL");
     VERIFY_NON_NULL(networkPacketCallback, WIFI_ADAPTER_TAG,
-            "Invalid argument : networkPacketCallback is NULL");
+                    "Invalid argument : networkPacketCallback is NULL");
     VERIFY_NON_NULL(netCallback, WIFI_ADAPTER_TAG, "Invalid argument : netCallback is NULL");
 
+    CASetWIFINetworkPacketCallback(networkPacketCallback);
+    CAWIFIRegisterNetworkNotifications(netCallback);
+
     CAConnectivityHandler_t wifiHandler;
     wifiHandler.startAdapter = CAStartWIFI;
     wifiHandler.startListenServer = CAStartWIFIListeningServer;
     wifiHandler.startDiscoverServer = CAStartWIFIDiscoveryServer;
     wifiHandler.sendData = CASendWIFIUnicastData;
     wifiHandler.sendDataToAll = CASendWIFIMulticastData;
-    wifiHandler.startNotifyServer = CAStartWIFINotifyRecvServers;
-    wifiHandler.sendNotification = CASendWIFINotification;
     wifiHandler.GetnetInfo = CAGetWIFIInterfaceInformation;
     wifiHandler.readData = CAReadWIFIData;
     wifiHandler.stopAdapter = CAStopWIFI;
     wifiHandler.terminate = CATerminateWIfI;
     registerCallback(wifiHandler, CA_WIFI);
 
-    CASetWIFINetworkPacketCallback(networkPacketCallback);
-    CAWIFIRegisterNetworkNotifications(netCallback);
     CAInitializeMutex();
     CAInitializeServerMutex();
     CASetThreadHandle(handle);
@@ -223,7 +223,7 @@ CAResult_t CAStartWIFI()
 
     CASetIsStartServerInvoked();
     CABool_t retVal = CAIsWIFIConnected();
-    if (retVal == CA_FALSE)
+    if (CA_FALSE == retVal)
     {
         OIC_LOG(INFO, WIFI_ADAPTER_TAG, "WIFI is not Connected");
         return ret;
@@ -252,7 +252,7 @@ CAResult_t CAStartWIFIListeningServer()
     }
 
     CABool_t retVal = CAIsWIFIConnected();
-    if (retVal == CA_FALSE)
+    if (CA_FALSE == retVal)
     {
         OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG,
                 "Failed to Start Listening Server, WIFI is not Connected! Return code[%d]",
@@ -261,7 +261,7 @@ CAResult_t CAStartWIFIListeningServer()
     }
 
     ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort);
-    if (ret == CA_STATUS_OK)
+    if (CA_STATUS_OK == ret)
     {
         OIC_LOG(INFO, WIFI_ADAPTER_TAG, "Multicast Server is Started Successfully");
         u_mutex_lock(gMutexIsMulticastServerStarted);
@@ -289,7 +289,7 @@ CAResult_t CAStartWIFIDiscoveryServer()
     }
 
     CABool_t retVal = CAIsWIFIConnected();
-    if (retVal == CA_FALSE)
+    if (CA_FALSE == retVal)
     {
         OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG,
                 "Failed to Start Discovery Server, WIFI is not Connected! Return code[%d]",
@@ -298,7 +298,7 @@ CAResult_t CAStartWIFIDiscoveryServer()
     }
 
     ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort);
-    if (ret == CA_STATUS_OK)
+    if (CA_STATUS_OK == ret)
     {
         OIC_LOG(INFO, WIFI_ADAPTER_TAG, "Multicast Server is Started Successfully");
         u_mutex_lock(gMutexIsMulticastServerStarted);
@@ -311,14 +311,14 @@ CAResult_t CAStartWIFIDiscoveryServer()
 }
 
 uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
-        uint32_t dataLen)
+                               uint32_t dataLen)
 {
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
 
     uint32_t dataSize = 0;
 
-    VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ADAPTER_TAG,
-            "Invalid argument : remoteEndpoint is NULL", dataSize);
+    VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ADAPTER_TAG, "Invalid argument : remoteEndpoint is NULL",
+                        dataSize);
     VERIFY_NON_NULL_RET(data, WIFI_ADAPTER_TAG, "Invalid argument : data is NULL", dataSize);
 
     if (dataLen <= 0)
@@ -367,28 +367,12 @@ uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLength)
     return dataLength;
 }
 
-CAResult_t CAStartWIFINotifyRecvServers()
-{
-    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
-
-    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
-uint32_t CASendWIFINotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen)
-{
-    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
-
-    OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "OUT");
-    return CA_STATUS_OK;
-}
-
 CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivity_t **info, uint32_t *size)
 {
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
 
     CABool_t retVal = CAIsWIFIConnected();
-    if (retVal == CA_FALSE)
+    if (CA_FALSE == retVal)
     {
         OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG,
                 "Failed to get interface address, WIFI is not Connected! Return code[%d]",
@@ -402,12 +386,13 @@ CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivity_t **info, uint32_t
 
     CAGetInterfaceAddress(localIpAddress, localIpAddressLen);
 
+
     // Create local endpoint using util function
     (*info) = CAAdapterCreateLocalEndpoint(CA_WIFI, localIpAddress, "WiFi");
     if (NULL == (*info))
     {
         OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to create Local Endpoint! Return code[%d]",
-                CA_MEMORY_ALLOC_FAILED);
+                  CA_MEMORY_ALLOC_FAILED);
         return CA_MEMORY_ALLOC_FAILED;
     }
 
@@ -437,7 +422,7 @@ CAResult_t CAReadWIFIData()
     if (gNetworkPacketCallback && (NULL != messageReceived))
     {
         gNetworkPacketCallback(messageReceived->remoteEndpoint, messageReceived->data,
-                messageReceived->dataLen);
+                               messageReceived->dataLen);
     }
 
     CAAdapterFreeMessage(messageReceived);
@@ -450,18 +435,16 @@ CAResult_t CAStopWIFI()
     OIC_LOG(DEBUG, WIFI_ADAPTER_TAG, "IN");
     CAResult_t result = CA_STATUS_FAILED;
     result = CAStopUnicastServer();
-    if (result != CA_STATUS_OK)
+    if (CA_STATUS_OK != result)
     {
-        OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Unicast Server! Return code[%d]",
-                result);
+        OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Unicast Server! Return code[%d]", result);
         return result;
     }
     CAUnsetIsStartServerInvoked();
     result = CAStopMulticastServer();
-    if (result != CA_STATUS_OK)
+    if (CA_STATUS_OK != result)
     {
-        OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Multicast Server! Return code[%d]",
-                result);
+        OIC_LOG_V(ERROR, WIFI_ADAPTER_TAG, "Failed to Stop Multicast Server! Return code[%d]", result);
         return result;
     }
     else
@@ -483,9 +466,10 @@ void CATerminateWIfI()
 
     CASetWIFINetworkPacketCallback(NULL);
     result = CAWIFIRegisterNetworkNotifications(NULL);
-    if (result != CA_STATUS_OK)
+    if (CA_STATUS_OK != result)
     {
-        OIC_LOG(ERROR, WIFI_ADAPTER_TAG, "Failed to Unregister Network Notifications");
+        OIC_LOG(ERROR, WIFI_ADAPTER_TAG,
+                "Failed to Unregister Network Notifications");
     }
     OIC_LOG(INFO, WIFI_ADAPTER_TAG, "TerminateWifi Success");
 
index 1417d79..cd000ce 100644 (file)
@@ -84,7 +84,7 @@ void CASetSendQueueHandle(CAAdapterMessageQueue_t *gSendQueueHandle, CABool_t fl
     OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "IN");
     gClientSendQueueHandle = gSendQueueHandle;
     gSendDataFlag = flag;
-    if (cond == NULL)
+    if (NULL == cond)
     {
         u_cond_signal(gClientSendDataCond);
     }
@@ -110,8 +110,8 @@ CAResult_t CAStartSendDataThread(u_thread_pool_t threadHandle)
         OIC_LOG(ERROR, WIFI_CLIENT_TAG, "Failed to add task in thread pool");
         return CA_STATUS_FAILED;
     }
-    return CA_STATUS_OK;
     OIC_LOG(DEBUG, WIFI_CLIENT_TAG, "OUT");
+    return CA_STATUS_OK;
 }
 
 uint32_t CAWIFISendData(const char *remoteIpAddress, const uint32_t port, const char *data,
index 47d8e70..9e6f561 100644 (file)
 #include "uthreadpool.h"
 
 /**
+ * @brief API to Set the Unicast Socket descriptor
+ * @param  unicastSocketDesc         [IN] Unicast Socket Descriptor
+ * @return - None
+ */
+void CASetUnicastSocketDescriptor(int unicastSocketDesc);
+/**
  * @brief API to Set the send queue handle
  * @param  gSendQueueHandle         [IN] Queue Handle to Send Data
  * @return - None
  */
-void CASetSendQueueHandle(CAAdapterMessageQueue_t *gSendQueueHandle, CABool_t flag, u_cond cond);
+void CASetSendQueueHandle(CAAdapterMessageQueue_t *gSendQueueHandle,
+                          CABool_t flag, u_cond cond);
 
 /**
  * @brief API to Set the Multicast IP and Port Address
index 53271b3..04b5522 100644 (file)
 
 #define WIFI_MONITOR_TAG "WIFI_MONITOR"
 
+/**
+ * @var gIsStartServerCalled
+ * @brief Flag for start server started or not.
+ */
 static int gIsStartServerCalled = 0;
+
+/**
+ * @var gMutexIsStartServerCalled
+ * @brief Mutex for global variable gIsStartServerCalled.
+ */
 static u_mutex gMutexIsStartServerCalled = NULL;
+
 CANetworkChangeCallback gNetworkChangeCb = NULL;
 
 CAResult_t CAGetInterfaceAddress(char *address, int32_t addrLen)
@@ -76,7 +86,7 @@ CAResult_t CAGetInterfaceAddress(char *address, int32_t addrLen)
                                    sizeof(struct sockaddr_in6),
                                    address, CA_IPADDR_SIZE,
                                    NULL, 0, NI_NUMERICHOST);
-                if (name != 0)
+                if (0 != name)
                 {
                     OIC_LOG_V(ERROR, WIFI_MONITOR_TAG, "Failed to get IPAddress, Error code: %s",
                               strerror(errno));
@@ -95,19 +105,39 @@ CAResult_t CAGetInterfaceAddress(char *address, int32_t addrLen)
 CAResult_t CAInitializeWIFIAdapter()
 {
     OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "IN");
-    wifi_initialize();
     gMutexIsStartServerCalled = u_mutex_new();
     wifi_error_e ret = WIFI_ERROR_INVALID_PARAMETER;
-    wifi_set_device_state_changed_cb(CAWIFIDeviceStateChangedCb, NULL);
+    ret = wifi_initialize();
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, WIFI_MONITOR_TAG, "wifi_initialize failed");
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_initialize success");
+    }
+
+    ret = wifi_set_device_state_changed_cb(CAWIFIDeviceStateChangedCb, NULL);
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(ERROR, WIFI_MONITOR_TAG, "wifi_set_device_state_changed_cb failed");
+        return CA_STATUS_FAILED;
+    }
+    else
+    {
+        OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_set_device_state_changed_cb success");
+    }
+
     ret = wifi_set_connection_state_changed_cb(CAWIFIConnectionStateChangedCb, NULL);
-    if (ret != WIFI_ERROR_NONE)
+    if (WIFI_ERROR_NONE != ret)
     {
         OIC_LOG(ERROR, WIFI_MONITOR_TAG, "wifi_set_connection_state_changed_cb failed");
         return CA_STATUS_FAILED;
     }
     else
     {
-        OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_set_connection_state_changed_cb sucess");
+        OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_set_connection_state_changed_cb success");
     }
     OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "OUT");
     return CA_STATUS_OK;
@@ -117,9 +147,9 @@ CAResult_t CADeinitializeWIFIAdapter()
 {
     OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "IN");
     wifi_error_e ret = WIFI_ERROR_INVALID_PARAMETER;
-    wifi_unset_device_state_changed_cb();
-    ret = wifi_unset_connection_state_changed_cb();
-    if (ret != WIFI_ERROR_NONE)
+
+    ret = wifi_unset_device_state_changed_cb();
+    if (WIFI_ERROR_NONE != ret)
     {
         OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_unset_device_state_changed_cb failed");
     }
@@ -127,7 +157,26 @@ CAResult_t CADeinitializeWIFIAdapter()
     {
         OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_unset_device_state_changed_cb success");
     }
-    wifi_deinitialize();
+
+    ret = wifi_unset_connection_state_changed_cb();
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_unset_connection_state_changed_cb failed");
+    }
+    else
+    {
+        OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_unset_connection_state_changed_cb success");
+    }
+
+    ret = wifi_deinitialize();
+    if (WIFI_ERROR_NONE != ret)
+    {
+        OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_deinitialize failed");
+    }
+    else
+    {
+        OIC_LOG(INFO, WIFI_MONITOR_TAG, "wifi_deinitialize success");
+    }
     OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "OUT");
     return CA_STATUS_OK;
 }
@@ -137,12 +186,12 @@ CABool_t CAIsWIFIConnected()
     OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "IN");
     wifi_connection_state_e connection_state;
     int retVal = wifi_get_connection_state(&connection_state);
-    if (retVal != WIFI_ERROR_NONE)
+    if (WIFI_ERROR_NONE != retVal)
     {
         OIC_LOG(ERROR, WIFI_MONITOR_TAG, "Failed to get the Connection State");
         return CA_FALSE;
     }
-    if (connection_state == WIFI_CONNECTION_STATE_DISCONNECTED)
+    if (WIFI_CONNECTION_STATE_DISCONNECTED == connection_state)
     {
         OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "WIFI is not Connected");
         return CA_FALSE;
@@ -155,7 +204,7 @@ CABool_t CAIsWIFIConnected()
 void CAWIFIConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *userData)
 {
     OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "IN");
-    if (state == WIFI_CONNECTION_STATE_ASSOCIATION
+    if (WIFI_CONNECTION_STATE_ASSOCIATION == state
         || WIFI_CONNECTION_STATE_CONFIGURATION == state)
     {
         OIC_LOG(DEBUG, WIFI_MONITOR_TAG, "Connection is in Association State");
@@ -179,8 +228,10 @@ void CAWIFIConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap,
         localEndpoint = CAAdapterCreateLocalEndpoint(CA_WIFI, "", NULL);
         CAStopUnicastServer();
     }
-
-    gNetworkChangeCb(localEndpoint, nwConnectivityStatus);
+    if (NULL != gNetworkChangeCb)
+    {
+        gNetworkChangeCb(localEndpoint, nwConnectivityStatus);
+    }
 
     CAAdapterFreeLocalEndpoint(localEndpoint);
 
index fef7d24..0347624 100644 (file)
@@ -35,6 +35,7 @@
 #include <unistd.h>
 #include "caadapterutils.h"
 #include "umutex.h"
+#include "cawificlient.h"
 
 /**
  * @def WIFI_SERVER_TAG
@@ -242,7 +243,7 @@ CAResult_t CAStartUnicastServer(const char *localAddress, int16_t *port)
 
     OIC_LOG(INFO, WIFI_SERVER_TAG, "socket bind success");
 
-    socklen_t len; // = sizeof(sin);
+    socklen_t len = sizeof(sockAddr);
 
     if (getsockname(gUnicastServerSocketDescriptor, (struct sockaddr *)&sockAddr, &len) == -1)
     {
@@ -446,7 +447,7 @@ CAResult_t CAStopUnicastServer()
     // close the socket
     int16_t ret = close(gUnicastServerSocketDescriptor);
 
-    if (ret == -1)
+    if (-1 == ret)
     {
         OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Unicast Server socket close failed, Error code: %s\n",
                   strerror(errno));
@@ -495,7 +496,7 @@ CAResult_t CAStopMulticastServer()
 
     // close the socket
     result = close(gMulticastServerSocketDescriptor);
-    if (result == -1)
+    if (-1 == result)
     {
         OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Multicast Server socket close failed, Error code: %s\n",
                   strerror(errno));
@@ -524,12 +525,6 @@ void *CAReceiveThreadForUnicast(void *data)
         return NULL;
     }
 
-    char *buf = (char *) OICMalloc (CA_BUFFER_LEN);
-    if (NULL == buf)
-    {
-        OIC_LOG(ERROR, WIFI_SERVER_TAG, "Memory Allocation failed");
-        return NULL;
-    }
     uint32_t recvLen;
     int32_t ret = 0;
     struct sockaddr_in siOther;
@@ -551,8 +546,6 @@ void *CAReceiveThreadForUnicast(void *data)
     {
         OIC_LOG(DEBUG, WIFI_SERVER_TAG, "Waiting for data..");
 
-        memset(buf, 0, sizeof(char) * CA_BUFFER_LEN);
-
         timeout.tv_sec = 1;
         timeout.tv_usec = 0;
 
@@ -572,17 +565,40 @@ void *CAReceiveThreadForUnicast(void *data)
             continue;
         }
 
+        // Allocate Memory for COAP Buffer
+        char *buf = (char *) OICMalloc (CA_BUFFER_LEN);
+        if (NULL == buf)
+        {
+            OIC_LOG(ERROR, WIFI_SERVER_TAG, "Memory Allocation failed");
+            return (void *) NULL;
+        }
+
+        memset(buf, 0, sizeof(char) * CA_BUFFER_LEN);
+
+        CARemoteEndpoint_t *endPointUnicast = (CARemoteEndpoint_t *) OICMalloc (sizeof(CARemoteEndpoint_t));
+        if (NULL == endPointUnicast)
+        {
+            OIC_LOG(ERROR, WIFI_SERVER_TAG, "Memory Allocation failed");
+            OICFree(buf);
+            return NULL;
+        }
+        memset (endPointUnicast, 0, sizeof(CARemoteEndpoint_t));
+
 
         // try to receive some data
         if ((recvLen = recvfrom(gUnicastServerSocketDescriptor, buf, CA_BUFFER_LEN, 0,
                                 (struct sockaddr *) &siOther, &sLen)) == -1)
         {
             OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "%s\n", strerror(errno));
+            OICFree(buf);
+            OICFree(endPointUnicast);
             continue;
         }
         else if (0 == recvLen)
         {
             OIC_LOG(ERROR, WIFI_SERVER_TAG, "Unicast socket is shutdown, returning from thread\n");
+            OICFree(buf);
+            OICFree(endPointUnicast);
             return (void *) NULL;
         }
 
@@ -605,6 +621,12 @@ void *CAReceiveThreadForUnicast(void *data)
         {
             gNetworkPacketCallback(endPointUnicast, buf, recvLen);
         }
+        else
+        {
+            OICFree(buf);
+            OICFree(endPointUnicast);
+        }
+        // Currently, endPointUnicast and buf is freed in gNetworkPacketCallback
 #endif //#if 0
     }
     OIC_LOG(DEBUG, WIFI_SERVER_TAG, "stopUnicastServer is called, Breaking from while loop\n");
@@ -622,34 +644,18 @@ void *CAReceiveThreadForMulticast(void *data)
         return NULL;
     }
 
-    char *buf = (char *) OICMalloc (CA_BUFFER_LEN);
-    if (NULL == buf)
-    {
-        OIC_LOG(ERROR, WIFI_SERVER_TAG, "Memory Allocation failed");
-        return NULL;
-    }
     int recvLen;
     struct sockaddr_in siOther;
     int32_t ret = 0;
     socklen_t sLen = sizeof(siOther);
     fd_set reads;
     struct timeval timeout;
-    CARemoteEndpoint_t *endPointMulticast = (CARemoteEndpoint_t *) OICMalloc (sizeof(
-            CARemoteEndpoint_t));
-    if (NULL == endPointMulticast)
-    {
-        OIC_LOG(ERROR, WIFI_SERVER_TAG, "Memory Allocation failed");
-        return NULL;
-    }
-    memset (endPointMulticast, 0, sizeof(CARemoteEndpoint_t));
-
 
     // keep listening for data
     while (!gStopMulticast)
     {
         OIC_LOG(DEBUG, WIFI_SERVER_TAG, "Waiting for data...\n");
 
-        memset(buf, 0, sizeof(char) * CA_BUFFER_LEN);
         timeout.tv_sec = 1;
         timeout.tv_usec = 0;
         FD_ZERO(&reads);
@@ -668,16 +674,40 @@ void *CAReceiveThreadForMulticast(void *data)
             continue;
         }
 
+        // Allocate Memory for COAP Buffer
+        char *buf = (char *) OICMalloc (CA_BUFFER_LEN);
+        if (NULL == buf)
+        {
+            OIC_LOG(ERROR, WIFI_SERVER_TAG, "Memory Allocation failed");
+            return (void *) NULL;
+        }
+
+        memset(buf, 0, sizeof(char) * CA_BUFFER_LEN);
+
+        CARemoteEndpoint_t *endPointMulticast = (CARemoteEndpoint_t *) OICMalloc (sizeof(
+                CARemoteEndpoint_t));
+        if (NULL == endPointMulticast)
+        {
+            OIC_LOG(ERROR, WIFI_SERVER_TAG, "Memory Allocation failed");
+            OICFree(buf);
+            return NULL;
+        }
+        memset (endPointMulticast, 0, sizeof(CARemoteEndpoint_t));
+
         // try to receive some data
         if ((recvLen = recvfrom(gMulticastServerSocketDescriptor, buf, CA_BUFFER_LEN, 0,
                                 (struct sockaddr *) &siOther, &sLen)) == -1)
         {
             OIC_LOG_V(DEBUG, WIFI_SERVER_TAG, "%s\n", strerror(errno));
+            OICFree(buf);
+            OICFree(endPointMulticast);
             continue;
         }
         else if (0 == recvLen)
         {
             OIC_LOG_V(ERROR, WIFI_SERVER_TAG, "Multicast socket is shutdown, returning from thread\n");
+            OICFree(buf);
+            OICFree(endPointMulticast);
             return (void *) NULL;
         }
 
@@ -688,19 +718,19 @@ void *CAReceiveThreadForMulticast(void *data)
 
         endPointMulticast->resourceUri = NULL; // will be filled by upper layer
         strncpy((char *)endPointMulticast->addressInfo.IP.ipAddress, inet_ntoa(siOther.sin_addr),
-                strlen(inet_ntoa(siOther.sin_addr)));
+                (CA_IPADDR_SIZE-1));
         endPointMulticast->addressInfo.IP.port = ntohs(siOther.sin_port);
         endPointMulticast->connectivityType = CA_WIFI;
-
-#if 0 /* Skip Queue */
-        // Enqueue the Received Message in the Queue
-        CAAdapterEnqueueMessage(gServerRecvQueueHandle, &endPointMulticast, buf, recvLen);
-#else
         if (gNetworkPacketCallback)
         {
             gNetworkPacketCallback(endPointMulticast, buf, recvLen);
         }
-#endif //#if 0
+        else
+        {
+            OICFree(buf);
+            OICFree(endPointMulticast);
+        }
+        // Currently, endpointMulticast and buf is freed in gNetworkPacketCallback
     }
     OIC_LOG(DEBUG, WIFI_SERVER_TAG, "stopMulticastServer is called, Breaking from while loop\n");
 
index 8a4d07d..352bb7a 100644 (file)
@@ -99,6 +99,8 @@ void interfaceRegisterCallback(CAConnectivityHandler handler,
                                CAConnectivityType connType)
 {
     printf("interfaceRegisterCallback Entry in Sample\n");
+// connectivity Handlerlist is not used
+#if 0
     ConnectivityHandlerList* newConnectivityHandler = (ConnectivityHandlerList*) malloc(sizeof(ConnectivityHandlerList));
     if (NULL == newConnectivityHandler)
     {
@@ -109,6 +111,7 @@ void interfaceRegisterCallback(CAConnectivityHandler handler,
     newConnectivityHandler->type = connType;
     newConnectivityHandler->handler = handler;
     storeInterfaceCallbacks(newConnectivityHandler);
+#endif //#if 0
     printf("interfaceRegisterCallback Exit in Sample\n");
 }