From 7538ae25f1ec388d4a1f765376e47f34dbd17e93 Mon Sep 17 00:00:00 2001 From: jk13 Date: Fri, 9 Jan 2015 16:14:17 +0900 Subject: [PATCH] [SSM] Modify ommited arduino sample and soft sensor sample 1. Modify Arduino indoor trajectory reference sensor 2. Modify indoor trajectory soft sensor for tizen Change-Id: If83113c4564d894c8d740ecc357999acabc29f46 Signed-off-by: jk13 Reviewed-on: https://gerrit.iotivity.org/gerrit/109 Tested-by: jenkins-iotivity Reviewed-by: Uze Choi --- .../SampleApp/Readme_ITScenario.txt | 45 + .../arduino/Reference_Thing/build/makefile | 76 +- .../arduino/Reference_Thing/include/bleLib.h | 131 +-- .../arduino/Reference_Thing/include/oic_lanLib.h | 25 +- .../arduino/Reference_Thing/src/bleLib.cpp | 917 ++++++++++----------- .../arduino/Reference_Thing/src/oic_lanLib.cpp | 39 +- .../arduino/Reference_Thing/src/reference.cpp | 316 ++++--- .../arduino/Reference_Thing/src/trackee.cpp | 263 ++++++ .../arduino/Trackee_Thing/include/bleLib.h | 131 +-- .../arduino/Trackee_Thing/include/proximity.h | 31 +- .../arduino/Trackee_Thing/include/trackee.h | 27 +- .../SampleApp/arduino/Trackee_Thing/src/bleLib.cpp | 903 ++++++++++---------- .../arduino/Trackee_Thing/src/oic_lanLib.cpp | 29 +- .../arduino/Trackee_Thing/src/proximity.cpp | 152 ++-- .../arduino/Trackee_Thing/src/trackee.cpp | 498 +++++------ .../IndoorTrajectorySensor/include/ITS.h | 5 +- .../IndoorTrajectorySensor/include/lib_proximity.h | 32 + .../include/tizen_CbleDevice.h | 62 ++ .../include/tizen_ble_bgthread.h | 91 ++ .../IndoorTrajectorySensor/include/tizen_log.h | 102 +++ .../include/tizen_proximity.h | 113 +++ .../include/tizen_public_ble.h | 33 + .../IndoorTrajectorySensor/src/GeneralData.cpp | 3 +- .../IndoorTrajectorySensor/src/ITS.cpp | 80 +- .../IndoorTrajectorySensor/src/Trajectory.cpp | 1 - .../IndoorTrajectorySensor/src/lib_proximity.cpp | 110 +++ .../src/tizen_CbleDevice.cpp | 160 ++++ .../src/tizen_ble_bgthread.cpp | 463 +++++++++++ .../IndoorTrajectorySensor/src/tizen_proximity.cpp | 446 ++++++++++ 29 files changed, 3685 insertions(+), 1599 deletions(-) create mode 100644 service/soft-sensor-manager/SampleApp/Readme_ITScenario.txt create mode 100644 service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/trackee.cpp create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/lib_proximity.h create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_CbleDevice.h create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_ble_bgthread.h create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_log.h create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_proximity.h create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_public_ble.h create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/lib_proximity.cpp create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_CbleDevice.cpp create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_ble_bgthread.cpp create mode 100644 service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_proximity.cpp diff --git a/service/soft-sensor-manager/SampleApp/Readme_ITScenario.txt b/service/soft-sensor-manager/SampleApp/Readme_ITScenario.txt new file mode 100644 index 0000000..094ddf4 --- /dev/null +++ b/service/soft-sensor-manager/SampleApp/Readme_ITScenario.txt @@ -0,0 +1,45 @@ +/****************************************************************** +* +* 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. +* +******************************************************************/ + +=============================================================================== +== What is Indoor Trajectory Scenario == +=============================================================================== + +Here we prepare Indoor Trajectory Sample for Soft Sensor Manager. + +There are 2 main components and 1 sub module to show how Indoor Trajectory works. + +1. Reference Thing is Arduino application that shold be deployed at somewhere + + which should working as signal beacon. + +2. Indoor Trajectory Sensor is the soft sensor for tizen platform that + + checks the RSSI signal between reference thing and tizen platform using + + tizen BLE api. + +3. Trackee_Thing is sub sensor which almost same behavior as Indoor Trajector Sensor + + which not only belongs to tizen platform. This also can check the RSSI for + + checking distance and send its measurements to other device using iotivity protocol. + + So you can also get the measurement without using tizen BLE api. \ No newline at end of file diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile index 4abd7ec..dfa246b 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile +++ b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile @@ -1,21 +1,25 @@ +-include ../../../../build/arduino/root_path.inc -include ../../../../build/arduino/environment.mk + ARDUINO_DIR = /usr/share/arduino +SRC_PATH=../src + +# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield +ARDUINOWIFI := 0 + +APP_NAME := trackee BUILD := release +#BUILD := debug PLATFORM := arduinomega -ARDUINO_PORT := ttyACM0 +ARDUINO_PORT := /dev/ttyACM0 SRCLIST=${wildcard ${SRC_PATH}/*.cpp} OBJPATH=${SRCLIST:.cpp=.o} OBJLIST=${notdir ${OBJPATH}} -SRC_PATH=../src -# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield -ARDUINOWIFI := 0 - -APP_NAME := reference - -TB_DIR = ../../../../../../resource/csdk +TB_DIR = ${IOT_BASE}/csdk +OIC_BUILD_DIR = ${IOT_CSDK_MAKE_PATH} LOGGER_DIR = $(TB_DIR)/logger OC_LOG_DIR = $(TB_DIR)/../oc_logger TBSTACK_DIR = $(TB_DIR)/stack @@ -46,65 +50,67 @@ else TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) endif -OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD) +.PHONY: all install resource clean -OBJ_DIR := $(OUT_DIR)/bin +all: prep_dirs core.a $(APP_NAME).elf $(APP_NAME).hex -all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex +OBJ_DIR := ./bin + +resource: preclean + @cd $(OIC_BUILD_DIR) && make PLATFORM=${PLATFORM} ARDUINOWIFI=${ARDUINOWIFI} + +preclean: + @cd $(OIC_BUILD_DIR) && make deepclean core.a: $(PLATFORM_OBJS) - @cd $(OBJ_DIR) && $(AR) -x ../../../../$(TB_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a - $(AR) rcs $(OBJ_DIR)/$@ $(foreach obj, $^, $(OBJ_DIR)/$(obj)) $(OBJ_DIR)/*.o - @cd $(OBJ_DIR) && $(RANLIB) $@ + @echo ">>>>>>>>>>> core.a build <<<<<<<<<<<<<<" + @cd $(OBJ_DIR) && $(AR) -x $(TB_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a + $(AR) rcs $@ $^ $(OBJ_DIR)/*.o + $(RANLIB) $@ prep_dirs: - -mkdir $(PLATFORM) - -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE) - -mkdir $(OUT_DIR) - -mkdir $(OBJ_DIR) + -mkdir -p $(OBJ_DIR) %.o: %.c - $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ + $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@ %.o: %.cpp - $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ + $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@ %.o: ${SRC_PATH}/%.cpp - $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ + $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@ $(APP_NAME).elf: $(OBJLIST) core.a ifeq ($(PLATFORM),arduinomega) - $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $(foreach obj, $^, $(OBJ_DIR)/$(obj)) -lm -o $(OBJ_DIR)/$@ + $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $^ -lm -o $@ else ifeq ($(PLATFORM),arduinodue) - $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group +# $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group + $(error Not yet Supported !! ) else $(error Wrong value for PLATFORM !!) endif $(APP_NAME).hex: $(APP_NAME).elf ifeq ($(PLATFORM),arduinomega) - $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(OBJ_DIR)/$< $(OBJ_DIR)/$(APP_NAME).eep - $(AVR_OBJCOPY) -O ihex -R .eeprom $(OBJ_DIR)/$< $(OUT_DIR)/$@ + $(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 $< $@ else ifeq ($(PLATFORM),arduinodue) - $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@ + $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $< $@ else $(error Wrong value for PLATFORM !!) endif -install: all +install: ifeq ($(PLATFORM),arduinomega) - $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(OUT_DIR)/$(APP_NAME).hex:i + $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(APP_NAME).hex:i else ifeq ($(PLATFORM),arduinodue) stty -F /dev/$(ARDUINO_PORT) speed 1200 cs8 -cstopb -parenb - $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(OUT_DIR)/$(APP_NAME).hex -R + $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(APP_NAME).hex -R else $(error Wrong value for PLATFORM !!) endif -.PHONY: clean -clean: legacy_clean - rm -rf arduinomega - rm -rf arduinodue -legacy_clean: - @rm -rf bin +clean: @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *- + @rm -rf $(OBJ_DIR) + diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h index 8356098..a543229 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h +++ b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h @@ -1,82 +1,95 @@ -/* - * bleLib.h - * - * Created on: 2014. 11. 5. - * Author: eunseok - */ +/****************************************************************** +* +* 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 BLELIB_H_ #define BLELIB_H_ #include "Arduino.h" -#define BLE_NOCHANGE -1 -#define BLE_MASTER 1 -#define BLE_SLAVER 0 +#define BLE_NOCHANGE -1 +#define BLE_MASTER 1 +#define BLE_SLAVER 0 -#define BLE_DISCON 200 -#define BLE_NODATA 100 +#define BLE_DISCON 200 +#define BLE_NODATA 100 /*************************************** * - * HM-10 BLE Module Control Class. - * Target Board : Arduino-Mega. + * HM-10 BLE Module Control Class. + * Target Board : Arduino-Mega. * **************************************/ class Cble { -public : - /*** - * BLE Control Function. - */ - // BLE initialization ( COM baud rate , BLE Master , Slave setting. ) - void init(long baudRate, int ble_mode, char* SelfMaxAddr); - - void StatusRead( void ); - - bool IsSelfArduino( void ); - - bool IsConnected( void ); - - bool pollingConnect( const char* maxAddr ); - - void pollingDisconnect( void ); - // Get RSSI by BLE communication. (polling method.) - int pollingGetRSSI( void ); - // Send Request to BLE Module. And, Get the response. (polling method.) - bool pollingRequest(const char* request, char* data, int dataLen); - - int mustHaveRequest(const char* request, char* data, int dataLen); - - void streamDummy( char* data, int dataLen); - - /*** - * Debug COM port to BLE COM port. - * BLE COM port to Debug COM port. - */ - // BLE Module to Debug Serial port. - void BLE2Debug( int autoDiscon ); - // Debug Serial port to BLE Module. - char* Debug2BLE( int BLEwrite ); - - /*** - * If you first setting, you need next-function. - */ - // Restore to factory setting data. - void FactoryReset( void ); - // First setting of COM port. - void firstUartSetting( void ); + public : + /*** + * BLE Control Function. + */ + // BLE initialization ( COM baud rate , BLE Master , Slave setting. ) + void init(long baudRate, int ble_mode, char *SelfMaxAddr); + + void StatusRead( void ); + + bool IsSelfArduino( void ); + + bool IsConnected( void ); + + bool pollingConnect( const char *maxAddr ); + + void pollingDisconnect( void ); + // Get RSSI by BLE communication. (polling method.) + int pollingGetRSSI( void ); + // Send Request to BLE Module. And, Get the response. (polling method.) + bool pollingRequest(const char *request, char *data, int dataLen); + + int mustHaveRequest(const char *request, char *data, int dataLen); + + void streamDummy( char *data, int dataLen); + + /*** + * Debug COM port to BLE COM port. + * BLE COM port to Debug COM port. + */ + // BLE Module to Debug Serial port. + void BLE2Debug( int autoDiscon ); + // Debug Serial port to BLE Module. + char *Debug2BLE( int BLEwrite ); + + /*** + * If you first setting, you need next-function. + */ + // Restore to factory setting data. + void FactoryReset( void ); + // First setting of COM port. + void firstUartSetting( void ); }; #if 0 -#define debug_printf(...) { \ - char* __temp__ = (char*)malloc(sizeof(char)*2048); \ - sprintf(__temp__, __VA_ARGS__ ); \ - Serial.print(__temp__); \ - free(__temp__); \ +#define debug_printf(...) { \ + char* __temp__ = (char*)malloc(sizeof(char)*2048); \ + sprintf(__temp__, __VA_ARGS__ ); \ + Serial.print(__temp__); \ + free(__temp__); \ } #else #define debug_printf(...) diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.h b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.h index 41556f6..e227da3 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.h +++ b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.h @@ -1,9 +1,22 @@ -/* - * oic_lanLib.h - * - * Created on: 2014. 11. 13. - * Author: eunseok - */ +/****************************************************************** +* +* 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 OIC_LANLIB_H_ #define OIC_LANLIB_H_ diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp index c4e12d3..bd75ed5 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp +++ b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp @@ -1,578 +1,569 @@ -/* - * blsLib.cpp - * - * Created on: 2014. 11. 5. - * Author: eunseok - */ +/****************************************************************** +* +* 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 "bleLib.h" #include -#define ARDUINO 1 -//#define __INTERNAL_DEBUG__ 1 +//#define __INTERNAL_DEBUG__ 1 +#define LIMIT_COUNT 100 +#define DUMMY_SIZE 30 +#define DEBUG_SIZE DUMMY_SIZE +#define SERIAL_SIZE 100 -#define LIMIT_COUNT 100 -#define DUMMY_SIZE 30 -#define DEBUG_SIZE DUMMY_SIZE -#if (ARDUINO != 0) -#define SERIAL_SIZE 100 -#endif - -#define BLE Serial2 +#define BLE Serial2 bool isConnected = false; -int SerialCnt=0; -int BLECnt=0; +int SerialCnt = 0; +int BLECnt = 0; char SelfMaxaddr[19] = {0,}; -char debugD[DEBUG_SIZE]={0,}; +char debugD[DEBUG_SIZE] = {0,}; -#if (ARDUINO != 0) -char SerialData[SERIAL_SIZE]={0,}; -char BLEData[SERIAL_SIZE]={0,}; -#endif -// baudRate이 115200이면, 주의해야한다. -// Arduino Chip은 16bit Process 이므로 int형의 사이즈가 4byte형 signed int이다. -void Cble::init(long baudRate, int ble_mode, char* SelfMaxAddr) +char SerialData[SERIAL_SIZE] = {0,}; +char BLEData[SERIAL_SIZE] = {0,}; + + +void Cble::init(long baudRate, int ble_mode, char *SelfMaxAddr) { - debug_printf("BLE shiled is initialed.-\r\n"); - - if(SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE ) - { - debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n"); - exit(-1); - } - sprintf(SelfMaxaddr, "%s",SelfMaxAddr); - - BLE.begin(baudRate); - BLE.setTimeout(1); - delay(1000); - - memset(debugD,0,DEBUG_SIZE); - - if( ble_mode != BLE_NOCHANGE ) - { - while( IsSelfArduino() == false ) - this->pollingDisconnect(); - } - - if( ble_mode == BLE_MASTER ) - { - pollingRequest("AT+ROLE1", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+MODE0", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+NOTI0", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - } - else if ( ble_mode == BLE_SLAVER ) - { - pollingRequest("AT+ROLE0", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+MODE2", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+NOTI0", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - } - - if( ble_mode != BLE_NOCHANGE ) - { - while( IsSelfArduino() == false ) - this->pollingDisconnect(); - } - - delay(250); + debug_printf("BLE shiled is initialed.-\r\n"); + + if (SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE ) + { + debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n"); + exit(-1); + } + sprintf(SelfMaxaddr, "%s", SelfMaxAddr); + + BLE.begin(baudRate); + BLE.setTimeout(1); + delay(1000); + + memset(debugD, 0, DEBUG_SIZE); + + if ( ble_mode != BLE_NOCHANGE ) + { + while ( IsSelfArduino() == false ) + this->pollingDisconnect(); + } + + if ( ble_mode == BLE_MASTER ) + { + pollingRequest("AT+ROLE1", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+MODE0", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+NOTI0", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + } + else if ( ble_mode == BLE_SLAVER ) + { + pollingRequest("AT+ROLE0", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+MODE2", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+NOTI0", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + } + + if ( ble_mode != BLE_NOCHANGE ) + { + while ( IsSelfArduino() == false ) + this->pollingDisconnect(); + } + + delay(250); } void Cble::StatusRead( void ) { - debug_printf("StatusRead function called.\r\n"); - - pollingRequest("AT+ROLE?", debugD, 9); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+MODE?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+IMME?", debugD, 9); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+TYPE?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+POWE?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+NOTI?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+PIO1?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); + debug_printf("StatusRead function called.\r\n"); + + pollingRequest("AT+ROLE?", debugD, 9); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+MODE?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+IMME?", debugD, 9); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+TYPE?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+POWE?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+NOTI?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+PIO1?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); } bool Cble::IsConnected( void ) { - return isConnected; + return isConnected; } bool Cble::IsSelfArduino( void ) { #ifdef __INTERNAL_DEBUG__ - debug_printf("IsSelfArduino is called.\r\n"); + debug_printf("IsSelfArduino is called.\r\n"); #endif - int length=mustHaveRequest("AT+ADDR?", debugD, 20); - - if( strstr(debugD, SelfMaxaddr) ) - { - isConnected = false; - memset(debugD,0,length); - return true; - } - else - { - isConnected = true; - memset(debugD,0,length); - return false; - } + int length = mustHaveRequest("AT+ADDR?", debugD, 20); + + if ( strstr(debugD, SelfMaxaddr) ) + { + isConnected = false; + memset(debugD, 0, length); + return true; + } + else + { + isConnected = true; + memset(debugD, 0, length); + return false; + } } -bool Cble::pollingConnect( const char* maxAddr ) +bool Cble::pollingConnect( const char *maxAddr ) { #ifdef __INTERNAL_DEBUG__ - debug_printf("pollingConnect is called.\r\n"); + debug_printf("pollingConnect is called.\r\n"); #endif -#define CONNECT_SIZE 20 - - char cmd[CONNECT_SIZE]= {0,}; - - // is Connected Address ? - pollingRequest("AT+ADDR?", debugD, 20); - if( strstr(debugD, maxAddr) ) - { - isConnected = true; - memset(debugD,0,DEBUG_SIZE); - return isConnected; - } - memset(debugD,0,DEBUG_SIZE); - - // Try Connection. - sprintf(cmd, "AT+CON%s",maxAddr); - if( pollingRequest(cmd, debugD, 8) == false ) - { - debug_printf("Error : %s command is failed.\r\n",cmd ); - memset(debugD,0,DEBUG_SIZE); - pollingDisconnect(); - return false; - } - else if( strstr(debugD,"OK+CONNA") ) - { - isConnected = true; - memset(debugD,0,DEBUG_SIZE); - } - else - { - memset(debugD,0,DEBUG_SIZE); - pollingDisconnect(); - return false; - } - - // Confirm Connected Address. - pollingRequest("AT+ADDR?", debugD, 20); - - if( strstr(debugD, maxAddr) == 0 ) - { - isConnected = false; - if ( strstr(debugD, "OK+CONNF") ) - { - memset(debugD,0,DEBUG_SIZE); - streamDummy(debugD, 8); - } - } - memset(debugD,0,DEBUG_SIZE); - delay(5); - - return isConnected; +#define CONNECT_SIZE 20 + + char cmd[CONNECT_SIZE] = {0,}; + + // is Connected Address ? + pollingRequest("AT+ADDR?", debugD, 20); + if ( strstr(debugD, maxAddr) ) + { + isConnected = true; + memset(debugD, 0, DEBUG_SIZE); + return isConnected; + } + memset(debugD, 0, DEBUG_SIZE); + + // Try Connection. + sprintf(cmd, "AT+CON%s", maxAddr); + if ( pollingRequest(cmd, debugD, 8) == false ) + { + debug_printf("Error : %s command is failed.\r\n", cmd ); + memset(debugD, 0, DEBUG_SIZE); + pollingDisconnect(); + return false; + } + else if ( strstr(debugD, "OK+CONNA") ) + { + isConnected = true; + memset(debugD, 0, DEBUG_SIZE); + } + else + { + memset(debugD, 0, DEBUG_SIZE); + pollingDisconnect(); + return false; + } + + // Confirm Connected Address. + pollingRequest("AT+ADDR?", debugD, 20); + + if ( strstr(debugD, maxAddr) == 0 ) + { + isConnected = false; + if ( strstr(debugD, "OK+CONNF") ) + { + memset(debugD, 0, DEBUG_SIZE); + streamDummy(debugD, 8); + } + } + memset(debugD, 0, DEBUG_SIZE); + delay(5); + + return isConnected; #undef CONNECT_SIZE } -#define CMD_DISCONNECT "(CMD_DISCON)" +#define CMD_DISCONNECT "(CMD_DISCON)" void Cble::pollingDisconnect( void ) { #ifdef __INTERNAL_DEBUG__ - debug_printf("pollingDisconnect is called.\r\n"); -#endif - int length=0; -#if (ARDUINO == 0) - pollingRequest("\r\n" CMD_DISCONNECT "\r\n", NULL, NULL); - delay(5); - - length=mustHaveRequest("AT", debugD, 2); - if( strstr(debugD,"OK") ) - isConnected = false; - - memset(debugD,0,length); -#else - if( BLE.available() ) - { - if( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true ) - { - debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT); - - do { - debug_printf("pollingDisconnect : Send AT message.\r\n"); - if( length ) - memset(debugD, 0, length); - - length=mustHaveRequest("AT", debugD, 2); - }while( strstr(debugD,"OK") == NULL ); - - debug_printf("pollingDisconnect() is Success.\r\n"); - memset(debugD, 0, length); - } - } + debug_printf("pollingDisconnect is called.\r\n"); #endif - - delay(5); + int length = 0; + + if ( BLE.available() ) + { + if ( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true ) + { + debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT); + + do + { + debug_printf("pollingDisconnect : Send AT message.\r\n"); + if ( length ) + memset(debugD, 0, length); + + length = mustHaveRequest("AT", debugD, 2); + } + while ( strstr(debugD, "OK") == NULL ); + + debug_printf("pollingDisconnect() is Success.\r\n"); + memset(debugD, 0, length); + } + } + + delay(5); } int Cble::pollingGetRSSI( void ) { -#define RSSI_SIZE 11 -#define RSSI_POS 7 - - long time_cnt=0; - char c=0; - char index=0; - char rssi_res[RSSI_SIZE] = {0,}; - - streamDummy(NULL, NULL); - - if( isConnected == true ) - { - BLE.write("AT+RSSI?"); - BLE.flush(); - delay(5); - - while(1) - { - if ( BLE.available() ) - c = (char)BLE.read(); - else - { - c = 0; - time_cnt++; - } - - if( c ) - { - rssi_res[index] = c; - index++; - if( index == RSSI_SIZE-1 ) - { - rssi_res[index] = '\0'; - goto RESULT; - } - } - - if( time_cnt == 0xFFFFF ) - { - debug_printf("Error : Time Out GetRSSI().\r\n"); - return BLE_NODATA; - } - - } - - RESULT : +#define RSSI_SIZE 11 +#define RSSI_POS 7 + + long time_cnt = 0; + char c = 0; + char index = 0; + char rssi_res[RSSI_SIZE] = {0,}; + + streamDummy(NULL, NULL); + + if ( isConnected == true ) + { + BLE.write("AT+RSSI?"); + BLE.flush(); + delay(5); + + while (1) + { + if ( BLE.available() ) + c = (char)BLE.read(); + else + { + c = 0; + time_cnt++; + } + + if ( c ) + { + rssi_res[index] = c; + index++; + if ( index == RSSI_SIZE - 1 ) + { + rssi_res[index] = '\0'; + goto RESULT; + } + } + + // debug_printf("time_cnt=%d\r\n", time_cnt); + if ( time_cnt == 0xFFFFF ) + { + debug_printf("Error : Time Out GetRSSI().\r\n"); + return BLE_NODATA; + } + + } + +RESULT : #ifdef __INTERNAL_DEBUG__ - debug_printf("res= %s \r\n",rssi_res); + debug_printf("res= %s \r\n", rssi_res); #endif - char* Srssi = &(rssi_res[RSSI_POS]); - int rssi = atoi(Srssi); + char *Srssi = &(rssi_res[RSSI_POS]); + // debug_printf("[S] rssi=%s\r\n", Srssi); + int rssi = atoi(Srssi); + // debug_printf("rssi=%d\r\n", rssi); - return rssi; - } + return rssi; + } - return BLE_DISCON; + return BLE_DISCON; #undef RSSI_POS #undef RSSI_SIZE } -int Cble::mustHaveRequest(const char* request, char* data, int dataLen) +int Cble::mustHaveRequest(const char *request, char *data, int dataLen) { - int cnt=0; - int length=0; - int required_length = dataLen; - char* data_index = data; + int cnt = 0; + int length = 0; + int required_length = dataLen; + char *data_index = data; - BLE.write(request); - BLE.flush(); - delay(150); + BLE.write(request); + BLE.flush(); + delay(150); READ_STREAM : - while( (length=BLE.readBytes(data_index, required_length)) == 0 ) - { - cnt++; - delay(10); + while ( (length = BLE.readBytes(data_index, required_length)) == 0 ) + { + cnt++; + delay(10); - if ( cnt >= LIMIT_COUNT/10 ) - { + if ( cnt >= LIMIT_COUNT / 10 ) + { #ifdef __INTERNAL_DEBUG__ - debug_printf("=====> Retry Request command Send. <=========\r\n"); + debug_printf("=====> Retry Request command Send. <=========\r\n"); #endif - cnt = 0; - BLE.write(request); - BLE.flush(); - - required_length = dataLen; - data_index = data; - length = 0; - delay(50); - } - } - - required_length -= length; - if( required_length != 0 ) - { - data_index = data_index + length; - length = 0; - goto READ_STREAM; - } + cnt = 0; + BLE.write(request); + BLE.flush(); + + required_length = dataLen; + data_index = data; + length = 0; + delay(50); + } + } + + required_length -= length; + if ( required_length != 0 ) + { + data_index = data_index + length; + length = 0; + goto READ_STREAM; + } #ifdef __INTERNAL_DEBUG__ - debug_printf("[ %s ] %s\r\n\r\n", request, data); + debug_printf("[ %s ] %s\r\n\r\n", request, data); #endif - return dataLen; + return dataLen; } -bool Cble::pollingRequest(const char* request, char* data, int dataLen) +bool Cble::pollingRequest(const char *request, char *data, int dataLen) { - int cnt=0; - int length=0; - int required_length = dataLen; - char* data_index = data; + int cnt = 0; + int length = 0; + int required_length = dataLen; + char *data_index = data; - BLE.write(request); - BLE.flush(); + BLE.write(request); + BLE.flush(); - if( data_index ) - { - delay(250); + if ( data_index ) + { + delay(250); READ_STREAM : - while( (length=BLE.readBytes(data_index, required_length)) == 0 ) - { - cnt++; - if ( cnt >= LIMIT_COUNT ) - { - debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request); - return false; - } - } - - required_length -= length; - if( required_length != 0 ) - { - data_index = data_index + length; - length = 0; - goto READ_STREAM; - } + while ( (length = BLE.readBytes(data_index, required_length)) == 0 ) + { + cnt++; + if ( cnt >= LIMIT_COUNT ) + { + debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request); + return false; + } + } + + required_length -= length; + if ( required_length != 0 ) + { + data_index = data_index + length; + length = 0; + goto READ_STREAM; + } #ifdef __INTERNAL_DEBUG__ - debug_printf("[ %s ] %s\r\n\r\n", request, data); + debug_printf("[ %s ] %s\r\n\r\n", request, data); #endif - } - return true; + } + return true; } -void Cble::streamDummy( char* data, int dataLen) +void Cble::streamDummy( char *data, int dataLen) { - int cnt=0; - int length=0; - int required_length = dataLen; - char* data_index = data; + int cnt = 0; + int length = 0; + int required_length = dataLen; + char *data_index = data; - if( data && required_length ) - { + if ( data && required_length ) + { READ_STREAM : - while( (length=BLE.readBytes(data_index, required_length)) == 0 ) - { - cnt++; - if ( cnt >= LIMIT_COUNT ) - { - debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n"); - return ; - } - } - - required_length -= length; - if( required_length != 0 ) - { - data_index = data_index + length; - length = 0; - goto READ_STREAM; - } - - debug_printf("[ streamDummy ] %s\r\n\r\n", data); - } - else - { - if( BLE.available() ) - { - BLE.readBytes(debugD, DEBUG_SIZE); + while ( (length = BLE.readBytes(data_index, required_length)) == 0 ) + { + cnt++; + if ( cnt >= LIMIT_COUNT ) + { + debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n"); + return ; + } + } + + required_length -= length; + if ( required_length != 0 ) + { + data_index = data_index + length; + length = 0; + goto READ_STREAM; + } + + debug_printf("[ streamDummy ] %s\r\n\r\n", data); + } + else + { + if ( BLE.available() ) + { + BLE.readBytes(debugD, DEBUG_SIZE); #ifdef __INTERNAL_DEBUG__ - debug_printf("[ streamDummy ] %s\r\n\r\n", debugD); + debug_printf("[ streamDummy ] %s\r\n\r\n", debugD); #endif - memset(debugD, 0, DEBUG_SIZE); - } - } + memset(debugD, 0, DEBUG_SIZE); + } + } } -#if (ARDUINO != 0) -#define REGARD_DISCON 5000 +#define REGARD_DISCON 5000 int needDiscon = 0; unsigned long global_cnt = 0; void Cble::BLE2Debug( int autoDiscon ) { - int cnt=0; - uint8_t length=0; - - if( BLE.available() ) - { - while( (length=BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 ) - { - cnt++; - if ( cnt >= LIMIT_COUNT ) - return ; - } - - global_cnt = 0; - needDiscon = 0; - - Serial.println(BLEData); - memset(BLEData, 0, length); - } - else if ( autoDiscon ) - { - global_cnt++; -// debug_printf("global_cnt=%u , ", global_cnt ); -// debug_printf("needDiscon=%d\r\n", needDiscon); - if( !needDiscon && global_cnt >= REGARD_DISCON ) - { - needDiscon = 1; - debug_printf("result : global_cnt=%u , ", global_cnt ); - debug_printf("needDiscon=%d\r\n", needDiscon); - } - - if ( needDiscon ) - { - debug_printf("Auto Discon : global_cnt=%u , ", global_cnt ); - debug_printf("needDiscon=%d\r\n", needDiscon); - if( pollingRequest("AT", debugD, 2) == true ) - { - global_cnt = 0; - needDiscon = 0; - } - } - } + int cnt = 0; + uint8_t length = 0; + + if ( BLE.available() ) + { + while ( (length = BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 ) + { + cnt++; + if ( cnt >= LIMIT_COUNT ) + return ; + } + + global_cnt = 0; + needDiscon = 0; + + Serial.println(BLEData); + memset(BLEData, 0, length); + } + else if ( autoDiscon ) + { + global_cnt++; +// debug_printf("global_cnt=%u , ", global_cnt ); +// debug_printf("needDiscon=%d\r\n", needDiscon); + if ( !needDiscon && global_cnt >= REGARD_DISCON ) + { + needDiscon = 1; + debug_printf("result : global_cnt=%u , ", global_cnt ); + debug_printf("needDiscon=%d\r\n", needDiscon); + } + + if ( needDiscon ) + { + debug_printf("Auto Discon : global_cnt=%u , ", global_cnt ); + debug_printf("needDiscon=%d\r\n", needDiscon); + if ( pollingRequest("AT", debugD, 2) == true ) + { + global_cnt = 0; + needDiscon = 0; + } + } + } } -char* Cble::Debug2BLE( int BLEwrite ) +char *Cble::Debug2BLE( int BLEwrite ) { - char* result = NULL; - - if( Serial.available() ) - { - char c = (char)Serial.read(); - - switch(c) - { - case '\0': - return result; - case '\r': - case '\n': - debug_printf("\r\n"); - if(BLEwrite && SerialCnt) - { - BLE.write(SerialData); - BLE.flush(); - } - - result = (char*)malloc(sizeof(char)*(SerialCnt+1)); - memcpy(result, SerialData, SerialCnt ); - result[SerialCnt] = NULL; - - memset(SerialData, 0, SerialCnt+1); - SerialCnt=0; - break; - default : - SerialData[SerialCnt] = c; - SerialCnt++; - Serial.print(c); - break; - } - } - - return result; -} -#else -void Cble::BLE2Debug( int autoDiscon ) -{ - ; + char *result = NULL; + + if ( Serial.available() ) + { + char c = (char)Serial.read(); + + switch (c) + { + case '\0': + return result; + case '\r': + case '\n': + debug_printf("\r\n"); + if (BLEwrite && SerialCnt) + { + BLE.write(SerialData); + BLE.flush(); + } + + result = (char *)malloc(sizeof(char) * (SerialCnt + 1)); + memcpy(result, SerialData, SerialCnt ); + result[SerialCnt] = NULL; + + memset(SerialData, 0, SerialCnt + 1); + SerialCnt = 0; + break; + default : + SerialData[SerialCnt] = c; + SerialCnt++; + Serial.print(c); + break; + } + } + + return result; } -char* Cble::Debug2BLE( int BLEwrite ) -{ - return NULL; -} -#endif void Cble::FactoryReset( void ) { - debug_printf("FactoryReset is called.\r\n"); + debug_printf("FactoryReset is called.\r\n"); - pollingRequest("AT+RENEW", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); + pollingRequest("AT+RENEW", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); } void Cble::firstUartSetting( void ) { - debug_printf("firstUartSetting is called.\r\n"); + debug_printf("firstUartSetting is called.\r\n"); - Serial.begin(9600); - BLE.begin(9600); - BLE.setTimeout(1); - delay(1000); + Serial.begin(9600); + BLE.begin(9600); + BLE.setTimeout(1); + delay(1000); - pollingRequest("AT+BAUD4", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); + pollingRequest("AT+BAUD4", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); - debug_printf("Please Power off and on.\r\n"); - BLE.end(); -// delay(1000); + debug_printf("Please Power off and on.\r\n"); + BLE.end(); +// delay(1000); // -// BLE.begin(115200); -// delay(1000); +// BLE.begin(115200); +// delay(1000); // -// pollingRequest("AT", debugD, DEBUG_SIZE); -// memset(debugD, 0, DEBUG_SIZE); +// pollingRequest("AT", debugD, DEBUG_SIZE); +// memset(debugD, 0, DEBUG_SIZE); - exit(0); + exit(0); } diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp index c4a4f26..2497906 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp +++ b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp @@ -1,9 +1,22 @@ -/* - * oic_wifiLib.cpp - * - * Created on: 2014. 11. 13. - * Author: eunseok - */ +/****************************************************************** +* +* 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 "logger.h" #include "ocstack.h" @@ -27,7 +40,7 @@ #endif -PROGMEM const char TAG[] = "ReferenceSensor"; +PROGMEM const char TAG[] = "TrackeeSensor"; #ifdef ARDUINOWIFI // Arduino WiFi Shield @@ -38,10 +51,10 @@ PROGMEM const char TAG[] = "ReferenceSensor"; static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0"; /// WiFi network info and credentials -char ssid[] = "SoftSensor_AP"; -char pass[] = "1234567890"; -//char ssid[] = "SoftSensor_2.4G"; -//char pass[] = "12344321"; +//char ssid[] = "SoftSensor_AP"; +//char pass[] = "1234567890"; +char ssid[] = "SoftSensor_2.4G"; +char pass[] = "12344321"; int ConnectToNetwork() { @@ -57,7 +70,7 @@ int ConnectToNetwork() // Verify that WiFi Shield is running the firmware with all UDP fixes fwVersion = WiFi.firmwareVersion(); OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion); - if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 ) + if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) != 0 ) { OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!")); return -1; @@ -67,7 +80,7 @@ int ConnectToNetwork() while (status != WL_CONNECTED) { OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid); - status = WiFi.begin(ssid,pass); + status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/reference.cpp b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/reference.cpp index 953032e..6161700 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/reference.cpp +++ b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/reference.cpp @@ -1,22 +1,22 @@ -//****************************************************************** -// -// 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +/****************************************************************** +* +* 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. +* +******************************************************************/ // Do not remove the include below #include "Arduino.h" @@ -28,7 +28,7 @@ #include #include "oic_lanLib.h" - +//#define ARDUINOWIFI 1 #define ARDUINO_AVR_MEGA2560 1 /// This is the port which Arduino Server will use for all unicast communication with it's peers #define OC_WELL_KNOWN_PORT 5683 @@ -38,10 +38,11 @@ #define JSON_BASE02 "\",\"3\":\"SERVICETYPE\",\"4\":\"string\",\"5\":\"" #define JSON_BASE03 "\"}}" -typedef struct REFERRESOURCE { +typedef struct REFERRESOURCE +{ OCResourceHandle m_handle; - char* m_macaddress; - char* m_servicetype; + char *m_macaddress; + char *m_servicetype; } REFERResource; PROGMEM const char TAG[] = "ReferenceSensor"; @@ -49,31 +50,33 @@ PROGMEM const char TAG[] = "ReferenceSensor"; REFERResource REFER; Cble ble; -char macaddress[13]={"9059AF1704D7"}; -char servicetype[15]={"BOOK"}; +//char macaddress[13]={"9059AF1704D7"}; +//char macaddress[13]={"9059AF1700EE"}; R1 +char macaddress[13] = {"34B1F7D004D2"}; +//char macaddress[13]={"9059AF170C1D"}; +char servicetype[15] = {"BOOKLight"}; int g_REFERUnderObservation = 0; const char *getResult(OCStackResult result); void createREFERResource(); -#define LENGTH_VAR 100 +#define LENGTH_VAR 100 static int base_length = 0; - -bool JsonGenerator( REFERResource& ref, char* jsonBuf, uint16_t buf_length ) +bool JsonGenerator( REFERResource &ref, char *jsonBuf, uint16_t buf_length ) { - if( (buf_length - base_length) < LENGTH_VAR ) - { - OC_LOG_V(ERROR, TAG, "Error : length is very long."); - return false; - } + if ( (buf_length - base_length) < LENGTH_VAR ) + { + OC_LOG_V(ERROR, TAG, "Error : length is very long."); + return false; + } - sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%s",ref.m_macaddress); - sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03, ref.m_servicetype); + sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%s", ref.m_macaddress); + sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03, ref.m_servicetype); - Serial.println(jsonBuf); + Serial.println(jsonBuf); - return true; + return true; } // On Arduino Atmel boards with Harvard memory architecture, the stack grows @@ -97,68 +100,46 @@ void PrintArduinoMemoryStats() // This is the entity handler for the registered resource. // This is invoked by OCStack whenever it recevies a request for this resource. -OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest ) +OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest ) { OCEntityHandlerResult ehRet = OC_EH_OK; - OCEntityHandlerResponse response = {0}; - char payload[MAX_RESPONSE_LENGTH] = {0}; - if(entityHandlerRequest && (flag & OC_REQUEST_FLAG)) + if (entityHandlerRequest && (flag & OC_REQUEST_FLAG)) { OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG")); - if(OC_REST_GET == entityHandlerRequest->method) + if (OC_REST_GET == entityHandlerRequest->method) { - if(JsonGenerator( REFER, payload, MAX_RESPONSE_LENGTH)) - { - } - else + if (JsonGenerator( REFER, (char *)entityHandlerRequest->resJSONPayload, \ + entityHandlerRequest->resJSONPayloadLen)) + { + } + else { ehRet = OC_EH_ERROR; } } - if(OC_REST_PUT == entityHandlerRequest->method) + if (OC_REST_PUT == entityHandlerRequest->method) { //Do something with the 'put' payload - if (JsonGenerator( REFER, payload, MAX_RESPONSE_LENGTH)) + if (JsonGenerator( REFER, (char *)entityHandlerRequest->resJSONPayload, \ + entityHandlerRequest->resJSONPayloadLen)) { } else { ehRet = OC_EH_ERROR; } - } - } - - if (ehRet == OC_EH_OK) - { - // Format the response. Note this requires some info about the request - response.requestHandle = entityHandlerRequest->requestHandle; - response.resourceHandle = entityHandlerRequest->resource; - response.ehResult = ehRet; - response.payload = (unsigned char *)payload; - response.payloadSize = strlen(payload); - response.numSendVendorSpecificHeaderOptions = 0; - memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); - memset(response.resourceUri, 0, sizeof response.resourceUri); - // Indicate that response is NOT in a persistent buffer - response.persistentBufferFlag = 0; - - // Send the response - if (OCDoResponse(&response) != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, "Error sending response"); - ehRet = OC_EH_ERROR; - } + } } - if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) { - if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) + if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action) { OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client")); g_REFERUnderObservation = 1; } - else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) + else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action) { OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client")); } @@ -171,62 +152,62 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle char tempdata[200]; void ChangeREFERRepresentation (void *param) { - (void)param; - OCStackResult result = OC_STACK_ERROR; - result = OCNotifyAllObservers (REFER.m_handle, OC_NA_QOS); + (void)param; + OCStackResult result = OC_STACK_ERROR; + result = OCNotifyAllObservers (REFER.m_handle, OC_NA_QOS); - OC_LOG_V(INFO, TAG, "%s", JsonGenerator( REFER, tempdata, 200)); + OC_LOG_V(INFO, TAG, "%s", JsonGenerator( REFER, tempdata, 200)); - if (OC_STACK_NO_OBSERVERS == result) - { - OC_LOG_V(INFO, TAG, "g_REFERUnderObservation is 0." ); - g_REFERUnderObservation = 0; - } + if (OC_STACK_NO_OBSERVERS == result) + { + OC_LOG_V(INFO, TAG, "g_REFERUnderObservation is 0." ); + g_REFERUnderObservation = 0; + } } //The setup function is called once at startup of the sketch void setup() { - Serial.begin(115200); + Serial.begin(115200); - REFER.m_macaddress = macaddress; - REFER.m_servicetype = servicetype; + REFER.m_macaddress = macaddress; + REFER.m_servicetype = servicetype; - // Add your initialization code here - OC_LOG_INIT(); + // Add your initialization code here + OC_LOG_INIT(); - OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); + OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); - // Connect to Ethernet or WiFi network - if (ConnectToNetwork() != 0) - { - OC_LOG(ERROR, TAG, "Unable to connect to network"); - return; - } + // Connect to Ethernet or WiFi network + if (ConnectToNetwork() != 0) + { + OC_LOG(ERROR, TAG, "Unable to connect to network"); + return; + } - // Initialize the OC Stack in Server mode - if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("OCStack init error")); - return; - } + // Initialize the OC Stack in Server mode + if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack init error")); + return; + } OCStartPresence(60); - // Declare and create the example resource: PROXI - createREFERResource(); + // Declare and create the example resource: PROXI + createREFERResource(); - ble.init( (long)115200, BLE_SLAVER, REFER.m_macaddress); + ble.init( (long)115200, BLE_SLAVER, REFER.m_macaddress); -// ble.StatusRead(); +// ble.StatusRead(); - char str0[] = JSON_BASE00; - char str1[] = JSON_BASE01; - char str2[] = JSON_BASE02; - char str3[] = JSON_BASE03; + char str0[] = JSON_BASE00; + char str1[] = JSON_BASE01; + char str2[] = JSON_BASE02; + char str3[] = JSON_BASE03; - base_length = strlen(str0)+ strlen(str1)+ strlen(str2)+ strlen(str3); + base_length = strlen(str0) + strlen(str1) + strlen(str2) + strlen(str3); - OC_LOG_V(INFO, TAG, "Program Start-\r\n"); + OC_LOG_V(INFO, TAG, "Program Start-\r\n"); } // The loop function is called in an endless loop @@ -237,72 +218,75 @@ void loop() // This call displays the amount of free SRAM available on Arduino PrintArduinoMemoryStats(); - delay(5000); - if (OCProcess() != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("OCStack process error")); - return; - } - ChangeREFERRepresentation(NULL); - - char* user_msg = NULL; - user_msg = ble.Debug2BLE( true ); - ble.BLE2Debug( true ); - - if ( user_msg ) - { - free( user_msg ); - user_msg = NULL; - } + delay(5000); + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack process error")); + return; + } + ChangeREFERRepresentation(NULL); + + char *user_msg = NULL; + user_msg = ble.Debug2BLE( true ); + ble.BLE2Debug( true ); + + if ( user_msg ) + { + free( user_msg ); + user_msg = NULL; + } } -void createREFERResource() { +void createREFERResource() +{ OCStackResult res = OCCreateResource(&REFER.m_handle, "SoftSensorManager.Sensor", "oc.mi.def", "/Reference_Thing", OCEntityHandlerCb, - OC_DISCOVERABLE|OC_OBSERVABLE); + OC_DISCOVERABLE | OC_OBSERVABLE); OC_LOG_V(INFO, TAG, "Created REFER resource with result: %s", getResult(res)); } -const char *getResult(OCStackResult result) { - switch (result) { - case OC_STACK_OK: - return "OC_STACK_OK"; - case OC_STACK_INVALID_URI: - return "OC_STACK_INVALID_URI"; - case OC_STACK_INVALID_QUERY: - return "OC_STACK_INVALID_QUERY"; - case OC_STACK_INVALID_IP: - return "OC_STACK_INVALID_IP"; - case OC_STACK_INVALID_PORT: - return "OC_STACK_INVALID_PORT"; - case OC_STACK_INVALID_CALLBACK: - return "OC_STACK_INVALID_CALLBACK"; - case OC_STACK_INVALID_METHOD: - return "OC_STACK_INVALID_METHOD"; - case OC_STACK_NO_MEMORY: - return "OC_STACK_NO_MEMORY"; - case OC_STACK_COMM_ERROR: - return "OC_STACK_COMM_ERROR"; - case OC_STACK_INVALID_PARAM: - return "OC_STACK_INVALID_PARAM"; - case OC_STACK_NOTIMPL: - return "OC_STACK_NOTIMPL"; - case OC_STACK_NO_RESOURCE: - return "OC_STACK_NO_RESOURCE"; - case OC_STACK_RESOURCE_ERROR: - return "OC_STACK_RESOURCE_ERROR"; - case OC_STACK_SLOW_RESOURCE: - return "OC_STACK_SLOW_RESOURCE"; - case OC_STACK_NO_OBSERVERS: - return "OC_STACK_NO_OBSERVERS"; - case OC_STACK_ERROR: - return "OC_STACK_ERROR"; - default: - return "UNKNOWN"; +const char *getResult(OCStackResult result) +{ + switch (result) + { + case OC_STACK_OK: + return "OC_STACK_OK"; + case OC_STACK_INVALID_URI: + return "OC_STACK_INVALID_URI"; + case OC_STACK_INVALID_QUERY: + return "OC_STACK_INVALID_QUERY"; + case OC_STACK_INVALID_IP: + return "OC_STACK_INVALID_IP"; + case OC_STACK_INVALID_PORT: + return "OC_STACK_INVALID_PORT"; + case OC_STACK_INVALID_CALLBACK: + return "OC_STACK_INVALID_CALLBACK"; + case OC_STACK_INVALID_METHOD: + return "OC_STACK_INVALID_METHOD"; + case OC_STACK_NO_MEMORY: + return "OC_STACK_NO_MEMORY"; + case OC_STACK_COMM_ERROR: + return "OC_STACK_COMM_ERROR"; + case OC_STACK_INVALID_PARAM: + return "OC_STACK_INVALID_PARAM"; + case OC_STACK_NOTIMPL: + return "OC_STACK_NOTIMPL"; + case OC_STACK_NO_RESOURCE: + return "OC_STACK_NO_RESOURCE"; + case OC_STACK_RESOURCE_ERROR: + return "OC_STACK_RESOURCE_ERROR"; + case OC_STACK_SLOW_RESOURCE: + return "OC_STACK_SLOW_RESOURCE"; + case OC_STACK_NO_OBSERVERS: + return "OC_STACK_NO_OBSERVERS"; + case OC_STACK_ERROR: + return "OC_STACK_ERROR"; + default: + return "UNKNOWN"; } } diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/trackee.cpp b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/trackee.cpp new file mode 100644 index 0000000..b1055af --- /dev/null +++ b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/trackee.cpp @@ -0,0 +1,263 @@ +//****************************************************************** +// +// 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// Do not remove the include below +#include "Arduino.h" +#include "bleLib.h" +#include + +#include "logger.h" +#include "ocstack.h" +#include + +#include "oic_lanLib.h" + +// proximity code s +#define DATA_EA 400 +#define SLAVER_EA 2 + +#define ARDUINO_AVR_MEGA2560 1 +/// This is the port which Arduino Server will use for all unicast communication with it's peers +#define OC_WELL_KNOWN_PORT 5683 + +PROGMEM const char TAG[] = "TrackeeSensor"; + +OCResourceHandle m_handle; + + + +Cble ble; +char trackeeID[13] = "9059AF16FEF7"; +int slaver_num = 0; +//char slaveList[SLAVER_EA][13]={"9059AF1700EE"}; +char slaveList[SLAVER_EA][13] = {"9059AF1700EE", "34B1F7D004D2"}; +int g_PROXIUnderObservation = 0; + + + +const char *getResult(OCStackResult result); +void createResource(); + + +#define LENGTH_VAR 50 +bool JsonGenerator( char *jsonBuf, uint16_t buf_length ) +{ + + return true; + +} + + +// On Arduino Atmel boards with Harvard memory architecture, the stack grows +// downwards from the top and the heap grows upwards. This method will print +// the distance(in terms of bytes) between those two. +// See here for more details : +// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html +void PrintArduinoMemoryStats() +{ +#ifdef ARDUINO_AVR_MEGA2560 + //This var is declared in avr-libc/stdlib/malloc.c + //It keeps the largest address not allocated for heap + extern char *__brkval; + //address of tmp gives us the current stack boundry + int tmp; + OC_LOG_V(INFO, TAG, "Stack: %u Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval); + OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u", + ((unsigned int)&tmp - (unsigned int)__brkval)); +#endif +} + +// This is the entity handler for the registered resource. +// This is invoked by OCStack whenever it recevies a request for this resource. +OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest ) +{ + OCEntityHandlerResult ehRet = OC_EH_OK; + + if (entityHandlerRequest && (flag & OC_REQUEST_FLAG)) + { + OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG")); + if (OC_REST_GET == entityHandlerRequest->method) + { + if ( JsonGenerator( (char *)entityHandlerRequest->resJSONPayload, + entityHandlerRequest->resJSONPayloadLen ) == false ) + { + ehRet = OC_EH_ERROR; + } + } + if (OC_REST_PUT == entityHandlerRequest->method) + { + if (JsonGenerator( (char *)entityHandlerRequest->resJSONPayload, + entityHandlerRequest->resJSONPayloadLen ) == false ) + { + ehRet = OC_EH_ERROR; + } + } + } + else if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) + { + if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action) + { + OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client")); + g_PROXIUnderObservation = 1; + } + else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action) + { + OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client")); + } + } + + Serial.println((char *)entityHandlerRequest->resJSONPayload); + + return ehRet; +} + + + + + + + +//The setup function is called once at startup of the sketch +void setup() +{ + Serial.begin(115200); + + // Add your initialization code here + OC_LOG_INIT(); + + OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); + // uint16_t port = OC_WELL_KNOWN_PORT; + + // Connect to Ethernet or WiFi network + if (ConnectToNetwork() != 0) + { + OC_LOG(ERROR, TAG, "Unable to connect to network"); + return; + } + + // Initialize the OC Stack in Server mode + if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack init error")); + return; + } + + // Declare and create the example resource + createResource(); + + // This call displays the amount of free SRAM available on Arduino + PrintArduinoMemoryStats(); + + ble.init( (long)115200, BLE_SLAVER, slaveList[0]); + + +// ble.StatusRead(); + + OC_LOG_V(INFO, TAG, "Program Start-\r\n"); +} + + +// The loop function is called in an endless loop +void loop() +{ + // This artificial delay is kept here to avoid endless spinning + // of Arduino microcontroller. Modify it as per specfic application needs. + + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack process error")); + return; + } + + char *user_cmd = NULL; + +// ble.pollingDisconnect(); + + user_cmd = ble.Debug2BLE(true); + ble.BLE2Debug( true ); + + if ( user_cmd ) + { + free( user_cmd ); + user_cmd = NULL; + } + +} + + + + + + + +void createResource() +{ + + OCStackResult res = OCCreateResource(&m_handle, + "SoftSensorManager.Sensor", + "oc.mi.def", + "/Tracker_Thing", + OCEntityHandlerCb, + OC_DISCOVERABLE | OC_OBSERVABLE); + OC_LOG_V(INFO, TAG, "Created PROXI resource with result: %s", getResult(res)); +} + +const char *getResult(OCStackResult result) +{ + switch (result) + { + case OC_STACK_OK: + return "OC_STACK_OK"; + case OC_STACK_INVALID_URI: + return "OC_STACK_INVALID_URI"; + case OC_STACK_INVALID_QUERY: + return "OC_STACK_INVALID_QUERY"; + case OC_STACK_INVALID_IP: + return "OC_STACK_INVALID_IP"; + case OC_STACK_INVALID_PORT: + return "OC_STACK_INVALID_PORT"; + case OC_STACK_INVALID_CALLBACK: + return "OC_STACK_INVALID_CALLBACK"; + case OC_STACK_INVALID_METHOD: + return "OC_STACK_INVALID_METHOD"; + case OC_STACK_NO_MEMORY: + return "OC_STACK_NO_MEMORY"; + case OC_STACK_COMM_ERROR: + return "OC_STACK_COMM_ERROR"; + case OC_STACK_INVALID_PARAM: + return "OC_STACK_INVALID_PARAM"; + case OC_STACK_NOTIMPL: + return "OC_STACK_NOTIMPL"; + case OC_STACK_NO_RESOURCE: + return "OC_STACK_NO_RESOURCE"; + case OC_STACK_RESOURCE_ERROR: + return "OC_STACK_RESOURCE_ERROR"; + case OC_STACK_SLOW_RESOURCE: + return "OC_STACK_SLOW_RESOURCE"; + case OC_STACK_NO_OBSERVERS: + return "OC_STACK_NO_OBSERVERS"; + case OC_STACK_ERROR: + return "OC_STACK_ERROR"; + default: + return "UNKNOWN"; + } +} + diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h index 8356098..a543229 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h +++ b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h @@ -1,82 +1,95 @@ -/* - * bleLib.h - * - * Created on: 2014. 11. 5. - * Author: eunseok - */ +/****************************************************************** +* +* 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 BLELIB_H_ #define BLELIB_H_ #include "Arduino.h" -#define BLE_NOCHANGE -1 -#define BLE_MASTER 1 -#define BLE_SLAVER 0 +#define BLE_NOCHANGE -1 +#define BLE_MASTER 1 +#define BLE_SLAVER 0 -#define BLE_DISCON 200 -#define BLE_NODATA 100 +#define BLE_DISCON 200 +#define BLE_NODATA 100 /*************************************** * - * HM-10 BLE Module Control Class. - * Target Board : Arduino-Mega. + * HM-10 BLE Module Control Class. + * Target Board : Arduino-Mega. * **************************************/ class Cble { -public : - /*** - * BLE Control Function. - */ - // BLE initialization ( COM baud rate , BLE Master , Slave setting. ) - void init(long baudRate, int ble_mode, char* SelfMaxAddr); - - void StatusRead( void ); - - bool IsSelfArduino( void ); - - bool IsConnected( void ); - - bool pollingConnect( const char* maxAddr ); - - void pollingDisconnect( void ); - // Get RSSI by BLE communication. (polling method.) - int pollingGetRSSI( void ); - // Send Request to BLE Module. And, Get the response. (polling method.) - bool pollingRequest(const char* request, char* data, int dataLen); - - int mustHaveRequest(const char* request, char* data, int dataLen); - - void streamDummy( char* data, int dataLen); - - /*** - * Debug COM port to BLE COM port. - * BLE COM port to Debug COM port. - */ - // BLE Module to Debug Serial port. - void BLE2Debug( int autoDiscon ); - // Debug Serial port to BLE Module. - char* Debug2BLE( int BLEwrite ); - - /*** - * If you first setting, you need next-function. - */ - // Restore to factory setting data. - void FactoryReset( void ); - // First setting of COM port. - void firstUartSetting( void ); + public : + /*** + * BLE Control Function. + */ + // BLE initialization ( COM baud rate , BLE Master , Slave setting. ) + void init(long baudRate, int ble_mode, char *SelfMaxAddr); + + void StatusRead( void ); + + bool IsSelfArduino( void ); + + bool IsConnected( void ); + + bool pollingConnect( const char *maxAddr ); + + void pollingDisconnect( void ); + // Get RSSI by BLE communication. (polling method.) + int pollingGetRSSI( void ); + // Send Request to BLE Module. And, Get the response. (polling method.) + bool pollingRequest(const char *request, char *data, int dataLen); + + int mustHaveRequest(const char *request, char *data, int dataLen); + + void streamDummy( char *data, int dataLen); + + /*** + * Debug COM port to BLE COM port. + * BLE COM port to Debug COM port. + */ + // BLE Module to Debug Serial port. + void BLE2Debug( int autoDiscon ); + // Debug Serial port to BLE Module. + char *Debug2BLE( int BLEwrite ); + + /*** + * If you first setting, you need next-function. + */ + // Restore to factory setting data. + void FactoryReset( void ); + // First setting of COM port. + void firstUartSetting( void ); }; #if 0 -#define debug_printf(...) { \ - char* __temp__ = (char*)malloc(sizeof(char)*2048); \ - sprintf(__temp__, __VA_ARGS__ ); \ - Serial.print(__temp__); \ - free(__temp__); \ +#define debug_printf(...) { \ + char* __temp__ = (char*)malloc(sizeof(char)*2048); \ + sprintf(__temp__, __VA_ARGS__ ); \ + Serial.print(__temp__); \ + free(__temp__); \ } #else #define debug_printf(...) diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h index 8e8666a..6d323ad 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h +++ b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h @@ -1,18 +1,31 @@ -/* - * proximity.h - * - * Created on: 2014. 11. 13. - * Author: eunseok - */ +/****************************************************************** +* +* 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 PROXIMITY_H_ #define PROXIMITY_H_ -#define arraysize 6 -#define RSSI_EA 3 +#define arraysize 6 +#define RSSI_EA 3 -float CalculateExponentialAverage(int numberOfSamples, int* array, int startindex, int flag); +float CalculateExponentialAverage(int numberOfSamples, int *array, int startindex, int flag); float calculateDistance(float avgRSSI, float txPower); diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h index 4271904..a1cd5f4 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h +++ b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h @@ -1,15 +1,28 @@ -/* - * trackee.h - * - * Created on: 2014. 11. 18. - * Author: eunseok - */ +/****************************************************************** +* +* 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 TRACKEE_H_ #define TRACKEE_H_ -#define ARDUINO 0 +#define ARDUINO 0 #endif /* TRACKEE_H_ */ diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp index 31cf5da..a9ad9df 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp +++ b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp @@ -1,580 +1,593 @@ -/* - * blsLib.cpp - * - * Created on: 2014. 11. 5. - * Author: eunseok - */ +/****************************************************************** +* +* 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 "bleLib.h" #include #include "trackee.h" -//#define __INTERNAL_DEBUG__ 1 +//#define __INTERNAL_DEBUG__ 1 PROGMEM const char TAG[] = "TrackeeSensor"; -#define LIMIT_COUNT 100 -#define DUMMY_SIZE 30 -#define DEBUG_SIZE DUMMY_SIZE +#define LIMIT_COUNT 100 +#define DUMMY_SIZE 30 +#define DEBUG_SIZE DUMMY_SIZE #if (ARDUINO != 0) -#define SERIAL_SIZE 100 +#define SERIAL_SIZE 100 #endif -#define BLE Serial2 +#define BLE Serial2 bool isConnected = false; -int SerialCnt=0; -int BLECnt=0; +int SerialCnt = 0; +int BLECnt = 0; char SelfMaxaddr[19] = {0,}; -char debugD[DEBUG_SIZE]={0,}; +char debugD[DEBUG_SIZE] = {0,}; #if (ARDUINO != 0) -char SerialData[SERIAL_SIZE]={0,}; -char BLEData[SERIAL_SIZE]={0,}; +char SerialData[SERIAL_SIZE] = {0,}; +char BLEData[SERIAL_SIZE] = {0,}; #endif -// baudRate이 115200이면, 주의해야한다. -// Arduino Chip은 16bit Process 이므로 int형의 사이즈가 4byte형 signed int이다. -void Cble::init(long baudRate, int ble_mode, char* SelfMaxAddr) +void Cble::init(long baudRate, int ble_mode, char *SelfMaxAddr) { - debug_printf("BLE shiled is initialed.-\r\n"); - - if(SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE ) - { - debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n"); - exit(-1); - } - sprintf(SelfMaxaddr, "%s",SelfMaxAddr); - - BLE.begin(baudRate); - BLE.setTimeout(1); - delay(1000); - - memset(debugD,0,DEBUG_SIZE); - - if( ble_mode != BLE_NOCHANGE ) - { - while( IsSelfArduino() == false ) - this->pollingDisconnect(); - } - - if( ble_mode == BLE_MASTER ) - { - pollingRequest("AT+ROLE1", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+MODE0", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+NOTI0", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - } - else if ( ble_mode == BLE_SLAVER ) - { - pollingRequest("AT+ROLE0", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+MODE2", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+NOTI0", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - } - - if( ble_mode != BLE_NOCHANGE ) - { - while( IsSelfArduino() == false ) - this->pollingDisconnect(); - } - - delay(250); + debug_printf("BLE shiled is initialed.-\r\n"); + + if (SelfMaxAddr == NULL && ble_mode != BLE_NOCHANGE ) + { + debug_printf("Error : Insert Maxaddress of Arduino BLE shiled.\r\n"); + exit(-1); + } + sprintf(SelfMaxaddr, "%s", SelfMaxAddr); + + BLE.begin(baudRate); + BLE.setTimeout(1); + delay(1000); + + memset(debugD, 0, DEBUG_SIZE); + + if ( ble_mode != BLE_NOCHANGE ) + { + while ( IsSelfArduino() == false ) + this->pollingDisconnect(); + } + + if ( ble_mode == BLE_MASTER ) + { + pollingRequest("AT+ROLE1", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+MODE0", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+NOTI0", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + } + else if ( ble_mode == BLE_SLAVER ) + { + pollingRequest("AT+ROLE0", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+MODE2", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+NOTI0", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + } + + if ( ble_mode != BLE_NOCHANGE ) + { + while ( IsSelfArduino() == false ) + this->pollingDisconnect(); + } + + delay(250); } void Cble::StatusRead( void ) { - debug_printf("StatusRead function called.\r\n"); - - pollingRequest("AT+ROLE?", debugD, 9); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+MODE?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+IMME?", debugD, 9); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+TYPE?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+POWE?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+NOTI?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); - pollingRequest("AT+PIO1?", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); - delay(150); + debug_printf("StatusRead function called.\r\n"); + + pollingRequest("AT+ROLE?", debugD, 9); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+MODE?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+IMME?", debugD, 9); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+TYPE?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+POWE?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+NOTI?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); + pollingRequest("AT+PIO1?", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); + delay(150); } bool Cble::IsConnected( void ) { - return isConnected; + return isConnected; } bool Cble::IsSelfArduino( void ) { #ifdef __INTERNAL_DEBUG__ - debug_printf("IsSelfArduino is called.\r\n"); + debug_printf("IsSelfArduino is called.\r\n"); #endif - int length=mustHaveRequest("AT+ADDR?", debugD, 20); - - if( strstr(debugD, SelfMaxaddr) ) - { - isConnected = false; - memset(debugD,0,length); - return true; - } - else - { - isConnected = true; - memset(debugD,0,length); - return false; - } + int length = mustHaveRequest("AT+ADDR?", debugD, 20); + + if ( strstr(debugD, SelfMaxaddr) ) + { + isConnected = false; + memset(debugD, 0, length); + return true; + } + else + { + isConnected = true; + memset(debugD, 0, length); + return false; + } } -bool Cble::pollingConnect( const char* maxAddr ) +bool Cble::pollingConnect( const char *maxAddr ) { #ifdef __INTERNAL_DEBUG__ - debug_printf("pollingConnect is called.\r\n"); + debug_printf("pollingConnect is called.\r\n"); #endif -#define CONNECT_SIZE 20 - - char cmd[CONNECT_SIZE]= {0,}; - - // is Connected Address ? - pollingRequest("AT+ADDR?", debugD, 20); - if( strstr(debugD, maxAddr) ) - { - isConnected = true; - memset(debugD,0,DEBUG_SIZE); - return isConnected; - } - memset(debugD,0,DEBUG_SIZE); - - // Try Connection. - sprintf(cmd, "AT+CON%s",maxAddr); - if( pollingRequest(cmd, debugD, 8) == false ) - { - debug_printf("Error : %s command is failed.\r\n",cmd ); - memset(debugD,0,DEBUG_SIZE); - pollingDisconnect(); - return false; - } - else if( strstr(debugD,"OK+CONNA") ) - { - isConnected = true; - memset(debugD,0,DEBUG_SIZE); - } - else - { - memset(debugD,0,DEBUG_SIZE); - pollingDisconnect(); - return false; - } - // Confirm Connected Address. - pollingRequest("AT+ADDR?", debugD, 20); - - if( strstr(debugD, maxAddr) == 0 ) - { - isConnected = false; - if ( strstr(debugD, "OK+CONNF") ) - { - memset(debugD,0,DEBUG_SIZE); - streamDummy(debugD, 8); - } - } - memset(debugD,0,DEBUG_SIZE); - delay(5); - - return isConnected; +#define CONNECT_SIZE 20 + + char cmd[CONNECT_SIZE] = {0,}; + + // is Connected Address ? + pollingRequest("AT+ADDR?", debugD, 20); + if ( strstr(debugD, maxAddr) ) + { + isConnected = true; + memset(debugD, 0, DEBUG_SIZE); + return isConnected; + } + memset(debugD, 0, DEBUG_SIZE); + + // Try Connection. + sprintf(cmd, "AT+CON%s", maxAddr); + if ( pollingRequest(cmd, debugD, 8) == false ) + { + debug_printf("Error : %s command is failed.\r\n", cmd ); + memset(debugD, 0, DEBUG_SIZE); + pollingDisconnect(); + return false; + } + else if ( strstr(debugD, "OK+CONNA") ) + { + isConnected = true; + memset(debugD, 0, DEBUG_SIZE); + } + else + { + memset(debugD, 0, DEBUG_SIZE); + pollingDisconnect(); + return false; + } + // Confirm Connected Address. + pollingRequest("AT+ADDR?", debugD, 20); + + if ( strstr(debugD, maxAddr) == 0 ) + { + isConnected = false; + if ( strstr(debugD, "OK+CONNF") ) + { + memset(debugD, 0, DEBUG_SIZE); + streamDummy(debugD, 8); + } + } + memset(debugD, 0, DEBUG_SIZE); + delay(5); + + return isConnected; #undef CONNECT_SIZE } -#define CMD_DISCONNECT "(CMD_DISCON)" +#define CMD_DISCONNECT "(CMD_DISCON)" void Cble::pollingDisconnect( void ) { #ifdef __INTERNAL_DEBUG__ - debug_printf("pollingDisconnect is called.\r\n"); + debug_printf("pollingDisconnect is called.\r\n"); #endif - int length=0; + int length = 0; #if (ARDUINO == 0) - pollingRequest("\r\n" CMD_DISCONNECT "\r\n", NULL, NULL); - delay(5); + pollingRequest("\r\n" CMD_DISCONNECT "\r\n", NULL, NULL); + delay(5); - length=mustHaveRequest("AT", debugD, 2); - if( strstr(debugD,"OK") ) - isConnected = false; + length = mustHaveRequest("AT", debugD, 2); + if ( strstr(debugD, "OK") ) + isConnected = false; - memset(debugD,0,length); + memset(debugD, 0, length); #else - if( BLE.available() ) - { - if( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true ) - { - debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT); - - do { - debug_printf("pollingDisconnect : Send AT message.\r\n"); - if( length ) - memset(debugD, 0, length); - - length=mustHaveRequest("AT", debugD, 2); - }while( strstr(debugD,"OK") == NULL ); - - debug_printf("pollingDisconnect() is Success.\r\n"); - memset(debugD, 0, length); - } - } + if ( BLE.available() ) + { + if ( BLE.findUntil(CMD_DISCONNECT, "\r\n") == true ) + { + debug_printf("pollingDisconnect : Detected %s command.\r\n", CMD_DISCONNECT); + + do + { + debug_printf("pollingDisconnect : Send AT message.\r\n"); + if ( length ) + memset(debugD, 0, length); + + length = mustHaveRequest("AT", debugD, 2); + } + while ( strstr(debugD, "OK") == NULL ); + + debug_printf("pollingDisconnect() is Success.\r\n"); + memset(debugD, 0, length); + } + } #endif - delay(5); + delay(5); } int Cble::pollingGetRSSI( void ) { -#define RSSI_SIZE 11 -#define RSSI_POS 7 - - long time_cnt=0; - char c=0; - char index=0; - char rssi_res[RSSI_SIZE] = {0,}; - - streamDummy(NULL, NULL); - - if( isConnected == true ) - { - BLE.write("AT+RSSI?"); - BLE.flush(); - delay(5); - - while(1) - { - if ( BLE.available() ) - c = (char)BLE.read(); - else - { - c = 0; - time_cnt++; - } - - if( c ) - { - rssi_res[index] = c; - index++; - if( index == RSSI_SIZE-1 ) - { - rssi_res[index] = '\0'; - goto RESULT; - } - } - - // debug_printf("time_cnt=%d\r\n", time_cnt); - if( time_cnt == 0xFFFFF ) - { - debug_printf("Error : Time Out GetRSSI().\r\n"); - return BLE_NODATA; - } - - } - - RESULT : +#define RSSI_SIZE 11 +#define RSSI_POS 7 + + long time_cnt = 0; + char c = 0; + char index = 0; + char rssi_res[RSSI_SIZE] = {0,}; + + streamDummy(NULL, NULL); + + if ( isConnected == true ) + { + BLE.write("AT+RSSI?"); + BLE.flush(); + delay(5); + + while (1) + { + if ( BLE.available() ) + c = (char)BLE.read(); + else + { + c = 0; + time_cnt++; + } + + if ( c ) + { + rssi_res[index] = c; + index++; + if ( index == RSSI_SIZE - 1 ) + { + rssi_res[index] = '\0'; + goto RESULT; + } + } + + // debug_printf("time_cnt=%d\r\n", time_cnt); + if ( time_cnt == 0xFFFFF ) + { + debug_printf("Error : Time Out GetRSSI().\r\n"); + return BLE_NODATA; + } + + } + +RESULT : #ifdef __INTERNAL_DEBUG__ - debug_printf("res= %s \r\n",rssi_res); + debug_printf("res= %s \r\n", rssi_res); #endif - char* Srssi = &(rssi_res[RSSI_POS]); - // debug_printf("[S] rssi=%s\r\n", Srssi); - int rssi = atoi(Srssi); - // debug_printf("rssi=%d\r\n", rssi); + char *Srssi = &(rssi_res[RSSI_POS]); + // debug_printf("[S] rssi=%s\r\n", Srssi); + int rssi = atoi(Srssi); + // debug_printf("rssi=%d\r\n", rssi); - return rssi; - } + return rssi; + } - return BLE_DISCON; + return BLE_DISCON; #undef RSSI_POS #undef RSSI_SIZE } -int Cble::mustHaveRequest(const char* request, char* data, int dataLen) +int Cble::mustHaveRequest(const char *request, char *data, int dataLen) { - int cnt=0; - int length=0; - int required_length = dataLen; - char* data_index = data; + int cnt = 0; + int length = 0; + int required_length = dataLen; + char *data_index = data; - BLE.write(request); - BLE.flush(); - delay(150); + BLE.write(request); + BLE.flush(); + delay(150); READ_STREAM : - while( (length=BLE.readBytes(data_index, required_length)) == 0 ) - { - cnt++; - delay(10); + while ( (length = BLE.readBytes(data_index, required_length)) == 0 ) + { + cnt++; + delay(10); - if ( cnt >= LIMIT_COUNT/10 ) - { + if ( cnt >= LIMIT_COUNT / 10 ) + { #ifdef __INTERNAL_DEBUG__ - debug_printf("=====> Retry Request command Send. <=========\r\n"); + debug_printf("=====> Retry Request command Send. <=========\r\n"); #endif - cnt = 0; - BLE.write(request); - BLE.flush(); - - required_length = dataLen; - data_index = data; - length = 0; - delay(50); - } - } - - required_length -= length; - if( required_length != 0 ) - { - data_index = data_index + length; - length = 0; - goto READ_STREAM; - } + cnt = 0; + BLE.write(request); + BLE.flush(); + + required_length = dataLen; + data_index = data; + length = 0; + delay(50); + } + } + + required_length -= length; + if ( required_length != 0 ) + { + data_index = data_index + length; + length = 0; + goto READ_STREAM; + } #ifdef __INTERNAL_DEBUG__ - debug_printf("[ %s ] %s\r\n\r\n", request, data); + debug_printf("[ %s ] %s\r\n\r\n", request, data); #endif - return dataLen; + return dataLen; } -bool Cble::pollingRequest(const char* request, char* data, int dataLen) +bool Cble::pollingRequest(const char *request, char *data, int dataLen) { - int cnt=0; - int length=0; - int required_length = dataLen; - char* data_index = data; + int cnt = 0; + int length = 0; + int required_length = dataLen; + char *data_index = data; - BLE.write(request); - BLE.flush(); + BLE.write(request); + BLE.flush(); - if( data_index ) - { - delay(250); + if ( data_index ) + { + delay(250); READ_STREAM : - while( (length=BLE.readBytes(data_index, required_length)) == 0 ) - { - cnt++; - if ( cnt >= LIMIT_COUNT ) - { - debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request); - return false; - } - } - - required_length -= length; - if( required_length != 0 ) - { - data_index = data_index + length; - length = 0; - goto READ_STREAM; - } + while ( (length = BLE.readBytes(data_index, required_length)) == 0 ) + { + cnt++; + if ( cnt >= LIMIT_COUNT ) + { + debug_printf("[ %s ] TimeOut : No data.\r\n\r\n", request); + return false; + } + } + + required_length -= length; + if ( required_length != 0 ) + { + data_index = data_index + length; + length = 0; + goto READ_STREAM; + } #ifdef __INTERNAL_DEBUG__ - debug_printf("[ %s ] %s\r\n\r\n", request, data); + debug_printf("[ %s ] %s\r\n\r\n", request, data); #endif - } - return true; + } + return true; } -void Cble::streamDummy( char* data, int dataLen) +void Cble::streamDummy( char *data, int dataLen) { - int cnt=0; - int length=0; - int required_length = dataLen; - char* data_index = data; + int cnt = 0; + int length = 0; + int required_length = dataLen; + char *data_index = data; - if( data && required_length ) - { + if ( data && required_length ) + { READ_STREAM : - while( (length=BLE.readBytes(data_index, required_length)) == 0 ) - { - cnt++; - if ( cnt >= LIMIT_COUNT ) - { - debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n"); - return ; - } - } - - required_length -= length; - if( required_length != 0 ) - { - data_index = data_index + length; - length = 0; - goto READ_STREAM; - } - - debug_printf("[ streamDummy ] %s\r\n\r\n", data); - } - else - { - if( BLE.available() ) - { - BLE.readBytes(debugD, DEBUG_SIZE); + while ( (length = BLE.readBytes(data_index, required_length)) == 0 ) + { + cnt++; + if ( cnt >= LIMIT_COUNT ) + { + debug_printf("[ streamDummy ] TimeOut : No data.\r\n\r\n"); + return ; + } + } + + required_length -= length; + if ( required_length != 0 ) + { + data_index = data_index + length; + length = 0; + goto READ_STREAM; + } + + debug_printf("[ streamDummy ] %s\r\n\r\n", data); + } + else + { + if ( BLE.available() ) + { + BLE.readBytes(debugD, DEBUG_SIZE); #ifdef __INTERNAL_DEBUG__ - debug_printf("[ streamDummy ] %s\r\n\r\n", debugD); + debug_printf("[ streamDummy ] %s\r\n\r\n", debugD); #endif - memset(debugD, 0, DEBUG_SIZE); - } - } + memset(debugD, 0, DEBUG_SIZE); + } + } } #if (ARDUINO != 0) -#define REGARD_DISCON 5000 +#define REGARD_DISCON 5000 int needDiscon = 0; unsigned long global_cnt = 0; void Cble::BLE2Debug( int autoDiscon ) { - int cnt=0; - uint8_t length=0; - - if( BLE.available() ) - { - while( (length=BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 ) - { - cnt++; - if ( cnt >= LIMIT_COUNT ) - return ; - } - - global_cnt = 0; - needDiscon = 0; - - Serial.println(BLEData); - memset(BLEData, 0, length); - } - else if ( autoDiscon ) - { - global_cnt++; -// debug_printf("global_cnt=%u , ", global_cnt ); -// debug_printf("needDiscon=%d\r\n", needDiscon); - if( !needDiscon && global_cnt >= REGARD_DISCON ) - { - needDiscon = 1; - debug_printf("result : global_cnt=%u , ", global_cnt ); - debug_printf("needDiscon=%d\r\n", needDiscon); - } - - if ( needDiscon ) - { - debug_printf("Auto Discon : global_cnt=%u , ", global_cnt ); - debug_printf("needDiscon=%d\r\n", needDiscon); - if( pollingRequest("AT", debugD, 2) == true ) - { - global_cnt = 0; - needDiscon = 0; - } - } - } + int cnt = 0; + uint8_t length = 0; + + if ( BLE.available() ) + { + while ( (length = BLE.readBytes(BLEData, SERIAL_SIZE)) == 0 ) + { + cnt++; + if ( cnt >= LIMIT_COUNT ) + return ; + } + + global_cnt = 0; + needDiscon = 0; + + Serial.println(BLEData); + memset(BLEData, 0, length); + } + else if ( autoDiscon ) + { + global_cnt++; +// debug_printf("global_cnt=%u , ", global_cnt ); +// debug_printf("needDiscon=%d\r\n", needDiscon); + if ( !needDiscon && global_cnt >= REGARD_DISCON ) + { + needDiscon = 1; + debug_printf("result : global_cnt=%u , ", global_cnt ); + debug_printf("needDiscon=%d\r\n", needDiscon); + } + + if ( needDiscon ) + { + debug_printf("Auto Discon : global_cnt=%u , ", global_cnt ); + debug_printf("needDiscon=%d\r\n", needDiscon); + if ( pollingRequest("AT", debugD, 2) == true ) + { + global_cnt = 0; + needDiscon = 0; + } + } + } } -char* Cble::Debug2BLE( int BLEwrite ) +char *Cble::Debug2BLE( int BLEwrite ) { - char* result = NULL; - - if( Serial.available() ) - { - char c = (char)Serial.read(); - - switch(c) - { - case '\0': - return result; - case '\r': - case '\n': - debug_printf("\r\n"); - if(BLEwrite && SerialCnt) - { - BLE.write(SerialData); - BLE.flush(); - } - - result = (char*)malloc(sizeof(char)*(SerialCnt+1)); - memcpy(result, SerialData, SerialCnt ); - result[SerialCnt] = NULL; - - memset(SerialData, 0, SerialCnt+1); - SerialCnt=0; - break; - default : - SerialData[SerialCnt] = c; - SerialCnt++; - Serial.print(c); - break; - } - } - - return result; + char *result = NULL; + + if ( Serial.available() ) + { + char c = (char)Serial.read(); + + switch (c) + { + case '\0': + return result; + case '\r': + case '\n': + debug_printf("\r\n"); + if (BLEwrite && SerialCnt) + { + BLE.write(SerialData); + BLE.flush(); + } + + result = (char *)malloc(sizeof(char) * (SerialCnt + 1)); + memcpy(result, SerialData, SerialCnt ); + result[SerialCnt] = NULL; + + memset(SerialData, 0, SerialCnt + 1); + SerialCnt = 0; + break; + default : + SerialData[SerialCnt] = c; + SerialCnt++; + Serial.print(c); + break; + } + } + + return result; } #else void Cble::BLE2Debug( int autoDiscon ) { - ; + ; } -char* Cble::Debug2BLE( int BLEwrite ) +char *Cble::Debug2BLE( int BLEwrite ) { - return NULL; + return NULL; } #endif void Cble::FactoryReset( void ) { - debug_printf("FactoryReset is called.\r\n"); + debug_printf("FactoryReset is called.\r\n"); - pollingRequest("AT+RENEW", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); + pollingRequest("AT+RENEW", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); } void Cble::firstUartSetting( void ) { - debug_printf("firstUartSetting is called.\r\n"); + debug_printf("firstUartSetting is called.\r\n"); - Serial.begin(9600); - BLE.begin(9600); - BLE.setTimeout(1); - delay(1000); + Serial.begin(9600); + BLE.begin(9600); + BLE.setTimeout(1); + delay(1000); - pollingRequest("AT+BAUD4", debugD, 8); - memset(debugD, 0, DEBUG_SIZE); + pollingRequest("AT+BAUD4", debugD, 8); + memset(debugD, 0, DEBUG_SIZE); - debug_printf("Please Power off and on.\r\n"); - BLE.end(); -// delay(1000); + debug_printf("Please Power off and on.\r\n"); + BLE.end(); +// delay(1000); // -// BLE.begin(115200); -// delay(1000); +// BLE.begin(115200); +// delay(1000); // -// pollingRequest("AT", debugD, DEBUG_SIZE); -// memset(debugD, 0, DEBUG_SIZE); +// pollingRequest("AT", debugD, DEBUG_SIZE); +// memset(debugD, 0, DEBUG_SIZE); - exit(0); + exit(0); } diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp index 432ee0d..e668fa4 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp +++ b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp @@ -1,9 +1,22 @@ -/* - * oic_wifiLib.cpp - * - * Created on: 2014. 11. 13. - * Author: eunseok - */ +/****************************************************************** +* +* 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 "logger.h" #include "ocstack.h" @@ -57,7 +70,7 @@ int ConnectToNetwork() // Verify that WiFi Shield is running the firmware with all UDP fixes fwVersion = WiFi.firmwareVersion(); OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion); - if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 ) + if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) != 0 ) { OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!")); return -1; @@ -67,7 +80,7 @@ int ConnectToNetwork() while (status != WL_CONNECTED) { OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid); - status = WiFi.begin(ssid,pass); + status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp index 351f930..efefc74 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp +++ b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp @@ -1,87 +1,103 @@ -/* - * proximity.cpp - * - * Created on: 2014. 11. 13. - * Author: eunseok - */ +/****************************************************************** +* +* 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 "Arduino.h" #include "proximity.h" #include // Proximity code start -float CalculateExponentialAverage(int numberOfSamples, int* array, int startindex, int flag){ - float numerator = 0; - float denominator = 0; - - float average = 0.0; - - if (flag < arraysize / RSSI_EA) // first loop buffer full - { - for (int i = 0; i < startindex; i++) - { - average += array[i]; - } - if(startindex == 0){} - else{ - average = average / startindex; - } +float CalculateExponentialAverage(int numberOfSamples, int *array, int startindex, int flag) +{ + float numerator = 0; + float denominator = 0; - Serial.print("average1 : "); - Serial.println(average); - } - else - { - for (int i = 0; i < arraysize; i++) - { - average += array[i]; - } + float average = 0.0; - for (int i = startindex; i < startindex + RSSI_EA; i++) - { - average -= array[i]; - } - average = average / (arraysize - numberOfSamples); + if (flag < arraysize / RSSI_EA) // first loop buffer full + { + for (int i = 0; i < startindex; i++) + { + average += array[i]; + } + if (startindex == 0) {} + else + { + average = average / startindex; + } + // Serial.print("exp: "); + Serial.print("average1 : "); + Serial.println(average); + } + else + { + for (int i = 0; i < arraysize; i++) + { + average += array[i]; + } - Serial.print("average2 : "); - Serial.println(average); - } - //exponential moving average - int i = 0; - //CHANGE THIS FOR DIFFERENT SMOOTHING EFFECT - float beta=0.8f; - for (i = startindex + numberOfSamples - 1; i >= startindex; i--) - { - numerator += array[i]* pow(beta, startindex + numberOfSamples - i - 1); - denominator += pow(beta, startindex + numberOfSamples - i - 1); - } + for (int i = startindex; i < startindex + RSSI_EA; i++) + { + average -= array[i]; + } + average = average / (arraysize - numberOfSamples); + // Serial.print("exp: "); + Serial.print("average2 : "); + Serial.println(average); + } + //exponential moving average + int i = 0; + //CHANGE THIS FOR DIFFERENT SMOOTHING EFFECT + float beta = 0.8f; + for (i = startindex + numberOfSamples - 1; i >= startindex; i--) + { + numerator += array[i] * pow(beta, startindex + numberOfSamples - i - 1); + denominator += pow(beta, startindex + numberOfSamples - i - 1); + } - int offset = 3; - if(average != 0.0){ - numerator += average * pow(beta, offset + numberOfSamples); - denominator += pow(beta, offset + numberOfSamples); - } - return numerator / denominator; + int offset = 3; + if (average != 0.0) + { + numerator += average * pow(beta, offset + numberOfSamples); + denominator += pow(beta, offset + numberOfSamples); + } + return numerator / denominator; } float calculateDistance(float avgRSSI, float txPower) { - if (avgRSSI == 0) - { - return -1.0; - } + if (avgRSSI == 0) + { + return -1.0; + } - float ratio = avgRSSI*1.0/txPower; - if (ratio < 1.0) - { - return pow(ratio,10); - } - else - { - float distance = (0.7)*pow(ratio,10) + 0.024; - return distance; - } + float ratio = avgRSSI * 1.0 / txPower; + if (ratio < 1.0) + { + return pow(ratio, 10); + } + else + { + float distance = (0.7) * pow(ratio, 10) + 0.024; + return distance; + } } // proximity code end diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp index 8d78c5b..6b2b277 100644 --- a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp +++ b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp @@ -1,22 +1,22 @@ -//****************************************************************** -// -// 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. -// -//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +/****************************************************************** +* +* 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. +* +******************************************************************/ @@ -33,8 +33,8 @@ #include "trackee.h" // proximity code s -#define DATA_EA 400 -#define SLAVER_EA 2 +#define DATA_EA 400 +#define SLAVER_EA 2 #define ARDUINO_AVR_MEGA2560 1 /// This is the port which Arduino Server will use for all unicast communication with it's peers @@ -42,7 +42,7 @@ PROGMEM const char TAG[] = "TrackeeSensor"; -OCResourceHandle m_handle; // OIC base를 handling하기위해서 필요한 handler. +OCResourceHandle m_handle; #if (ARDUINO == 0) #include "proximity.h" @@ -60,7 +60,8 @@ OCResourceHandle m_handle; // OIC base를 handling하기위해서 필요한 han #define JSON_BASE09 "\",\"27\":\"SD\",\"28\":\"float\",\"29\":\"" #define JSON_BASE10 "\"}}" -typedef struct PROXIRESOURCE { +typedef struct PROXIRESOURCE +{ float m_distance[SLAVER_EA]; float m_proximity[SLAVER_EA]; } PROXIResource; @@ -76,11 +77,11 @@ int flag[SLAVER_EA] = {0,}; #endif Cble ble; - +//char trackeeID[13] = "9059AF170C1D"; char trackeeID[13] = "9059AF16FEF7"; int slaver_num = 0; - -char slaveList[SLAVER_EA][13]={"9059AF1700EE","34B1F7D004D2"}; +//char slaveList[SLAVER_EA][13]={"9059AF1704D7"}; +char slaveList[SLAVER_EA][13] = {"9059AF1700EE", "34B1F7D004D2"}; int g_PROXIUnderObservation = 0; @@ -89,47 +90,53 @@ const char *getResult(OCStackResult result); void createResource(); -#define LENGTH_VAR 50 -bool JsonGenerator( char* jsonBuf, uint16_t buf_length ) +#define LENGTH_VAR 50 +bool JsonGenerator( char *jsonBuf, uint16_t buf_length ) { - if( g_PROXIUnderObservation == 1 ) - { + if ( g_PROXIUnderObservation == 1 ) + { #if (ARDUINO == 0) - PROXIResource* ref = &PROXI; - int ref_cnt = SLAVER_EA; - uint16_t base_length = 0; - base_length = strlen(JSON_BASE)+ strlen(JSON_BASE00)+ strlen(JSON_BASE01)+ strlen(JSON_BASE02)+ strlen(JSON_BASE03)+\ - strlen(JSON_BASE04)+ strlen(JSON_BASE05)+ strlen(JSON_BASE06)+ strlen(JSON_BASE07)+\ - strlen(JSON_BASE08)+ strlen(JSON_BASE09)+ strlen(JSON_BASE10); + PROXIResource *ref = &PROXI; + int ref_cnt = SLAVER_EA; + uint16_t base_length = 0; + base_length = strlen(JSON_BASE) + strlen(JSON_BASE00) + strlen(JSON_BASE01) + strlen( + JSON_BASE02) + strlen(JSON_BASE03) + \ + strlen(JSON_BASE04) + strlen(JSON_BASE05) + strlen(JSON_BASE06) + strlen(JSON_BASE07) + \ + strlen(JSON_BASE08) + strlen(JSON_BASE09) + strlen(JSON_BASE10); - OC_LOG_V(INFO, TAG, "base length = %d, buf_length=%d", base_length, buf_length ); +// base_length = strlen(JSON_BASE00)+ strlen(JSON_BASE01)+ strlen(JSON_BASE02)+ strlen(JSON_BASE03)+\ +// strlen(JSON_BASE04)+ strlen(JSON_BASE05)+ strlen(JSON_BASE10); - if( ((long)buf_length - (long)base_length) < LENGTH_VAR ) - { - OC_LOG_V(ERROR, TAG, "Error : length is very long."); - return false; - } + OC_LOG_V(INFO, TAG, "base length = %d, buf_length=%d", base_length, buf_length ); - sprintf(jsonBuf, JSON_BASE ); - sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE00"%s"JSON_BASE01"%d", trackeeID, ref_cnt); - sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03"%d.%03d", slaveList[0], (int)ref->m_distance[0], (int)((ref->m_distance[0]-(int)ref->m_distance[0])*1000.0) ); - sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE04"%d"JSON_BASE05"0.0", (int)ref->m_proximity[0] ); - sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE06"%s"JSON_BASE07"%d.%03d", slaveList[1], (int)ref->m_distance[1], (int)((ref->m_distance[1]-(int)ref->m_distance[1])*1000.0) ); - sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE08"%d"JSON_BASE09"0.0", (int)ref->m_proximity[1] ); - strcpy(jsonBuf+strlen(jsonBuf), JSON_BASE10 ); + if ( ((long)buf_length - (long)base_length) < LENGTH_VAR ) + { + OC_LOG_V(ERROR, TAG, "Error : length is very long."); + return false; + } + + sprintf(jsonBuf, JSON_BASE ); + sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE00"%s"JSON_BASE01"%d", trackeeID, ref_cnt); + sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03"%d.%03d", slaveList[0], + (int)ref->m_distance[0], (int)((ref->m_distance[0] - (int)ref->m_distance[0]) * 1000.0) ); + sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE04"%d"JSON_BASE05"0.0", (int)ref->m_proximity[0] ); + sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE06"%s"JSON_BASE07"%d.%03d", slaveList[1], + (int)ref->m_distance[1], (int)((ref->m_distance[1] - (int)ref->m_distance[1]) * 1000.0) ); + sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE08"%d"JSON_BASE09"0.0", (int)ref->m_proximity[1] ); + strcpy(jsonBuf + strlen(jsonBuf), JSON_BASE10 ); - OC_LOG_V(INFO, TAG, "json length = %u", strlen(jsonBuf) ); + OC_LOG_V(INFO, TAG, "json length = %u", strlen(jsonBuf) ); - return true; + return true; -#else // Slave Json Code. +#else // Slave Json Code. - return true; + return true; #endif - } + } - OC_LOG_V(INFO, TAG, "Not Support Observer unfounded mode." ); - return false; + OC_LOG_V(INFO, TAG, "Not Support Observer unfounded mode." ); + return false; } @@ -154,72 +161,51 @@ void PrintArduinoMemoryStats() // This is the entity handler for the registered resource. // This is invoked by OCStack whenever it recevies a request for this resource. -OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest ) +OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest ) { OCEntityHandlerResult ehRet = OC_EH_OK; - OCEntityHandlerResponse response = {0}; - char payload[MAX_RESPONSE_LENGTH] = {0}; - if(entityHandlerRequest && (flag & OC_REQUEST_FLAG)) + if (entityHandlerRequest && (flag & OC_REQUEST_FLAG)) { OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG")); - if(OC_REST_GET == entityHandlerRequest->method) + if (OC_REST_GET == entityHandlerRequest->method) { - if(JsonGenerator(payload, MAX_RESPONSE_LENGTH)) - { - } - else + if (JsonGenerator((char *)entityHandlerRequest->resJSONPayload, \ + entityHandlerRequest->resJSONPayloadLen)) + { + } + else { ehRet = OC_EH_ERROR; } } - if(OC_REST_PUT == entityHandlerRequest->method) + if (OC_REST_PUT == entityHandlerRequest->method) { //Do something with the 'put' payload - if (JsonGenerator(payload, MAX_RESPONSE_LENGTH)) + if (JsonGenerator((char *)entityHandlerRequest->resJSONPayload, \ + entityHandlerRequest->resJSONPayloadLen)) { } else { ehRet = OC_EH_ERROR; } - } - } - - if (ehRet == OC_EH_OK) - { - // Format the response. Note this requires some info about the request - response.requestHandle = entityHandlerRequest->requestHandle; - response.resourceHandle = entityHandlerRequest->resource; - response.ehResult = ehRet; - response.payload = (unsigned char *)payload; - response.payloadSize = strlen(payload); - response.numSendVendorSpecificHeaderOptions = 0; - memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); - memset(response.resourceUri, 0, sizeof response.resourceUri); - // Indicate that response is NOT in a persistent buffer - response.persistentBufferFlag = 0; - - // Send the response - if (OCDoResponse(&response) != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, "Error sending response"); - ehRet = OC_EH_ERROR; - } + } } - if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) { - if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) + if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action) { OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client")); g_PROXIUnderObservation = 1; } - else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) + else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action) { OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client")); } } + return ehRet; } @@ -227,82 +213,95 @@ OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandle #if (ARDUINO == 0) void ChangePROXIRepresentation (void *param) { - (void)param; - OCStackResult result = OC_STACK_ERROR; - float avg[SLAVER_EA] = {0,}; - - for(int i = 0; i < SLAVER_EA; i++) - { - if( rssicnt[i] > arraysize - 1) - { - rssicnt[i] = rssicnt[i] % arraysize; - } - - ble.streamDummy(NULL, NULL); - - while(ble.pollingConnect(&slaveList[slaver_num][0]) == false){ - ble.streamDummy(NULL, NULL); - } - - if( ble.IsConnected() == true ) - { - // print the string when a newline arrives: - OC_LOG_V(INFO, TAG, "Connected. (%s)\r\n", slaveList[slaver_num]); - - for(int j=0; j < RSSI_EA; j++){ - rssi[i][rssicnt[i]] = ble.pollingGetRSSI(); - OC_LOG_V(INFO, TAG, "rssi val : %d \r\n", rssi[i][rssicnt[i]]); - rssicnt[i]++; - } - - while( ble.IsSelfArduino() == false ) - ble.pollingDisconnect(); - - slaver_num++; - slaver_num = slaver_num % SLAVER_EA; - } - - avg[i] = CalculateExponentialAverage(RSSI_EA, rssi[i], startindex[i], flag[i]); - Serial.println(avg[i]); - Serial.print("distance : "); - - PROXI.m_distance[i] = calculateDistance(avg[i], -58); - - if(PROXI.m_distance[i] <= 1){ - PROXI.m_proximity[i] = 1; - } - else if(PROXI.m_distance[i] <= 2){ - PROXI.m_proximity[i] = 2; - } - else{ - PROXI.m_proximity[i] = 3; - } - - Serial.println(PROXI.m_distance[i]); - Serial.println(PROXI.m_proximity[i]); - - startindex[i] += RSSI_EA; - - // This call displays the amount of free SRAM available on Arduino - PrintArduinoMemoryStats(); - - if(startindex[i] >= arraysize){ - startindex[i] = 0; - } - - if(flag[i] < (arraysize / RSSI_EA)) - { - flag[i]++; - } - } - - result = OCNotifyAllObservers (m_handle, OC_NA_QOS); - - if (OC_STACK_NO_OBSERVERS == result) - { - OC_LOG_V(INFO, TAG, "g_PROXIUnderObservation is 0." ); - g_PROXIUnderObservation = 0; - } + (void)param; + OCStackResult result = OC_STACK_ERROR; + float avg[SLAVER_EA] = {0,}; + + for (int i = 0; i < SLAVER_EA; i++) + { + if ( rssicnt[i] > arraysize - 1) + { + rssicnt[i] = rssicnt[i] % arraysize; + } + + ble.streamDummy(NULL, NULL); + /* if( ble.pollingConnect(&slaveList[slaver_num][0]) == false ) + { + OC_LOG_V("Error : Not Connected.\r\n"); + }*/ + while (ble.pollingConnect(&slaveList[slaver_num][0]) == false) + { + ble.streamDummy(NULL, NULL); + } + + if ( ble.IsConnected() == true ) + { + // print the string when a newline arrives: + OC_LOG_V(INFO, TAG, "Connected. (%s)\r\n", slaveList[slaver_num]); + +// time = millis(); + for (int j = 0; j < RSSI_EA; j++) + { + rssi[i][rssicnt[i]] = ble.pollingGetRSSI(); + OC_LOG_V(INFO, TAG, "rssi val : %d \r\n", rssi[i][rssicnt[i]]); + rssicnt[i]++; + } +// oldTime = millis(); +// float TpR = (float)(((oldTime-time)/1000.0)/20.0); +// OC_LOG_V("time per rssi : %d.%03d\r\n", (int)TpR, (int)(TpR*1000.0 -((int)TpR)*1000.0) ); + + while ( ble.IsSelfArduino() == false ) + ble.pollingDisconnect(); + + slaver_num++; + slaver_num = slaver_num % SLAVER_EA; + } + + avg[i] = CalculateExponentialAverage(RSSI_EA, rssi[i], startindex[i], flag[i]); + Serial.println(avg[i]); + Serial.print("distance : "); + + PROXI.m_distance[i] = calculateDistance(avg[i], -58); + + if (PROXI.m_distance[i] <= 1) + { + PROXI.m_proximity[i] = 1; + } + else if (PROXI.m_distance[i] <= 2) + { + PROXI.m_proximity[i] = 2; + } + else + { + PROXI.m_proximity[i] = 3; + } + + Serial.println(PROXI.m_distance[i]); + Serial.println(PROXI.m_proximity[i]); + //Serial.println(calculateDistance(avg[i], -58)); + startindex[i] += RSSI_EA; + + // This call displays the amount of free SRAM available on Arduino + PrintArduinoMemoryStats(); + + if (startindex[i] >= arraysize) + { + startindex[i] = 0; + } + + if (flag[i] < (arraysize / RSSI_EA)) + { + flag[i]++; + } + } + + result = OCNotifyAllObservers (m_handle, OC_NA_QOS); + + if (OC_STACK_NO_OBSERVERS == result) + { + OC_LOG_V(INFO, TAG, "g_PROXIUnderObservation is 0." ); + g_PROXIUnderObservation = 0; + } } #endif @@ -313,45 +312,45 @@ void ChangePROXIRepresentation (void *param) //The setup function is called once at startup of the sketch void setup() { - Serial.begin(115200); + Serial.begin(115200); - // Add your initialization code here - OC_LOG_INIT(); + // Add your initialization code here + OC_LOG_INIT(); - OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); - // uint16_t port = OC_WELL_KNOWN_PORT; + OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); + // uint16_t port = OC_WELL_KNOWN_PORT; - // Connect to Ethernet or WiFi network - if (ConnectToNetwork() != 0) - { - OC_LOG(ERROR, TAG, "Unable to connect to network"); - return; - } + // Connect to Ethernet or WiFi network + if (ConnectToNetwork() != 0) + { + OC_LOG(ERROR, TAG, "Unable to connect to network"); + return; + } - // Initialize the OC Stack in Server mode - if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("OCStack init error")); - return; - } + // Initialize the OC Stack in Server mode + if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack init error")); + return; + } OCStartPresence(60); - // Declare and create the example resource - createResource(); + // Declare and create the example resource + createResource(); - // This call displays the amount of free SRAM available on Arduino - PrintArduinoMemoryStats(); + // This call displays the amount of free SRAM available on Arduino + PrintArduinoMemoryStats(); #if (ARDUINO == 0) - ble.init( (long)115200, BLE_MASTER, trackeeID); + ble.init( (long)115200, BLE_MASTER, trackeeID); #elif (ARDUINO == 1) - ble.init( (long)115200, BLE_SLAVER, slaveList[0]); + ble.init( (long)115200, BLE_SLAVER, slaveList[0]); #elif (ARDUINO == 2) - ble.init( (long)115200, BLE_SLAVER, slaveList[1]); + ble.init( (long)115200, BLE_SLAVER, slaveList[1]); #endif -// ble.StatusRead(); +// ble.StatusRead(); - OC_LOG_V(INFO, TAG, "Program Start-\r\n"); + OC_LOG_V(INFO, TAG, "Program Start-\r\n"); } @@ -361,26 +360,26 @@ void loop() // This artificial delay is kept here to avoid endless spinning // of Arduino microcontroller. Modify it as per specfic application needs. - if (OCProcess() != OC_STACK_OK) - { - OC_LOG(ERROR, TAG, PCF("OCStack process error")); - return; - } + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack process error")); + return; + } #if (ARDUINO == 0) - ChangePROXIRepresentation(NULL); + ChangePROXIRepresentation(NULL); #else - char* user_cmd = NULL; + char *user_cmd = NULL; -// ble.pollingDisconnect(); +// ble.pollingDisconnect(); - user_cmd = ble.Debug2BLE(true); - ble.BLE2Debug( true ); + user_cmd = ble.Debug2BLE(true); + ble.BLE2Debug( true ); - if( user_cmd ) - { - free( user_cmd ); - user_cmd = NULL; - } + if ( user_cmd ) + { + free( user_cmd ); + user_cmd = NULL; + } #endif } @@ -391,53 +390,56 @@ void loop() -void createResource() { +void createResource() +{ OCStackResult res = OCCreateResource(&m_handle, "SoftSensorManager.Sensor", "oc.mi.def", "/Tracker_Thing", OCEntityHandlerCb, - OC_DISCOVERABLE|OC_OBSERVABLE); + OC_DISCOVERABLE | OC_OBSERVABLE); OC_LOG_V(INFO, TAG, "Created PROXI resource with result: %s", getResult(res)); } -const char *getResult(OCStackResult result) { - switch (result) { - case OC_STACK_OK: - return "OC_STACK_OK"; - case OC_STACK_INVALID_URI: - return "OC_STACK_INVALID_URI"; - case OC_STACK_INVALID_QUERY: - return "OC_STACK_INVALID_QUERY"; - case OC_STACK_INVALID_IP: - return "OC_STACK_INVALID_IP"; - case OC_STACK_INVALID_PORT: - return "OC_STACK_INVALID_PORT"; - case OC_STACK_INVALID_CALLBACK: - return "OC_STACK_INVALID_CALLBACK"; - case OC_STACK_INVALID_METHOD: - return "OC_STACK_INVALID_METHOD"; - case OC_STACK_NO_MEMORY: - return "OC_STACK_NO_MEMORY"; - case OC_STACK_COMM_ERROR: - return "OC_STACK_COMM_ERROR"; - case OC_STACK_INVALID_PARAM: - return "OC_STACK_INVALID_PARAM"; - case OC_STACK_NOTIMPL: - return "OC_STACK_NOTIMPL"; - case OC_STACK_NO_RESOURCE: - return "OC_STACK_NO_RESOURCE"; - case OC_STACK_RESOURCE_ERROR: - return "OC_STACK_RESOURCE_ERROR"; - case OC_STACK_SLOW_RESOURCE: - return "OC_STACK_SLOW_RESOURCE"; - case OC_STACK_NO_OBSERVERS: - return "OC_STACK_NO_OBSERVERS"; - case OC_STACK_ERROR: - return "OC_STACK_ERROR"; - default: - return "UNKNOWN"; +const char *getResult(OCStackResult result) +{ + switch (result) + { + case OC_STACK_OK: + return "OC_STACK_OK"; + case OC_STACK_INVALID_URI: + return "OC_STACK_INVALID_URI"; + case OC_STACK_INVALID_QUERY: + return "OC_STACK_INVALID_QUERY"; + case OC_STACK_INVALID_IP: + return "OC_STACK_INVALID_IP"; + case OC_STACK_INVALID_PORT: + return "OC_STACK_INVALID_PORT"; + case OC_STACK_INVALID_CALLBACK: + return "OC_STACK_INVALID_CALLBACK"; + case OC_STACK_INVALID_METHOD: + return "OC_STACK_INVALID_METHOD"; + case OC_STACK_NO_MEMORY: + return "OC_STACK_NO_MEMORY"; + case OC_STACK_COMM_ERROR: + return "OC_STACK_COMM_ERROR"; + case OC_STACK_INVALID_PARAM: + return "OC_STACK_INVALID_PARAM"; + case OC_STACK_NOTIMPL: + return "OC_STACK_NOTIMPL"; + case OC_STACK_NO_RESOURCE: + return "OC_STACK_NO_RESOURCE"; + case OC_STACK_RESOURCE_ERROR: + return "OC_STACK_RESOURCE_ERROR"; + case OC_STACK_SLOW_RESOURCE: + return "OC_STACK_SLOW_RESOURCE"; + case OC_STACK_NO_OBSERVERS: + return "OC_STACK_NO_OBSERVERS"; + case OC_STACK_ERROR: + return "OC_STACK_ERROR"; + default: + return "UNKNOWN"; } } diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h index ab20039..9d245ba 100644 --- a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/ITS.h @@ -58,7 +58,7 @@ namespace ITSName { SUCCESS = 0, ERROR, NO_ELEMENT } ITSResult; - + class SThing { public: @@ -96,6 +96,7 @@ namespace ITSName class ITS: public ICtxEvent { private: + static ITS *singleton; Things *m_TList; SThing *m_closestThing; @@ -104,9 +105,11 @@ namespace ITSName public: static physicalInput s_PHYSICAL_SENSORs[PHYSICAL_EA]; + static ITS *GetInstance( void ); ITS(); ~ITS(); + static void *SelfTrajectoryThread(void *param); void onCtxEvent(enum CTX_EVENT_TYPE eventType, std::vector< ContextData > contextDataList); ITSResult getInput(std::vector< ContextData > &contextDataList, CurrentService *CService ); diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/lib_proximity.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/lib_proximity.h new file mode 100644 index 0000000..6d323ad --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/lib_proximity.h @@ -0,0 +1,32 @@ +/****************************************************************** +* +* 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 PROXIMITY_H_ +#define PROXIMITY_H_ + + +#define arraysize 6 +#define RSSI_EA 3 + +float CalculateExponentialAverage(int numberOfSamples, int *array, int startindex, int flag); + +float calculateDistance(float avgRSSI, float txPower); + +#endif /* PROXIMITY_H_ */ diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_CbleDevice.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_CbleDevice.h new file mode 100644 index 0000000..41fa53b --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_CbleDevice.h @@ -0,0 +1,62 @@ +/****************************************************************** +* +* 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 CBLEDEVICE_H_ +#define CBLEDEVICE_H_ + +#include +#include +#include + + +class CbleDevice +{ + private : + typedef bt_adapter_device_discovery_info_s ble_value; + typedef std::map CbleDeviceMAP; + CbleDeviceMAP device; + + public : + unsigned long time_count; + + CbleDevice(); + ~CbleDevice(); + + int insert( ble_value *discovery_info ); + + ble_value *getNext( int seq ); + + int setRSSI( std::string addr, int rssi ); + + ble_value *get( std::string addr ); + + bool find( std::string addr ); + + int size( void ); + + void erase( CbleDeviceMAP::iterator itr ); + + void clear( void ); + + bool isTimeOut( void ); +}; + + +#endif /* CBLEDEVICE_H_ */ diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_ble_bgthread.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_ble_bgthread.h new file mode 100644 index 0000000..f0a9535 --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_ble_bgthread.h @@ -0,0 +1,91 @@ +/****************************************************************** +* +* 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 BLE_LIB_H_ +#define BLE_LIB_H_ + +#include +#include "tizen_CbleDevice.h" + +void what_return_value( bt_error_e returnValue ); + + +#define PROCESS_FREE 0 +#define PROCESS_TRYING 1 +#define PROCESS_FOUND 2 +#define PROCESS_COMPLETE 3 + +class CbleBGthread +{ + public : + typedef void (*workfunc)( void *); + + private : + static CbleBGthread *singleton; + + static bool ble_adapter_flag; + static int ble_discover_flag; + static int ble_bond_flag; + static int reg_bond_cnt; + static workfunc workProcess; + + static bool ble_discovery( void ); + + static bool find_referenceThing( bt_adapter_device_discovery_info_s *discovery_info , + CbleDevice *pdevice ); + + public : + static bool isThreadRun; + static pthread_t Thandle; + + CbleBGthread( workfunc func ); + + ~CbleBGthread( void ); + + static CbleBGthread *GetInstance( workfunc func ); + + // ETC. function List. +// static void set_workProcess(workfunc func); + static void set_adapter_state_flag(void); + + + // Thread List. + static void *ble_thread(void *param); + // Callback List. + static void CB_adapter_state_change(int result, bt_adapter_state_e adapter_state, void *user_data); + static void CB_discover_state_change(int result, + bt_adapter_device_discovery_state_e discovery_state, + bt_adapter_device_discovery_info_s *discovery_info, void *user_data); + static void CB_bond_create(int result, bt_device_info_s *device_info, void *user_data); + +}; + + +//#define BT_ERROR_CHECK( _FUNC_ ) { \ +// bt_error_e __err__ = (bt_error_e)(_FUNC_); \ +// if ( __err__ != BT_ERROR_NONE ) \ +// { \ +// what_return_value( __err__ ); \ +// goto BT_ERROR; \ +// } \ +//} + + +#endif /* BLE_LIB_H_ */ diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_log.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_log.h new file mode 100644 index 0000000..e197c4c --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_log.h @@ -0,0 +1,102 @@ +/****************************************************************** +* +* 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 __OICAPP_LOG_H__ +#define __OICAPP_LOG_H__ + +#define TIZEN_DEBUG_ENABLE +#define LOG_TAG "OIC_TEST" +#include + +#define LOG_COLOR_RED "\033[0;31m" +#define LOG_COLOR_BROWN "\033[0;33m" +#define LOG_COLOR_BLUE "\033[0;34m" +#define LOG_COLOR_END "\033[0;m" + + +#if 0 +#define _DBG(fmt, arg...) SLOGD(fmt, ##arg) +#define _INFO(fmt, arg...) SLOGI(fmt, ##arg) +#define _WARN(fmt, arg...) SLOGW(fmt, ##arg) +#define _ERR(fmt, arg...) SLOGE(fmt, ##arg) +#else +#define _DBG(fmt, arg...) \ + printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg) +#define _INFO(fmt, arg...) \ + printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg) +#define _WARN(fmt, arg...) \ + printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg) +#define _ERR(fmt, arg...) \ + printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg) +#endif + +#define DBG(fmt, arg...) _DBG(fmt, ##arg) +#define WARN(fmt, arg...) _WARN(LOG_COLOR_BROWN fmt LOG_COLOR_END, ##arg) +#define ERR(fmt, arg...) _ERR(LOG_COLOR_RED fmt LOG_COLOR_END, ##arg) +#define INFO(fmt, arg...) _INFO(LOG_COLOR_BLUE fmt LOG_COLOR_END, ##arg) + +#define ret_if(expr) \ + do { \ + if (expr) { \ + ERR("(%s)", #expr); \ + return; \ + }\ + } while(0) +#define retv_if(expr, val) \ + do {\ + if (expr) { \ + ERR("(%s)", #expr); \ + return (val); \ + } \ + } while(0) +#define retm_if(expr, fmt, arg...) \ + do {\ + if (expr) { \ + ERR(fmt, ##arg); \ + return; \ + }\ + } while(0) +#define retvm_if(expr, val, fmt, arg...) \ + do {\ + if (expr) { \ + ERR(fmt, ##arg); \ + return (val); \ + } \ + } while(0) +#define warn_if(expr) \ + do { \ + if (expr) { \ + WARN("(%s)", #expr); \ + } \ + } while (0) + + + +#define BT_ERROR_CHECK( _FUNC_ ) { \ + bt_error_e __err__ = (bt_error_e)(_FUNC_); \ + if ( __err__ != BT_ERROR_NONE ) \ + { \ + what_return_value( __err__ ); \ + goto BT_ERROR; \ + } \ +} + + +#endif //__OICAPP_LOG_H__ + diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_proximity.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_proximity.h new file mode 100644 index 0000000..476053d --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_proximity.h @@ -0,0 +1,113 @@ +/****************************************************************** +* +* 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 TIZEN_PROXIMITY_H_ +#define TIZEN_PROXIMITY_H_ + +#include +#include +#include "tizen_CbleDevice.h" + +void proximity_loop( void *param ); +void what_return_value( bt_error_e returnValue ); + +#define JOB_NONE 0 +#define JOB_GET_RSSI 1 +#define JOB_GET_PROX 2 +#define JOB_PUT_OUTPUT 3 +#define JOB_BUSY 4 + +class CRSSI +{ + public: + int cnt; + int *rssi; + + CRSSI() : cnt(0), rssi(0) {} + CRSSI( int count ) : cnt(0), rssi(0) { init(count); } + ~CRSSI() + { + if ( rssi ) + { + cnt = 0; + delete [] rssi; + rssi = 0; + } + } + + void init( int count ) + { + if ( rssi == NULL ) + { + rssi = new int[count]; + cnt = count; + } + } + +}; + +class CProximity +{ + public : + typedef void *(*workfunc)( void *); + typedef std::map rssiMAP; + private : + static int loop_flag; + static int get_rssi_cnt; + static int num_set_rssi; + static rssiMAP map_rssi; + + workfunc threadFunc; + + int reference_ea; + float *m_distance; + int *m_proximity; + public : + pthread_t Thandle; + + CProximity( workfunc func ); + + ~CProximity( void ); + + static bool find_referenceThing( bt_adapter_device_discovery_info_s *discovery_info , + CbleDevice *pdevice ); + + static void CB_discover_state_change(int result, + bt_adapter_device_discovery_state_e discovery_state, \ + bt_adapter_device_discovery_info_s *discovery_info, void *user_data); + + bool GetRSSI(CbleDevice *pdevice); + + void GetProximity(CbleDevice *pdevice); + + bool set_threadFunc(workfunc func); + + workfunc get_threadFunc(void); + + void set_output( CbleDevice *pdevice ); + + void prox_first_setting( int reference_ea ); + + friend void proximity_loop( void *param ); +}; + + + +#endif /* TIZEN_PROXIMITY_H_ */ diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_public_ble.h b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_public_ble.h new file mode 100644 index 0000000..d410ae5 --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/include/tizen_public_ble.h @@ -0,0 +1,33 @@ +/****************************************************************** +* +* 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 PUBLIC_BLE_H_ +#define PUBLIC_BLE_H_ + + +#define REF_NAME "reference" + +void ble_init( void (*func)(void *) ); + +void proximity_init( void *(*func)(void *) ); + +void proximity_loop( void *param ); + +#endif /* PUBLIC_BLE_H_ */ diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp index a6a8542..c8ba0f3 100644 --- a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/GeneralData.cpp @@ -33,7 +33,7 @@ class AllFormat_data : public Virtual_data TYPE data; public : - AllFormat_data(int typenum) : base(typenum), data() + AllFormat_data(int typenum) : base(typenum) { #ifdef __INTER_DEBUG__ printf("[DEBUG] Test_data Constructor().\n"); @@ -65,7 +65,6 @@ void Virtual_data::s2data( const char *value) char data = atoi(value); put_data( (void *)&data ); } - break; case TYPE_INT : case TYPE_SHORT : { diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp index 0ae53cf..fa578da 100644 --- a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/ITS.cpp @@ -31,11 +31,14 @@ #include "GeneralData.h" #include "SysTimer.h" +#include "tizen_public_ble.h" + using namespace ITSName; //#define __INTERNAL_DEBUG__ #define SENSOR_NAME "IndoorTrajectorySensor" + #define INPUT_EA 4 #define SEQ_ID 0 #define SEQ_DISTANCE 1 @@ -57,6 +60,7 @@ physicalInput ITS::s_PHYSICAL_SENSORs[PHYSICAL_EA] = }; ICtxDelegate *g_pDelegate; +ITS *ITS::singleton = NULL; // map typedef std::map < std::string, Trajectory > TrajectoryMap; @@ -80,6 +84,7 @@ void parserTracker_Thing( int seq, std::vector< GeneralData > &gVector, CurrentS return ; } + std::string name = ""; gVector[0].get_Name(name); @@ -96,6 +101,7 @@ void parserTracker_Thing( int seq, std::vector< GeneralData > &gVector, CurrentS CService->service.timestamp = SysTimer::MilliSecondTime(); + name = ""; gVector[1].get_Name(name); @@ -122,6 +128,7 @@ void parserTracker_Thing( int seq, std::vector< GeneralData > &gVector, CurrentS return ; } + for (unsigned int j = 2; j < gVector.size(); j++) { gVector[j].get_Name(name); @@ -161,15 +168,73 @@ void InitializeContext(ICtxDelegate *pDelegate) { std::vector < ContextData > contextData; - ITS *eventCls = new ITS(); + ITS *eventCls = ITS::GetInstance(); pDelegate->registerCallback(eventCls); g_pDelegate = pDelegate; - std::cout << "ITS sensor loaded -01-" << std::endl; + proximity_init(ITS::SelfTrajectoryThread); + ble_init(proximity_loop); + std::cout << "ITS sensor loaded -02-" << std::endl; return; } + +/****************************************************** + * Loop function based thread. + */ +void *ITS::SelfTrajectoryThread(void *param) +{ +//#ifdef __INTERNAL_DEBUG__ + std::cout << "[DEBUG] ITS::" << __func__ << " is called." << std::endl; +//#endif + + ContextData out; + CurrentService CService; + Things *TList = (Things *)param; + Trajectory *tra = 0; + ITSResult flag = ERROR; + ITS *its = ITS::GetInstance(); + + CService.trackee.ID = "SelfTrackee"; + CService.service.timestamp = SysTimer::MilliSecondTime(); + + if ( (flag = its->searchValidService( TList, &CService )) != SUCCESS ) + { + if ( flag == NO_ELEMENT ) + return 0; + + std::cout << "Error : searchValidService() function failed." << std::endl; + return NULL; + } + + if ( (tra = its->makeTrajectory(&CService)) == NULL) + { + std::cout << "Error : makeTrajectory() function failed." << std::endl; + return NULL; + } + + if ( its->setOutput( tra, &out ) != SUCCESS ) + { + std::cout << "Error : setOutput() function failed." << std::endl; + return NULL; + } + + std::vector < ContextData > outList; + outList.push_back(out); + g_pDelegate->addOutput(outList); + + return NULL; +} + +ITS *ITS::GetInstance( void ) +{ + if ( singleton == NULL ) + singleton = new ITS(); + + return singleton; +} + ITS::ITS() { #ifdef __INTERNAL_DEBUG__ @@ -192,6 +257,9 @@ ITS::~ITS() m_TList = 0; m_closestThing = 0; } + + if ( singleton ) + delete singleton; } void ITS::onCtxEvent(enum CTX_EVENT_TYPE eventType, @@ -208,8 +276,6 @@ void ITS::onCtxEvent(enum CTX_EVENT_TYPE eventType, } } - - int ITS::runLogic(std::vector< ContextData > &contextDataList) { #ifdef __INTERNAL_DEBUG__ @@ -255,8 +321,6 @@ int ITS::runLogic(std::vector< ContextData > &contextDataList) return 0; } - - /** * Get Input data (temperature, humidity) using resource Client of Iotivity base. */ @@ -281,8 +345,7 @@ ITSResult ITS::getInput(std::vector< ContextData > &contextDataList, CurrentServ if (contextDataList[i].rootName == s_PHYSICAL_SENSORs[k].m_thingName) { std::vector< GeneralData > gVector; - Conversion_DataFormat( contextDataList[i].outputProperty, - gVector ); + Conversion_DataFormat( contextDataList[i].outputProperty, gVector ); switch ( k ) { @@ -302,7 +365,6 @@ ITSResult ITS::getInput(std::vector< ContextData > &contextDataList, CurrentServ return SUCCESS; } - /** * searchValidService Function. */ diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp index 504e662..8025595 100644 --- a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/Trajectory.cpp @@ -17,7 +17,6 @@ * limitations under the License. * ******************************************************************/ - #include "Trajectory.h" #include diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/lib_proximity.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/lib_proximity.cpp new file mode 100644 index 0000000..45cf149 --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/lib_proximity.cpp @@ -0,0 +1,110 @@ +/****************************************************************** +* +* 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 +#include "tizen_log.h" +#include "lib_proximity.h" +#include + +// Proximity code start +float CalculateExponentialAverage(int numberOfSamples, int *array, int startindex, int flag) +{ + float numerator = 0; + float denominator = 0; + + float average = 0.0; + + if (flag < arraysize / RSSI_EA) // first loop buffer full + { + + for (int i = 0; i < startindex; i++) + { + average += array[i]; + } + + if (startindex == 0) {} + else + { + average = average / startindex; + } + // DBG("exp: "); + DBG("average1 : %f", average); + } + else + { + for (int i = 0; i < arraysize; i++) + { + average += array[i]; + } + + for (int i = startindex; i < startindex + RSSI_EA; i++) + { + average -= array[i]; + } + + average = average / (arraysize - numberOfSamples); + + // DBG("exp: "); + DBG("average2 : %f", average); + } + + //exponential moving average + int i = 0; + //CHANGE THIS FOR DIFFERENT SMOOTHING EFFECT + float beta = 0.8f; + for (i = startindex + numberOfSamples - 1; i >= startindex; i--) + { + double temp = pow(beta, startindex + numberOfSamples - i - 1); + numerator += array[i] * (float)temp; + denominator += (float)temp; + } + + int offset = 3; + if (average != 0.0) + { + numerator += average * pow(beta, offset + numberOfSamples); + denominator += pow(beta, offset + numberOfSamples); + } + + return numerator / denominator; +} + + +float calculateDistance(float avgRSSI, float txPower) +{ + if (avgRSSI == 0) + { + return -1.0; + } + + float ratio = avgRSSI * 1.0 / txPower; + if (ratio < 1.0) + { + return pow(ratio, 10); + } + else + { + float distance = (0.7) * pow(ratio, 10) + 0.024; + return distance; + } +} + +// proximity code end + diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_CbleDevice.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_CbleDevice.cpp new file mode 100644 index 0000000..fb47d62 --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_CbleDevice.cpp @@ -0,0 +1,160 @@ +/****************************************************************** +* +* 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 +#include "tizen_log.h" +#include "tizen_CbleDevice.h" + +#define TIME_LIMITE 5 // unit : second + +CbleDevice::CbleDevice() : time_count(0) { clear(); } +CbleDevice::~CbleDevice() { clear(); } + +int CbleDevice::insert( CbleDevice::ble_value *discovery_info ) +{ + DBG("Enter."); + std::string addr = std::string(discovery_info->remote_address); + + if ( find(addr) == false ) + { + device[addr] = *discovery_info; + + device[addr].remote_address = new char[ strlen(discovery_info->remote_address) + 1 ]; + strcpy( device[addr].remote_address, discovery_info->remote_address); + device[addr].remote_name = new char[ strlen(discovery_info->remote_name) + 1 ]; + strcpy( device[addr].remote_name, discovery_info->remote_name); + device[addr].service_uuid = NULL; + device[addr].service_count = 0; + } + + return device.size(); +} + +CbleDevice::ble_value *CbleDevice::getNext( int seq ) +{ + DBG("Enter."); + CbleDeviceMAP::iterator itr = device.begin(); + + if ( seq < 0 || seq >= device.size()) + { +#if __INTERNAL_DEBUG_ + DBG("return null"); +#endif + return NULL; + } + + for (; seq ; seq--) + itr++; + +#if __INTERNAL_DEBUG_ + DBG("return %s pointer", itr->second.remote_address ); +#endif + return &itr->second; +} + +int CbleDevice::setRSSI( std::string addr, int rssi ) +{ + DBG("Enter."); + CbleDeviceMAP::iterator itr = device.find( addr ); + + if ( itr == device.end() ) + return NULL; + + ble_value *pdevice = &itr->second; + + if ( rssi == NULL ) + { + pdevice->service_count = NULL; + pdevice->rssi = 0; + } + else if ( pdevice->service_count == NULL ) + { + pdevice->service_count = 1; + pdevice->rssi = rssi; + } + else + return NULL; + + return pdevice->rssi; +} + +CbleDevice::ble_value *CbleDevice::get( std::string addr ) +{ + DBG("Enter."); + CbleDeviceMAP::iterator itr = device.find( addr ); + + if ( itr == device.end() ) + return NULL; + + return &itr->second; +} + +bool CbleDevice::find( std::string addr ) +{ + DBG("Enter."); + CbleDeviceMAP::iterator itr = device.find( addr ); + + if ( itr == device.end() ) + return false; + + return true; +} + +int CbleDevice::size( void ) +{ + DBG("Enter."); + return device.size(); +} + +void CbleDevice::erase( CbleDeviceMAP::iterator itr ) +{ + ble_value *value = &itr->second; + + if ( value->remote_address ) + delete value->remote_address; + if ( value->remote_name ) + delete value->remote_name; + if ( value->service_uuid ) + delete [] value->service_uuid; + + device.erase(itr); +} + +void CbleDevice::clear( void ) +{ + CbleDeviceMAP::iterator itr = device.begin(); + + if ( itr != device.end() ) + { + erase(itr); + itr++; + } +} + +bool CbleDevice::isTimeOut( void ) +{ + DBG("Enter."); + if ( time_count > TIME_LIMITE ) + return true; + else + return false; +} + + diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_ble_bgthread.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_ble_bgthread.cpp new file mode 100644 index 0000000..55375cb --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_ble_bgthread.cpp @@ -0,0 +1,463 @@ +/****************************************************************** +* +* 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 +#include +#include "tizen_log.h" +#include +#include + +#include "tizen_public_ble.h" +#include "tizen_ble_bgthread.h" +#include "tizen_CbleDevice.h" + +CbleBGthread *CbleBGthread::singleton = NULL; +CbleBGthread::workfunc CbleBGthread::workProcess = NULL; +bool CbleBGthread::ble_adapter_flag = false; +int CbleBGthread::ble_discover_flag = PROCESS_FREE; +int CbleBGthread::ble_bond_flag = PROCESS_FREE; +bool CbleBGthread::isThreadRun = false; +int CbleBGthread::reg_bond_cnt = 0; +pthread_t CbleBGthread::Thandle = 0; + +// tizen ble init function. +void ble_init( CbleBGthread::workfunc func ) +{ + DBG("Enter."); + + CbleBGthread *ble = CbleBGthread::GetInstance( func ); + if ( ble == NULL ) + { + DBG("Error : function is failed."); + return ; + } + + BT_ERROR_CHECK( bt_initialize() ); + + BT_ERROR_CHECK( bt_adapter_set_state_changed_cb(CbleBGthread::CB_adapter_state_change, NULL) ); + sleep(1); + + bt_error_e returnValue; + returnValue = (bt_error_e)bt_adapter_enable(); + if (returnValue != BT_ERROR_NONE ) + { + what_return_value( returnValue ); + if ( returnValue != BT_ERROR_ALREADY_DONE) + return ; + else + { +#if __INTERNAL_DEBUG_ + DBG("return == BT_ERROR_ALREADY_DONE"); +#endif + CbleBGthread::set_adapter_state_flag(); + } + } + +#if __INTERNAL_DEBUG_ + DBG("Register discovery callback func."); +#endif + static CbleDevice device; + BT_ERROR_CHECK( bt_adapter_set_device_discovery_state_changed_cb( + CbleBGthread::CB_discover_state_change, &device) ); +// sleep(1); + +// DBG("Register bond create callback func."); +// BT_ERROR_CHECK( bt_device_set_bond_created_cb( CbleBGthread::CB_bond_create , &device) ); +// sleep(1); + + ble->isThreadRun = true; + pthread_create(&ble->Thandle, NULL, CbleBGthread::ble_thread, &device); + + DBG("Exit."); + return ; + +BT_ERROR: + DBG("Error Exception. Exit."); + +} + +//void workProcess( void ) +//{ +// DBG("WorkProcess run."); +//} + +/********************************* + * CbleBGthread class definition. + */ +CbleBGthread::CbleBGthread(workfunc func) +{ + workProcess = func; + ble_adapter_flag = false; + ble_discover_flag = PROCESS_FREE; + ble_bond_flag = PROCESS_FREE; + isThreadRun = false; + reg_bond_cnt = 0; + Thandle = 0; +} + +CbleBGthread::~CbleBGthread() +{ + if ( singleton ) + { + singleton = NULL; + } +} + +CbleBGthread *CbleBGthread::GetInstance( workfunc func ) +{ + if ( func == NULL ) + return NULL; + + if (singleton == NULL) + singleton = new CbleBGthread(func); + + return singleton; +} + +/***************************** + * BLE processing thread. + */ +void *CbleBGthread::ble_thread(void *param) +{ + DBG("Enter."); + CbleDevice *pdevice = (CbleDevice *)param; + + while (isThreadRun ) + { + sleep(1); + pdevice->time_count++; + + if ( ble_adapter_flag ) + { + // discovery + if ( ble_discover_flag == PROCESS_FREE) + { + if ( ble_discovery() == false) + goto BT_ERROR; + + ble_discover_flag = PROCESS_TRYING; + } + + // bond create +// if( ble_discover_flag == PROCESS_COMPLETE && ble_bond_flag == PROCESS_FREE ) +// { +// if( pdevice ) +// { +// DBG( "Try bond referenceThing List. size=%d, cnt=%d", pdevice->size(), reg_bond_cnt ); +// if( reg_bond_cnt < pdevice->size() ) +// { +// BT_ERROR_CHECK(bt_device_create_bond( (pdevice->getNext(reg_bond_cnt))->remote_address )); +// ble_bond_flag = PROCESS_TRYING; +// } +//// for( int i = 0; i < pdevice->size(); i++ ) +//// BT_ERROR_CHECK(bt_device_create_bond( (pdevice->getNext(i))->remote_address )); +// } +// } + +// if( ble_bond_flag == PROCESS_COMPLETE ) + if ( ble_discover_flag == PROCESS_COMPLETE ) + break; + + continue ; + +BT_ERROR: + continue ; + } // if ( ble_adapter_flag ) + }// while(isThreadRun ) + + + while (isThreadRun) + { + // working process + workProcess( (void *)pdevice ); + } + + DBG("Exit."); + return 0; +} + + +/****************************** + * Callback Function definition. + */ + +// Called by adapter_enable / adapter_disable function. +void CbleBGthread::CB_adapter_state_change(int result, bt_adapter_state_e adapter_state, + void *user_data) +{ + DBG("callback called."); + + set_adapter_state_flag(); +} + +// Called by bt_adapter_start_device_discovery / bt_adapter_stop_device_discovery function. +void CbleBGthread::CB_discover_state_change(int result, + bt_adapter_device_discovery_state_e discovery_state, \ + bt_adapter_device_discovery_info_s *discovery_info, void *user_data) +{ + DBG("callback called."); +#if __INTERNAL_DEBUG_ + DBG("result = %d", result); +#endif + + if ( discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FOUND ) + { + CbleDevice *pdevice = (CbleDevice *)user_data; + + if ( discovery_info == NULL) + goto BT_ERROR; + +#if __INTERNAL_DEBUG_ + printf("=========== discovered device =============\n"); + printf("= address \t : %s \n", discovery_info->remote_address); + printf("= name \t : %s \n", discovery_info->remote_name); + printf("= rssi \t : %d \n", (discovery_info->rssi - 65535) ); + printf("= is_bonded\t : %d \n", discovery_info->is_bonded); + printf("= svc_count\t : %d \n", discovery_info->service_count); + printf("= dev_type \t : %d \n", discovery_info->device_type); + printf("===========================================\n"); +#endif + + find_referenceThing( discovery_info , pdevice ); + + if ( pdevice->isTimeOut() == true ) + { +#if __INTERNAL_DEBUG_ + DBG("Stop searching device."); +#endif + BT_ERROR_CHECK( bt_adapter_stop_device_discovery() ); + } + } + else if ( discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FINISHED ) + { +#if __INTERNAL_DEBUG_ + DBG("state == BT_ADAPTER_DEVICE_DISCOVERY_FINISHED"); +#endif + reg_bond_cnt = 0; + ble_discover_flag = PROCESS_COMPLETE; + } + + return ; + +BT_ERROR: + return ; +} + +// (*bt_device_bond_created_cb) +void CbleBGthread::CB_bond_create(int result, bt_device_info_s *device_info, void *user_data) +{ + DBG("callback called."); + if ( (bt_error_e)result != BT_ERROR_NONE ) + { + what_return_value( (bt_error_e)result ); + if ( (bt_error_e)result == BT_ERROR_REMOTE_DEVICE_NOT_FOUND ) + ble_bond_flag = PROCESS_FREE; + + return ; + } + + CbleDevice *pdevice = (CbleDevice *)user_data; + + if ( pdevice ) + { +#if __INTERNAL_DEBUG_ + printf("=========== bonded device =============\n"); + printf("= address \t : %s \n", device_info->remote_address); + printf("= name \t : %s \n", device_info->remote_name); + printf("= is_bonded\t : %d \n", device_info->is_bonded); + printf("= is_connec\t : %d \n", device_info->is_connected); + printf("= is_autho \t : %d \n", device_info->is_authorized); + printf("= svc_count\t : %d \n", device_info->service_count); + printf("===========================================\n"); +#endif + + if ( pdevice->find( std::string(device_info->remote_address) ) ) + { + reg_bond_cnt++; + ble_bond_flag = PROCESS_FREE; +#if __INTERNAL_DEBUG_ + DBG( "bonded_cnt = %d", reg_bond_cnt ); +#endif + } + + if ( reg_bond_cnt == pdevice->size() ) + { +#if __INTERNAL_DEBUG_ + DBG("bond_flag is PROCESS_COMPLETE"); +#endif + reg_bond_cnt = 0; + ble_bond_flag = PROCESS_COMPLETE; + } + } + + return ; +} + + + +/******************************** + * ETC. function definition. + */ +void CbleBGthread::set_adapter_state_flag(void) +{ + DBG("Enter."); + + // Get adapter state. + bt_adapter_state_e state; + BT_ERROR_CHECK( bt_adapter_get_state(&state) ); + + if ( state == BT_ADAPTER_ENABLED) + ble_adapter_flag = true; + else + ble_adapter_flag = false; + + return ; + +BT_ERROR: + DBG("Error Exception. Exit."); +} + +// return : true --> OK +// false --> ERROR +bool CbleBGthread::ble_discovery( void ) +{ + DBG("is Searching device."); + bool isDiscovery = false; + BT_ERROR_CHECK(bt_adapter_is_discovering(&isDiscovery)); + + if ( isDiscovery == false ) + { +#if __INTERNAL_DEBUG_ + DBG("Start searching device."); +#endif + BT_ERROR_CHECK( bt_adapter_start_device_discovery() ); + } + + return true; + +BT_ERROR: + return false; +} + +bool CbleBGthread::find_referenceThing( bt_adapter_device_discovery_info_s *discovery_info , + CbleDevice *pdevice ) +{ + DBG("Enter."); + + if ( strstr( discovery_info->remote_name, REF_NAME ) ) + { +#if __INTERNAL_DEBUG_ + DBG("Find %s device.", REF_NAME); + DBG("Register %s device to reference-Thing.", discovery_info->remote_name ); +#endif + pdevice->insert( discovery_info ); + } + + return true; +} + +void what_return_value( bt_error_e returnValue ) +{ + printf("\n"); + DBG("returnValue=%d", returnValue); + + switch (returnValue) + { + case BT_ERROR_NONE: + DBG("return value is BT_ERROR_NONE\n"); + break; + case BT_ERROR_CANCELLED: + DBG("return value is BT_ERROR_CANCELLED\n"); + break; + case BT_ERROR_INVALID_PARAMETER: + DBG("return value is BT_ERROR_INVALID_PARAMETER\n"); + break; + case BT_ERROR_OUT_OF_MEMORY: + DBG("return value is BT_ERROR_OUT_OF_MEMORY\n"); + break; + case BT_ERROR_RESOURCE_BUSY: + DBG("return value is BT_ERROR_RESOURCE_BUSY\n"); + break; + case BT_ERROR_TIMED_OUT: + DBG("return value is BT_ERROR_TIMED_OUT\n"); + break; + case BT_ERROR_NOW_IN_PROGRESS: + DBG("return value is BT_ERROR_NOW_IN_PROGRESS\n"); + break; + case BT_ERROR_NOT_INITIALIZED: + DBG("return value is BT_ERROR_NOT_INITIALIZED\n"); + break; + case BT_ERROR_NOT_ENABLED: + DBG("return value is BT_ERROR_NOT_ENABLED\n"); + break; + case BT_ERROR_ALREADY_DONE: + DBG("return value is BT_ERROR_ALREADY_DONE\n"); + break; + case BT_ERROR_OPERATION_FAILED: + DBG("return value is BT_ERROR_OPERATION_FAILED\n"); + break; + case BT_ERROR_NOT_IN_PROGRESS: + DBG("return value is BT_ERROR_NOT_IN_PROGRESS\n"); + break; + case BT_ERROR_REMOTE_DEVICE_NOT_BONDED: + DBG("return value is BT_ERROR_REMOTE_DEVICE_NOT_BONDED\n"); + break; + case BT_ERROR_AUTH_REJECTED: + DBG("return value is BT_ERROR_AUTH_REJECTED\n"); + break; + case BT_ERROR_AUTH_FAILED: + DBG("return value is BT_ERROR_AUTH_FAILED\n"); + break; + case BT_ERROR_REMOTE_DEVICE_NOT_FOUND: + DBG("return value is BT_ERROR_REMOTE_DEVICE_NOT_FOUND\n"); + break; + case BT_ERROR_SERVICE_SEARCH_FAILED: + DBG("return value is BT_ERROR_SERVICE_SEARCH_FAILED\n"); + break; + case BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED: + DBG("return value is BT_ERROR_REMOTE_DEVICE_NOT_CONNECTED\n"); + break; + case BT_ERROR_PERMISSION_DENIED: + DBG("return value is BT_ERROR_PERMISSION_DENIED\n"); + break; + } +} + + +//int bt_adapter_get_le_state ( bt_adapter_le_state_e * adapter_le_state ) +//bt_adapter_le_enable() +// bt_adapter_get_state() + +// bt_adapter_start_device_discovery(). +// bt_adapter_device_discovery_state_changed_cb(). +// bt_device_connect_le(). +// bt_device_gatt_state_changed_cb(). +// bt_device_read_rssi_value(const char *address); + + +//int bt_device_set_connection_state_changed_cb(bt_device_connection_state_changed_cb callback, void *user_data); +//typedef void (*bt_device_connection_state_changed_cb)(bool connected, const char *remote_address, void *user_data); + + +// bt_adapter_start_device_discovery(). +// bt_adapter_device_discovery_state_changed_cb(). +// bt_device_create_bond() +// bt_device_bond_created_cb(). +// bt_device_set_alias(address,name) diff --git a/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_proximity.cpp b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_proximity.cpp new file mode 100644 index 0000000..de501cc --- /dev/null +++ b/service/soft-sensor-manager/SoftSensorPlugin/IndoorTrajectorySensor/src/tizen_proximity.cpp @@ -0,0 +1,446 @@ +/****************************************************************** +* +* 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 +#include +#include "tizen_log.h" +#include +#include +#include "tizen_proximity.h" +#include "tizen_CbleDevice.h" +#include "lib_proximity.h" + +#include "ITS.h" + +CProximity *prox = NULL; +ITSName::Things *output = NULL; +int CProximity::get_rssi_cnt = 0; +int CProximity::num_set_rssi = 0; +int CProximity::loop_flag = JOB_GET_RSSI; +CProximity::rssiMAP CProximity::map_rssi; + +// Proximity variables +int **rssi = 0; +int *rssicnt = 0; +int *startindex = 0; +int *flag = 0; + + +void proximity_init( void *(*func)(void *) ) +{ +#if __INTERNAL_DEBUG_ + DBG("Enter."); +#endif + prox = new CProximity( func ); + output = NULL; +} + +void proximity_loop( void *param ) +{ +// DBG("called. main loop function."); + CbleDevice *pdevice = (CbleDevice *)param; + + if ( prox == NULL || pdevice == NULL ) + { + DBG("Error : proximity_loop is occurred error."); + return ; + } + + // Get BLE RSSI and Calculate Proximity value. ( choi job ) + if ( prox->loop_flag == JOB_GET_RSSI ) + { + prox->GetRSSI( pdevice ); + prox->loop_flag = JOB_BUSY; + } + + if ( prox->loop_flag == JOB_GET_PROX ) + { + prox->GetProximity( pdevice ); + prox->loop_flag = JOB_PUT_OUTPUT; + } + + if ( prox->loop_flag == JOB_PUT_OUTPUT ) + { + // Result Setting and transmit data from proximity to ITS + prox->set_output( pdevice ); + pthread_create(&prox->Thandle, NULL, prox->threadFunc, output); + prox->loop_flag = JOB_GET_RSSI; + } + + usleep(100); +// DBG("Exit."); +} + + + + +/**************************************** + * + * CProximity class definition. + * + */ + +CProximity::CProximity( workfunc func ) +{ +#if __INTERNAL_DEBUG_ + DBG("Enter."); +#endif + if ( set_threadFunc(func) == false) + DBG("Error: set_threadFunc is failed."); + + loop_flag = JOB_GET_RSSI; + get_rssi_cnt = 0; + num_set_rssi = 0; + + reference_ea = 0; + m_distance = 0; + m_proximity = 0; + map_rssi.clear(); +} + +CProximity::~CProximity( void ) +{ +#if __INTERNAL_DEBUG_ + DBG("Enter."); +#endif + if ( rssi ) + { + delete [] rssi; + rssi = NULL; + } + + if ( rssicnt ) + { + delete rssicnt; + rssicnt = NULL; + } + + if ( startindex ) + { + delete startindex; + startindex = NULL; + } + + if ( flag ) + { + delete flag; + flag = NULL; + } + + if ( m_distance ) + { + delete m_distance; + m_distance = NULL; + } + + if ( m_proximity ) + { + delete m_proximity; + m_proximity = NULL; + } + +} + +bool CProximity::find_referenceThing( bt_adapter_device_discovery_info_s *discovery_info , + CbleDevice *pdevice ) +{ +#if __INTERNAL_DEBUG_ + DBG("Enter"); +#endif + if ( pdevice->find(discovery_info->remote_address) == false ) + { + return false; + } +#if __INTERNAL_DEBUG_ + DBG("Find %s device.", discovery_info->remote_address); +#endif + if ( pdevice->setRSSI( discovery_info->remote_address, + discovery_info->rssi ) == discovery_info->rssi ) + { + map_rssi[ discovery_info->remote_address ].init( RSSI_EA ); + map_rssi[ discovery_info->remote_address ].rssi[get_rssi_cnt - 1] = discovery_info->rssi - 65535; +#if __INTERNAL_DEBUG_ + DBG("Get RSSI. %d", map_rssi[ discovery_info->remote_address ].rssi[get_rssi_cnt - 1] ); +#endif + num_set_rssi++; + } + + return true; +} + +// Called by bt_adapter_start_device_discovery / bt_adapter_stop_device_discovery function. +void CProximity::CB_discover_state_change(int result, + bt_adapter_device_discovery_state_e discovery_state, \ + bt_adapter_device_discovery_info_s *discovery_info, void *user_data) +{ + DBG("callback called."); +#if __INTERNAL_DEBUG_ + DBG("result = %d", result); +#endif + + CbleDevice *pdevice = (CbleDevice *)user_data; + + if ( discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FOUND ) + { + if ( discovery_info == NULL) + goto BT_ERROR; +#if __INTERNAL_DEBUG_ + printf("=========== Get RSSI =============\n"); + printf("= address \t : %s \n", discovery_info->remote_address); + printf("= name \t : %s \n", discovery_info->remote_name); + printf("= rssi \t : %d \n", (discovery_info->rssi - 65535) ); + printf("===========================================\n"); +#endif + find_referenceThing( discovery_info , pdevice ); + + if ( num_set_rssi == pdevice->size() ) + { +#if __INTERNAL_DEBUG_ + DBG("Stop searching device."); +#endif + BT_ERROR_CHECK( bt_adapter_stop_device_discovery() ); + } + } + else if ( discovery_state == BT_ADAPTER_DEVICE_DISCOVERY_FINISHED ) + { + DBG("state == BT_ADAPTER_DEVICE_DISCOVERY_FINISHED"); + + num_set_rssi = 0; + if ( get_rssi_cnt == RSSI_EA ) + { + get_rssi_cnt = 0; + loop_flag = JOB_GET_PROX; + } + else + loop_flag = JOB_GET_RSSI; + } + + return ; + +BT_ERROR: + return ; +} + + +bool CProximity::GetRSSI(CbleDevice *pdevice) +{ +#if __INTERNAL_DEBUG_ + DBG("Enter"); +#endif + if ( num_set_rssi == 0 && get_rssi_cnt == 0) + map_rssi.clear(); + + num_set_rssi = 0; + get_rssi_cnt++; + + for ( int i = 0; i < pdevice->size(); i++ ) + pdevice->setRSSI( (pdevice->getNext(i))->remote_address, 0); + + BT_ERROR_CHECK( bt_adapter_set_device_discovery_state_changed_cb( + CProximity::CB_discover_state_change, pdevice) ); + + BT_ERROR_CHECK( bt_adapter_start_device_discovery() ); + + return true; + +BT_ERROR: + return false; +} + +bool is_first = true; +void CProximity::GetProximity(CbleDevice *pdevice) +{ +#if __INTERNAL_DEBUG_ + DBG("Enter."); +#endif +//#if __INTERNAL_DEBUG_ + DBG("thing ea = %d", map_rssi.size() ); + DBG("RSSI ea = %d", RSSI_EA ); + + for (int num = 0; num < map_rssi.size(); num++ ) + { + std::string addr = pdevice->getNext(num)->remote_address; + DBG("Addr -> %s", addr.c_str() ); + for (int i = 0; i < RSSI_EA ; i++) + DBG(" %d th. rssi = %d", i, map_rssi[addr].rssi[i] ); + } +//#endif + + reference_ea = map_rssi.size(); + float *avg = new float[reference_ea]; + + if ( is_first ) + prox_first_setting( reference_ea ); + + for (int i = 0; i < reference_ea; i++) + { + std::string addr = pdevice->getNext(i)->remote_address; + + if ( rssicnt[i] > arraysize - 1) + rssicnt[i] = rssicnt[i] % arraysize; + + for (int j = 0; j < RSSI_EA; j++) + { + rssi[i][rssicnt[i]] = map_rssi[addr].rssi[j]; + rssicnt[i]++; + } + + avg[i] = CalculateExponentialAverage(RSSI_EA, rssi[i], startindex[i], flag[i]); + m_distance[i] = calculateDistance(avg[i], -58); + + if ( m_distance[i] <= 1.0 ) + { + m_proximity[i] = 1; + } + else if (m_distance[i] <= 2) + { + m_proximity[i] = 2; + } + else + { + m_proximity[i] = 3; + } + + DBG("distance = %f", m_distance[i]); + DBG("proximity = %d", m_proximity[i]); + //Serial.println(calculateDistance(avg[i], -58)); + startindex[i] += RSSI_EA; + + if (startindex[i] >= arraysize) + { + startindex[i] = 0; + } + + if (flag[i] < (arraysize / RSSI_EA)) + { + flag[i]++; + } + } // for + + delete avg; +} + +bool CProximity::set_threadFunc(workfunc func) +{ +#if __INTERNAL_DEBUG_ + DBG("Enter."); +#endif + if ( func == NULL ) + { + DBG("Error: func is null."); + return false; + } + + threadFunc = func; + return true; +} + +CProximity::workfunc CProximity::get_threadFunc(void) +{ + return threadFunc; +} + +void CProximity::set_output( CbleDevice *pdevice ) +{ +#if __INTERNAL_DEBUG_ + DBG("Enter."); +#endif + + if (output) + { + delete output; + output = NULL; + } + + if ( output == NULL ) + { + output = new ITSName::Things(reference_ea); + } + + if ( output == NULL ) + { + DBG("Error : output is NULL."); + return ; + } + + // Set Output value. + for (int i = 0; i < reference_ea; i++) + { + output->things[i].ID = pdevice->getNext(i)->remote_address; + output->things[i].SD = 0.0; + output->things[i].distance = m_distance[i]; + output->things[i].proximity = m_proximity[i]; + } +} + + + + +void CProximity::prox_first_setting( int reference_ea ) +{ + if ( rssi == NULL ) + { + rssi = new int *[reference_ea]; + + for (int i = 0; i < reference_ea; i++) + { + rssi[i] = new int[arraysize]; + for (int j = 0; j < arraysize; j++) + rssi[i][j] = 0; + } + } + + if ( rssicnt == NULL ) + { + rssicnt = new int[reference_ea]; + for (int j = 0; j < reference_ea; j++) + rssicnt[j] = 0; + } + + if ( startindex == NULL ) + { + startindex = new int[reference_ea]; + for (int j = 0; j < reference_ea; j++) + startindex[j] = 0; + } + + if ( flag == NULL) + { + flag = new int[reference_ea]; + for (int j = 0; j < reference_ea; j++) + flag[j] = 0; + } + + if ( m_distance == NULL ) + { + m_distance = new float[reference_ea]; + for (int j = 0; j < reference_ea; j++) + m_distance[j] = 0; + } + + if ( m_proximity == NULL ) + { + m_proximity = new int[reference_ea]; + for (int j = 0; j < reference_ea; j++) + m_proximity[j] = 0; + } + + is_first = false; +} \ No newline at end of file -- 2.7.4