[SSM] Reference & Trackee Thing release for arduino
authormin7.choi <min7.choi@samsung.com>
Thu, 18 Dec 2014 07:34:08 +0000 (16:34 +0900)
committermin7.choi <min7.choi@samsung.com>
Thu, 18 Dec 2014 07:45:03 +0000 (16:45 +0900)
1. Reference Thing code release for arduino
2. Trackee Thing code release for arduino

Change-Id: Ib05327af485289dba1b4a1d0ee2b143b5434ab15
Signed-off-by: min7.choi <min7.choi@samsung.com>
20 files changed:
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/bleLib.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/include/oic_lanLib.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/bleLib.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/oic_lanLib.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/readme.txt [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/reference.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/makefile [moved from service/soft-sensor-manager/SampleApp/arduino/THSensorApp/build/Makefile with 100% similarity]
service/soft-sensor-manager/SampleApp/arduino/THSensorApp/src/thserver.cpp
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/bleLib.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/oic_lanLib.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/proximity.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/bleLib.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/oic_lanLib.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/proximity.cpp [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/readme.txt [new file with mode: 0644]
service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/trackee.cpp [new file with mode: 0644]
service/soft-sensor-manager/build/arduino/local.properties

diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/build/makefile
new file mode 100644 (file)
index 0000000..6df468b
--- /dev/null
@@ -0,0 +1,130 @@
+# //******************************************************************
+# //
+# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+# //
+# // Licensed under the Apache License, Version 2.0 (the "License");
+# // you may not use this file except in compliance with the License.
+# // You may obtain a copy of the License at
+# //
+# //      http://www.apache.org/licenses/LICENSE-2.0
+# //
+# // Unless required by applicable law or agreed to in writing, software
+# // distributed under the License is distributed on an "AS IS" BASIS,
+# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# // See the License for the specific language governing permissions and
+# // limitations under the License.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+-include ../../../../build/arduino/environment.mk
+ARDUINO_DIR = /usr/share/arduino
+
+BUILD := release
+PLATFORM := arduinomega
+ARDUINO_PORT := 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
+LOGGER_DIR = $(TB_DIR)/logger
+OC_LOG_DIR = $(TB_DIR)/../oc_logger
+TBSTACK_DIR = $(TB_DIR)/stack
+TBSOCKET_DIR = $(TB_DIR)/ocsocket
+
+include $(TB_DIR)/local.properties
+include $(TB_DIR)/$(PLATFORM).properties
+
+VPATH := $(SDIR_ARD_PLATFORM)
+
+#include directories
+OCSOCK_DIR = $(TB_DIR)/ocsocket
+LOGGER_DIR = $(TB_DIR)/logger
+STACK_DIR  = $(TB_DIR)/stack
+INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include -I../include
+
+CC_FLAGS.debug         := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic
+CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
+
+CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG
+
+ifeq ($(ARDUINOWIFI),1)
+       CFLAGS += -DARDUINOWIFI
+       ARDUINO_SHIELD_TYPE := "/wifi_shield"
+       TRANSPORT_OBJS = $(WIFI_COBJ)
+else
+       ARDUINO_SHIELD_TYPE := "/ethernet_shield"
+       TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
+endif
+
+OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
+
+OBJ_DIR := $(OUT_DIR)/bin
+
+all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
+
+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) $@
+
+prep_dirs:
+       -mkdir $(PLATFORM)
+       -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
+       -mkdir $(OUT_DIR)
+       -mkdir $(OBJ_DIR)
+
+%.o: %.c
+       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+%.o: %.cpp
+       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ 
+%.o: ${SRC_PATH}/%.cpp
+       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+
+$(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)/$@
+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
+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)/$@
+else ifeq ($(PLATFORM),arduinodue)
+       $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+install: all
+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
+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
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+.PHONY: clean
+
+clean: legacy_clean
+       rm -rf arduinomega
+       rm -rf arduinodue
+
+legacy_clean:
+       @rm -rf bin
+       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
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
new file mode 100644 (file)
index 0000000..8356098
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * bleLib.h
+ *
+ *  Created on: 2014. 11. 5.
+ *      Author: eunseok
+ */
+
+#ifndef BLELIB_H_
+#define BLELIB_H_
+
+#include "Arduino.h"
+
+#define BLE_NOCHANGE   -1
+#define BLE_MASTER             1
+#define BLE_SLAVER             0
+
+#define BLE_DISCON             200
+#define BLE_NODATA             100
+
+
+/***************************************
+ *
+ *     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 );
+};
+
+
+
+#if 0
+#define debug_printf(...)      {                                                       \
+       char* __temp__ = (char*)malloc(sizeof(char)*2048);              \
+       sprintf(__temp__, __VA_ARGS__ );                                        \
+       Serial.print(__temp__);                                                                 \
+       free(__temp__);                                                                                                 \
+}
+#else
+#define debug_printf(...)
+#endif
+
+
+
+#endif /* BLELIB_H_ */
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
new file mode 100644 (file)
index 0000000..41556f6
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * oic_lanLib.h
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#ifndef OIC_LANLIB_H_
+#define OIC_LANLIB_H_
+
+
+int ConnectToNetwork();
+
+
+#endif /* OIC_WIFILIB_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
new file mode 100644 (file)
index 0000000..c4e12d3
--- /dev/null
@@ -0,0 +1,584 @@
+/*
+ * blsLib.cpp
+ *
+ *  Created on: 2014. 11. 5.
+ *      Author: eunseok
+ */
+
+#include "bleLib.h"
+#include <stdarg.h>
+
+#define ARDUINO                        1
+//#define __INTERNAL_DEBUG__           1
+
+
+#define LIMIT_COUNT                    100
+#define DUMMY_SIZE                     30
+#define DEBUG_SIZE                     DUMMY_SIZE
+#if (ARDUINO != 0)
+#define SERIAL_SIZE                    100
+#endif
+
+#define BLE            Serial2
+
+bool isConnected = false;
+int SerialCnt=0;
+int BLECnt=0;
+char SelfMaxaddr[19] = {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)
+{
+       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);
+}
+
+bool Cble::IsConnected( void )
+{
+       return isConnected;
+}
+
+bool Cble::IsSelfArduino( void )
+{
+#ifdef __INTERNAL_DEBUG__
+       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;
+       }
+}
+
+bool Cble::pollingConnect( const char* maxAddr )
+{
+#ifdef __INTERNAL_DEBUG__
+       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;
+
+#undef CONNECT_SIZE
+}
+
+
+#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);
+               }
+       }
+#endif
+
+       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 :
+#ifdef __INTERNAL_DEBUG__
+               debug_printf("res= %s \r\n",rssi_res);
+#endif
+               char* Srssi = &(rssi_res[RSSI_POS]);
+               int rssi = atoi(Srssi);
+
+               return rssi;
+       }
+
+       return BLE_DISCON;
+
+#undef RSSI_POS
+#undef RSSI_SIZE
+}
+
+int Cble::mustHaveRequest(const char* request, char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       BLE.write(request);
+       BLE.flush();
+       delay(150);
+
+READ_STREAM :
+       while( (length=BLE.readBytes(data_index, required_length)) == 0 )
+       {
+               cnt++;
+               delay(10);
+
+               if ( cnt >= LIMIT_COUNT/10 )
+               {
+#ifdef __INTERNAL_DEBUG__
+                       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;
+       }
+
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("[ %s ] %s\r\n\r\n", request, data);
+#endif
+       return 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;
+
+       BLE.write(request);
+       BLE.flush();
+
+       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;
+               }
+
+#ifdef __INTERNAL_DEBUG__
+               debug_printf("[ %s ] %s\r\n\r\n", request, data);
+#endif
+       }
+       return true;
+}
+
+void Cble::streamDummy( char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       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);
+#ifdef __INTERNAL_DEBUG__
+                       debug_printf("[ streamDummy ] %s\r\n\r\n", debugD);
+#endif
+                       memset(debugD, 0, DEBUG_SIZE);
+               }
+       }
+
+}
+
+#if (ARDUINO != 0)
+
+#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;
+                       }
+               }
+       }
+}
+
+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* Cble::Debug2BLE( int BLEwrite )
+{
+        return NULL;
+}
+#endif
+
+void Cble::FactoryReset( void )
+{
+       debug_printf("FactoryReset is called.\r\n");
+
+       pollingRequest("AT+RENEW", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+}
+
+
+void Cble::firstUartSetting( void )
+{
+       debug_printf("firstUartSetting is called.\r\n");
+
+       Serial.begin(9600);
+       BLE.begin(9600);
+       BLE.setTimeout(1);
+       delay(1000);
+
+       pollingRequest("AT+BAUD4", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+
+       debug_printf("Please Power off and on.\r\n");
+       BLE.end();
+//     delay(1000);
+//
+//     BLE.begin(115200);
+//     delay(1000);
+//
+//     pollingRequest("AT", debugD, DEBUG_SIZE);
+//     memset(debugD, 0, DEBUG_SIZE);
+
+
+       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
new file mode 100644 (file)
index 0000000..c4a4f26
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * oic_wifiLib.cpp
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+// proximity code e
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#else
+// Arduino Ethernet Shield
+#include <EthernetServer.h>
+#include <Ethernet.h>
+#include <Dns.h>
+#include <EthernetClient.h>
+#include <util.h>
+#include <EthernetUdp.h>
+#include <Dhcp.h>
+#endif
+
+
+PROGMEM const char TAG[] = "ReferenceSensor";
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
+// this server will NOT be listening on 224.0.1.187 multicast address.
+
+/// WiFi Shield firmware with Intel patches
+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";
+
+int ConnectToNetwork()
+{
+    char *fwVersion;
+    int status = WL_IDLE_STATUS;
+    // check for the presence of the shield:
+    if (WiFi.status() == WL_NO_SHIELD)
+    {
+        OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
+        return -1;
+    }
+
+    // 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 )
+    {
+        OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
+        return -1;
+    }
+
+    // attempt to connect to Wifi network:
+    while (status != WL_CONNECTED)
+    {
+        OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
+        status = WiFi.begin(ssid,pass);
+
+        // wait 10 seconds for connection:
+        delay(10000);
+    }
+    OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
+
+    IPAddress ip = WiFi.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#else
+// Arduino Ethernet Shield
+int ConnectToNetwork()
+{
+    // Note: ****Update the MAC address here with your shield's MAC address****
+    uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xB8, 0xAC};
+
+    uint8_t error = Ethernet.begin(ETHERNET_MAC);
+    if (error  == 0)
+    {
+        OC_LOG_V(ERROR, TAG, "error is: %d", error);
+        return -1;
+    }
+    IPAddress ip = Ethernet.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#endif //ARDUINOWIFI
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/readme.txt b/service/soft-sensor-manager/SampleApp/arduino/Reference_Thing/src/readme.txt
new file mode 100644 (file)
index 0000000..7c041e1
--- /dev/null
@@ -0,0 +1,19 @@
+
+Followings should be done befor building Arudno applications 
+
+1. Applications on arduino conform  the Iotivity Base released on 22-Aug-2014.
+   (Ver. 22th Aug(oic-resource: commit: cdeeed62bd9b11beb2cdd340168e766088c18dac [cdeeed6]))
+
+   For successful execution, you have to copy the file, local.properties, into the following pathes:
+    - oic-resource/csdk/
+    - oic-resource/csdk/libcoap-4.1.1
+
+
+2. Time.c, Time.h should be copied in your machine and they should be refered in the Makefile as followings
+
+   Makefile path:  / oic-resource / csdk / libcoap-4.1.1 / makefile
+
+   path to be modified: 
+  
+     - INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time ---> for Time.h
+     - SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time ---> for Time.c
\ No newline at end of file
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
new file mode 100644 (file)
index 0000000..953032e
--- /dev/null
@@ -0,0 +1,308 @@
+//******************************************************************
+//
+// 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 <stdio.h>
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#include "oic_lanLib.h"
+
+#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
+
+#define JSON_BASE00 "{\"href\":\"\",\"rep\":{"
+#define JSON_BASE01 "\"0\":\"MAC\",\"1\":\"string\",\"2\":\""
+#define JSON_BASE02 "\",\"3\":\"SERVICETYPE\",\"4\":\"string\",\"5\":\""
+#define JSON_BASE03 "\"}}"
+
+typedef struct REFERRESOURCE {
+    OCResourceHandle m_handle;
+    char* m_macaddress;
+    char* m_servicetype;
+} REFERResource;
+
+PROGMEM const char TAG[] = "ReferenceSensor";
+
+REFERResource REFER;
+Cble ble;
+
+char macaddress[13]={"9059AF1704D7"};
+char servicetype[15]={"BOOK"};
+
+int g_REFERUnderObservation = 0;
+
+const char *getResult(OCStackResult result);
+void createREFERResource();
+
+#define LENGTH_VAR             100
+static int base_length = 0;
+
+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;
+       }
+
+       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);
+
+       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;
+    OCEntityHandlerResponse response = {0};
+    char payload[MAX_RESPONSE_LENGTH] = {0};
+
+    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    {
+        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
+        if(OC_REST_GET == entityHandlerRequest->method)
+        {
+                if(JsonGenerator( REFER, payload, MAX_RESPONSE_LENGTH))
+                {
+                }
+           else
+            {
+                ehRet = OC_EH_ERROR;
+            }
+        }
+        if(OC_REST_PUT == entityHandlerRequest->method)
+        {
+            //Do something with the 'put' payload
+            if (JsonGenerator( REFER, payload, MAX_RESPONSE_LENGTH))
+            {
+            }
+            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)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
+            g_REFERUnderObservation = 1;
+        }
+        else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
+        {
+            OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
+        }
+    }
+
+    return ehRet;
+}
+
+
+char tempdata[200];
+void ChangeREFERRepresentation (void *param)
+{
+       (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));
+
+       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);
+
+   REFER.m_macaddress = macaddress;
+   REFER.m_servicetype = servicetype;
+
+       // Add your initialization code here
+       OC_LOG_INIT();
+
+       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;
+       }
+
+       // 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();
+
+       ble.init( (long)115200, BLE_SLAVER,  REFER.m_macaddress);
+
+//     ble.StatusRead();
+
+       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);
+
+       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.
+
+    // 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;
+       }
+}
+
+void createREFERResource() {
+
+    OCStackResult res = OCCreateResource(&REFER.m_handle,
+                                         "SoftSensorManager.Sensor",
+                                         "oc.mi.def",
+                                         "/Reference_Thing",
+                                         OCEntityHandlerCb,
+                                         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";
+    }
+}
+
index 28cb319..fe41441 100644 (file)
@@ -58,9 +58,6 @@ typedef struct THRESOURCE
 
 static THResource TH;
 
-//char* g_responsePayloadPut =    "{\"href\":\"\",\"rep\":{\"0\":\"temperature\",\"1\":\"int\",\"2\":\"0\",\"3\":\"humidity\",\"4\":\"int\",\"5\":\"0\"}}";
-//char* g_responsePayloadGet =    "{\"href\":\"\",\"rep\":{\"0\":\"temperature\",\"1\":\"int\",\"2\":\"0\",\"3\":\"humidity\",\"4\":\"int\",\"5\":\"0\"}}";
-
 /// This is the port which Arduino Server will use for all unicast communication with it's peers
 static uint16_t OC_WELL_KNOWN_PORT = 5683;
 
@@ -71,23 +68,23 @@ static uint16_t OC_WELL_KNOWN_PORT = 5683;
 
 char temp[100];
 
-#define LENGTH_VAR      100
+#define LENGTH_VAR             100
 static int base_length = 0;
 
-bool JsonGenerator( THResource &th, char *jsonBuf, uint16_t buf_length )
+bool JsonGenerator( THResource& th, 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"%d", th.m_temp);
-    sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%d"JSON_BASE03, th.m_humid);
+       sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%d",th.m_temp);
+       sprintf(jsonBuf+strlen(jsonBuf), JSON_BASE02"%d"JSON_BASE03, th.m_humid);
 
-    Serial.println(jsonBuf);
+       Serial.println(jsonBuf);
 
-    return true;
+       return true;
 }
 
 byte read_dht11_dat()
@@ -196,46 +193,67 @@ 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( TH, (char *)entityHandlerRequest->resJSONPayload, \
-                               entityHandlerRequest->resJSONPayloadLen))
-            {
-            }
-            else
+               if(JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
+                {
+                }
+           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( TH, (char *)entityHandlerRequest->resJSONPayload, \
-                               entityHandlerRequest->resJSONPayloadLen))
+            if (JsonGenerator( TH, payload, MAX_RESPONSE_LENGTH))
             {
             }
             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_THUnderObservation = 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"));
         }
@@ -301,7 +319,7 @@ void *ChangeTHRepresentation (void *param)
         TH.m_humid = dht11_dat[0];
         TH.m_temp = dht11_dat[2];
 
-        if (g_THUnderObservation)
+           if (g_THUnderObservation)
         {
             OC_LOG_V(INFO, TAG, " =====> Notifying stack of new humid level %d\n", TH.m_humid);
             OC_LOG_V(INFO, TAG, " =====> Notifying stack of new temp level %d\n", TH.m_temp);
@@ -344,7 +362,7 @@ void setup()
         OC_LOG(ERROR, TAG, PCF("OCStack init error"));
         return;
     }
-
+    OCStartPresence(60);
     // Declare and create the example resource: TH
     createTHResource();
 
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/build/makefile
new file mode 100644 (file)
index 0000000..d21b780
--- /dev/null
@@ -0,0 +1,130 @@
+# //******************************************************************
+# //
+# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+# //
+# // Licensed under the Apache License, Version 2.0 (the "License");
+# // you may not use this file except in compliance with the License.
+# // You may obtain a copy of the License at
+# //
+# //      http://www.apache.org/licenses/LICENSE-2.0
+# //
+# // Unless required by applicable law or agreed to in writing, software
+# // distributed under the License is distributed on an "AS IS" BASIS,
+# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# // See the License for the specific language governing permissions and
+# // limitations under the License.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+-include ../../../../build/arduino/environment.mk
+ARDUINO_DIR = /usr/share/arduino
+
+BUILD := release
+PLATFORM := arduinomega
+ARDUINO_PORT := 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 := trackee
+
+TB_DIR = ../../../../../../resource/csdk
+LOGGER_DIR = $(TB_DIR)/logger
+OC_LOG_DIR = $(TB_DIR)/../oc_logger
+TBSTACK_DIR = $(TB_DIR)/stack
+TBSOCKET_DIR = $(TB_DIR)/ocsocket
+
+include $(TB_DIR)/local.properties
+include $(TB_DIR)/$(PLATFORM).properties
+
+VPATH := $(SDIR_ARD_PLATFORM)
+
+#include directories
+OCSOCK_DIR = $(TB_DIR)/ocsocket
+LOGGER_DIR = $(TB_DIR)/logger
+STACK_DIR  = $(TB_DIR)/stack
+INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include -I../include
+
+CC_FLAGS.debug         := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic
+CC_FLAGS.release       := -Os -Wall -c -fmessage-length=0 -fpic
+
+CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG
+
+ifeq ($(ARDUINOWIFI),1)
+       CFLAGS += -DARDUINOWIFI
+       ARDUINO_SHIELD_TYPE := "/wifi_shield"
+       TRANSPORT_OBJS = $(WIFI_COBJ)
+else
+       ARDUINO_SHIELD_TYPE := "/ethernet_shield"
+       TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
+endif
+
+OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)
+
+OBJ_DIR := $(OUT_DIR)/bin
+
+all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
+
+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) $@
+
+prep_dirs:
+       -mkdir $(PLATFORM)
+       -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE)
+       -mkdir $(OUT_DIR)
+       -mkdir $(OBJ_DIR)
+
+%.o: %.c
+       $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+%.o: %.cpp
+       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ 
+%.o: ${SRC_PATH}/%.cpp
+       $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@
+
+$(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)/$@
+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
+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)/$@
+else ifeq ($(PLATFORM),arduinodue)
+       $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+install: all
+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
+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
+else
+       $(error Wrong value for PLATFORM !!)
+endif
+
+.PHONY: clean
+
+clean: legacy_clean
+       rm -rf arduinomega
+       rm -rf arduinodue
+
+legacy_clean:
+       @rm -rf bin
+       @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *-
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
new file mode 100644 (file)
index 0000000..8356098
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * bleLib.h
+ *
+ *  Created on: 2014. 11. 5.
+ *      Author: eunseok
+ */
+
+#ifndef BLELIB_H_
+#define BLELIB_H_
+
+#include "Arduino.h"
+
+#define BLE_NOCHANGE   -1
+#define BLE_MASTER             1
+#define BLE_SLAVER             0
+
+#define BLE_DISCON             200
+#define BLE_NODATA             100
+
+
+/***************************************
+ *
+ *     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 );
+};
+
+
+
+#if 0
+#define debug_printf(...)      {                                                       \
+       char* __temp__ = (char*)malloc(sizeof(char)*2048);              \
+       sprintf(__temp__, __VA_ARGS__ );                                        \
+       Serial.print(__temp__);                                                                 \
+       free(__temp__);                                                                                                 \
+}
+#else
+#define debug_printf(...)
+#endif
+
+
+
+#endif /* BLELIB_H_ */
diff --git a/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/oic_lanLib.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/oic_lanLib.h
new file mode 100644 (file)
index 0000000..41556f6
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * oic_lanLib.h
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#ifndef OIC_LANLIB_H_
+#define OIC_LANLIB_H_
+
+
+int ConnectToNetwork();
+
+
+#endif /* OIC_WIFILIB_H_ */
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
new file mode 100644 (file)
index 0000000..8e8666a
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * proximity.h
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#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/SampleApp/arduino/Trackee_Thing/include/trackee.h b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/include/trackee.h
new file mode 100644 (file)
index 0000000..4271904
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * trackee.h
+ *
+ *  Created on: 2014. 11. 18.
+ *      Author: eunseok
+ */
+
+#ifndef TRACKEE_H_
+#define TRACKEE_H_
+
+
+#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
new file mode 100644 (file)
index 0000000..31cf5da
--- /dev/null
@@ -0,0 +1,586 @@
+/*
+ * blsLib.cpp
+ *
+ *  Created on: 2014. 11. 5.
+ *      Author: eunseok
+ */
+
+#include "bleLib.h"
+#include <stdarg.h>
+#include "trackee.h"
+
+//#define __INTERNAL_DEBUG__           1
+
+PROGMEM const char TAG[] = "TrackeeSensor";
+#define LIMIT_COUNT                    100
+#define DUMMY_SIZE                     30
+#define DEBUG_SIZE                     DUMMY_SIZE
+#if (ARDUINO != 0)
+#define SERIAL_SIZE                    100
+#endif
+
+#define BLE            Serial2
+
+bool isConnected = false;
+int SerialCnt=0;
+int BLECnt=0;
+char SelfMaxaddr[19] = {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)
+{
+       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);
+}
+
+bool Cble::IsConnected( void )
+{
+       return isConnected;
+}
+
+bool Cble::IsSelfArduino( void )
+{
+#ifdef __INTERNAL_DEBUG__
+       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;
+       }
+}
+
+bool Cble::pollingConnect( const char* maxAddr )
+{
+#ifdef __INTERNAL_DEBUG__
+       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;
+
+#undef CONNECT_SIZE
+}
+
+
+#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);
+               }
+       }
+#endif
+
+       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 :
+#ifdef __INTERNAL_DEBUG__
+               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);
+
+               return rssi;
+       }
+
+       return BLE_DISCON;
+
+#undef RSSI_POS
+#undef RSSI_SIZE
+}
+
+int Cble::mustHaveRequest(const char* request, char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       BLE.write(request);
+       BLE.flush();
+       delay(150);
+
+READ_STREAM :
+       while( (length=BLE.readBytes(data_index, required_length)) == 0 )
+       {
+               cnt++;
+               delay(10);
+
+               if ( cnt >= LIMIT_COUNT/10 )
+               {
+#ifdef __INTERNAL_DEBUG__
+                       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;
+       }
+
+#ifdef __INTERNAL_DEBUG__
+       debug_printf("[ %s ] %s\r\n\r\n", request, data);
+#endif
+       return 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;
+
+       BLE.write(request);
+       BLE.flush();
+
+       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;
+               }
+
+#ifdef __INTERNAL_DEBUG__
+               debug_printf("[ %s ] %s\r\n\r\n", request, data);
+#endif
+       }
+       return true;
+}
+
+void Cble::streamDummy( char* data, int dataLen)
+{
+       int cnt=0;
+       int length=0;
+       int required_length = dataLen;
+       char* data_index = data;
+
+       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);
+#ifdef __INTERNAL_DEBUG__
+                       debug_printf("[ streamDummy ] %s\r\n\r\n", debugD);
+#endif
+                       memset(debugD, 0, DEBUG_SIZE);
+               }
+       }
+
+}
+
+#if (ARDUINO != 0)
+
+#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;
+                       }
+               }
+       }
+}
+
+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* Cble::Debug2BLE( int BLEwrite )
+{
+        return NULL;
+}
+#endif
+
+void Cble::FactoryReset( void )
+{
+       debug_printf("FactoryReset is called.\r\n");
+
+       pollingRequest("AT+RENEW", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+}
+
+
+void Cble::firstUartSetting( void )
+{
+       debug_printf("firstUartSetting is called.\r\n");
+
+       Serial.begin(9600);
+       BLE.begin(9600);
+       BLE.setTimeout(1);
+       delay(1000);
+
+       pollingRequest("AT+BAUD4", debugD, 8);
+       memset(debugD, 0, DEBUG_SIZE);
+
+       debug_printf("Please Power off and on.\r\n");
+       BLE.end();
+//     delay(1000);
+//
+//     BLE.begin(115200);
+//     delay(1000);
+//
+//     pollingRequest("AT", debugD, DEBUG_SIZE);
+//     memset(debugD, 0, DEBUG_SIZE);
+
+
+       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
new file mode 100644 (file)
index 0000000..432ee0d
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * oic_wifiLib.cpp
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+// proximity code e
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#else
+// Arduino Ethernet Shield
+#include <EthernetServer.h>
+#include <Ethernet.h>
+#include <Dns.h>
+#include <EthernetClient.h>
+#include <util.h>
+#include <EthernetUdp.h>
+#include <Dhcp.h>
+#endif
+
+
+PROGMEM const char TAG[] = "TrackeeSensor";
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
+// this server will NOT be listening on 224.0.1.187 multicast address.
+
+/// WiFi Shield firmware with Intel patches
+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";
+
+int ConnectToNetwork()
+{
+    char *fwVersion;
+    int status = WL_IDLE_STATUS;
+    // check for the presence of the shield:
+    if (WiFi.status() == WL_NO_SHIELD)
+    {
+        OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
+        return -1;
+    }
+
+    // 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 )
+    {
+        OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
+        return -1;
+    }
+
+    // attempt to connect to Wifi network:
+    while (status != WL_CONNECTED)
+    {
+        OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
+        status = WiFi.begin(ssid,pass);
+
+        // wait 10 seconds for connection:
+        delay(10000);
+    }
+    OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
+
+    IPAddress ip = WiFi.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#else
+// Arduino Ethernet Shield
+int ConnectToNetwork()
+{
+    // Note: ****Update the MAC address here with your shield's MAC address****
+    uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xB8, 0xAC};
+
+    uint8_t error = Ethernet.begin(ETHERNET_MAC);
+    if (error  == 0)
+    {
+        OC_LOG_V(ERROR, TAG, "error is: %d", error);
+        return -1;
+    }
+    IPAddress ip = Ethernet.localIP();
+    OC_LOG_V(INFO, TAG, "IP Address:  %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
+    return 0;
+}
+#endif //ARDUINOWIFI
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
new file mode 100644 (file)
index 0000000..351f930
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * proximity.cpp
+ *
+ *  Created on: 2014. 11. 13.
+ *      Author: eunseok
+ */
+
+#include "Arduino.h"
+#include "proximity.h"
+#include <math.h>
+
+// 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;
+               }
+
+               Serial.print("average1 : ");
+               Serial.println(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);
+
+               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;
+}
+
+
+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/SampleApp/arduino/Trackee_Thing/src/readme.txt b/service/soft-sensor-manager/SampleApp/arduino/Trackee_Thing/src/readme.txt
new file mode 100644 (file)
index 0000000..7c041e1
--- /dev/null
@@ -0,0 +1,19 @@
+
+Followings should be done befor building Arudno applications 
+
+1. Applications on arduino conform  the Iotivity Base released on 22-Aug-2014.
+   (Ver. 22th Aug(oic-resource: commit: cdeeed62bd9b11beb2cdd340168e766088c18dac [cdeeed6]))
+
+   For successful execution, you have to copy the file, local.properties, into the following pathes:
+    - oic-resource/csdk/
+    - oic-resource/csdk/libcoap-4.1.1
+
+
+2. Time.c, Time.h should be copied in your machine and they should be refered in the Makefile as followings
+
+   Makefile path:  / oic-resource / csdk / libcoap-4.1.1 / makefile
+
+   path to be modified: 
+  
+     - INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time ---> for Time.h
+     - SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time ---> for Time.c
\ No newline at end of file
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
new file mode 100644 (file)
index 0000000..8d78c5b
--- /dev/null
@@ -0,0 +1,443 @@
+//******************************************************************
+//
+// 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 <stdio.h>
+
+#include "logger.h"
+#include "ocstack.h"
+#include <string.h>
+
+#include "oic_lanLib.h"
+#include "trackee.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;             // OIC base를 handling하기위해서 필요한 handler.
+
+#if (ARDUINO == 0)
+#include "proximity.h"
+
+#define JSON_BASE "{\"href\":\"\",\"rep\":{"
+#define JSON_BASE00 "\"0\":\"trackeeID\",\"1\":\"string\",\"2\":\""
+#define JSON_BASE01 "\",\"3\":\"things\",\"4\":\"int\",\"5\":\""
+#define JSON_BASE02 "\",\"6\":\"ID\",\"7\":\"string\",\"8\":\""
+#define JSON_BASE03 "\",\"9\":\"distance\",\"10\":\"float\",\"11\":\""
+#define JSON_BASE04 "\",\"12\":\"proximity\",\"13\":\"int\",\"14\":\""
+#define JSON_BASE05 "\",\"15\":\"SD\",\"16\":\"float\",\"17\":\""
+#define JSON_BASE06 "\",\"18\":\"ID\",\"19\":\"string\",\"20\":\""
+#define JSON_BASE07 "\",\"21\":\"distance\",\"22\":\"float\",\"23\":\""
+#define JSON_BASE08 "\",\"24\":\"proximity\",\"25\":\"int\",\"26\":\""
+#define JSON_BASE09 "\",\"27\":\"SD\",\"28\":\"float\",\"29\":\""
+#define JSON_BASE10 "\"}}"
+
+typedef struct PROXIRESOURCE {
+    float m_distance[SLAVER_EA];
+    float m_proximity[SLAVER_EA];
+} PROXIResource;
+
+PROXIResource PROXI;
+
+int rssi[SLAVER_EA][arraysize];
+int rssicnt[SLAVER_EA] = {0,};
+int startindex[SLAVER_EA] = {0,};
+int flag[SLAVER_EA] = {0,};
+//#else
+//bool bleWrite = true;
+#endif
+
+Cble ble;
+
+char trackeeID[13] = "9059AF16FEF7";
+int slaver_num = 0;
+
+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 )
+{
+       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);
+
+               OC_LOG_V(INFO, TAG, "base length = %d, buf_length=%d", base_length, buf_length );
+
+               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) );
+
+               return true;
+
+#else          // Slave Json Code.
+
+               return true;
+#endif
+       }
+
+       OC_LOG_V(INFO, TAG, "Not Support Observer unfounded mode." );
+       return false;
+}
+
+
+// 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;
+    OCEntityHandlerResponse response = {0};
+    char payload[MAX_RESPONSE_LENGTH] = {0};
+
+    if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+    {
+        OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
+        if(OC_REST_GET == entityHandlerRequest->method)
+        {
+                if(JsonGenerator(payload, MAX_RESPONSE_LENGTH))
+                {
+                }
+           else
+            {
+                ehRet = OC_EH_ERROR;
+            }
+        }
+        if(OC_REST_PUT == entityHandlerRequest->method)
+        {
+            //Do something with the 'put' payload
+            if (JsonGenerator(payload, MAX_RESPONSE_LENGTH))
+            {
+            }
+            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)
+        {
+            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"));
+        }
+    }
+    return ehRet;
+}
+
+
+#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;
+       }
+
+}
+#endif
+
+
+
+
+//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;
+       }
+
+    OCStartPresence(60);
+       // Declare and create the example resource
+       createResource();
+
+       // This call displays the amount of free SRAM available on Arduino
+       PrintArduinoMemoryStats();
+#if (ARDUINO == 0)
+       ble.init( (long)115200, BLE_MASTER, trackeeID);
+#elif (ARDUINO == 1)
+       ble.init( (long)115200, BLE_SLAVER, slaveList[0]);
+#elif (ARDUINO == 2)
+       ble.init( (long)115200, BLE_SLAVER, slaveList[1]);
+#endif
+
+//     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;
+       }
+#if (ARDUINO == 0)
+       ChangePROXIRepresentation(NULL);
+#else
+       char* user_cmd = NULL;
+
+//     ble.pollingDisconnect();
+
+       user_cmd = ble.Debug2BLE(true);
+       ble.BLE2Debug( true );
+
+       if( user_cmd )
+       {
+               free( user_cmd );
+               user_cmd = NULL;
+       }
+
+#endif
+}
+
+
+
+
+
+
+
+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";
+    }
+}
+
index e0b44b8..e318153 100644 (file)
@@ -1,6 +1,2 @@
 ARDUINO_DIR = /usr/share/arduino
-#ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
-CC=avr-g++
-CCPLUS=avr-g++
-AR=avr-ar
-RANLIB=avr-ranlib
+ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin