From bdf17b26933c78688e2d064c2bfae66eb9d75d9e Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Tue, 11 Apr 2017 14:03:10 +0900 Subject: [PATCH 01/16] Reorganize the header directory to distinguish the private headers Change-Id: I171257c61fdf452eb93921a8343f2b4583da7b31 Signed-off-by: Mu-Woong Lee --- CMakeLists.txt | 8 -------- include/{ => private}/SensorRecorderService.h | 0 src/client-dummy/CMakeLists.txt | 4 ++++ src/client/CMakeLists.txt | 4 ++++ src/server-dummy/CMakeLists.txt | 4 ++++ src/server/CMakeLists.txt | 4 ++++ 6 files changed, 16 insertions(+), 8 deletions(-) rename include/{ => private}/SensorRecorderService.h (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 946d2c7..b735be0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,7 +7,6 @@ SET(INCDIR "${CMAKE_INSTALL_INCLUDEDIR}/context-service") INCLUDE_DIRECTORIES( ${CMAKE_INSTALL_PREFIX}/${INCDIR}/private - ${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/src/shared ) @@ -21,15 +20,8 @@ SET(PC_INCLUDE "${CMAKE_INSTALL_PREFIX}/${INCDIR}") SET(PC_LIBDIR "${CMAKE_INSTALL_LIBDIR}") INSTALL( - FILES ${CMAKE_SOURCE_DIR}/include/SensorRecorderService.h - DESTINATION ${INCDIR}/private -) -INSTALL( DIRECTORY ${CMAKE_SOURCE_DIR}/include/ DESTINATION ${INCDIR} - FILES_MATCHING - PATTERN "*.h" - PATTERN "SensorRecorderService.h" EXCLUDE ) ADD_SUBDIRECTORY(src/client-dummy) diff --git a/include/SensorRecorderService.h b/include/private/SensorRecorderService.h similarity index 100% rename from include/SensorRecorderService.h rename to include/private/SensorRecorderService.h diff --git a/src/client-dummy/CMakeLists.txt b/src/client-dummy/CMakeLists.txt index 536f8a1..e768488 100644 --- a/src/client-dummy/CMakeLists.txt +++ b/src/client-dummy/CMakeLists.txt @@ -2,6 +2,10 @@ SET(target "${PROJECT_NAME}-client") SET(DEPS "${DEPS} context-common-client") +INCLUDE_DIRECTORIES( + ${CMAKE_SOURCE_DIR}/include +) + FILE(GLOB_RECURSE SRCS *.cpp) MESSAGE("Sources: ${SRCS}") diff --git a/src/client/CMakeLists.txt b/src/client/CMakeLists.txt index 8f551d7..2e6ef32 100644 --- a/src/client/CMakeLists.txt +++ b/src/client/CMakeLists.txt @@ -2,6 +2,10 @@ SET(target "${PROJECT_NAME}-client-genuine") SET(DEPS "${DEPS} context-common-client") +INCLUDE_DIRECTORIES( + ${CMAKE_SOURCE_DIR}/include +) + FILE(GLOB_RECURSE SRCS *.cpp ../shared/*.cpp) MESSAGE("Sources: ${SRCS}") diff --git a/src/server-dummy/CMakeLists.txt b/src/server-dummy/CMakeLists.txt index e0dcdd5..62ba1e9 100644 --- a/src/server-dummy/CMakeLists.txt +++ b/src/server-dummy/CMakeLists.txt @@ -2,6 +2,10 @@ SET(target "${PROJECT_NAME}-server") SET(DEPS "${DEPS} context-common-server") +INCLUDE_DIRECTORIES( + ${CMAKE_SOURCE_DIR}/include/private +) + FILE(GLOB_RECURSE SRCS *.cpp) MESSAGE("Sources: ${SRCS}") diff --git a/src/server/CMakeLists.txt b/src/server/CMakeLists.txt index 64a741f..839d274 100644 --- a/src/server/CMakeLists.txt +++ b/src/server/CMakeLists.txt @@ -2,6 +2,10 @@ SET(target "${PROJECT_NAME}-server-genuine") SET(DEPS "${DEPS} context-common-server") +INCLUDE_DIRECTORIES( + ${CMAKE_SOURCE_DIR}/include/private +) + FILE(GLOB_RECURSE SRCS *.cpp ../shared/*.cpp) MESSAGE("Sources: ${SRCS}") -- 2.7.4 From 1bcb11e8a6154fbfeab15e6376e2dd13bff58f9b Mon Sep 17 00:00:00 2001 From: "kibak.yoon" Date: Wed, 12 Apr 2017 13:56:26 +0900 Subject: [PATCH 02/16] sensor-rec: Fix TCT fails - add defence code for invalid parameter - create/destroy query handle Change-Id: I48c382c07dd3d3bb9fae3deaced20ead50752530 Signed-off-by: kibak.yoon --- src/client/sensor_recorder.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/client/sensor_recorder.cpp b/src/client/sensor_recorder.cpp index 51edc50..96edc11 100644 --- a/src/client/sensor_recorder.cpp +++ b/src/client/sensor_recorder.cpp @@ -68,6 +68,9 @@ EXPORT_API int ctx_sensor_rec_create_query(ctx_sensor_rec_query_h *query) { IF_FAIL_RETURN(query, E_PARAM); + *query = new(std::nothrow) ctx_sensor_rec_query_t(); + IF_FAIL_RETURN(query, E_NO_MEM); + return E_NONE; } @@ -75,6 +78,8 @@ EXPORT_API int ctx_sensor_rec_destroy_query(ctx_sensor_rec_query_h query) { IF_FAIL_RETURN(query, E_PARAM); + delete query; + return E_NONE; } @@ -82,7 +87,9 @@ EXPORT_API int ctx_sensor_rec_query_set_int(ctx_sensor_rec_query_h query, const { IF_FAIL_RETURN(query, E_PARAM); IF_FAIL_RETURN(STR_EQ(param, CTX_SENSOR_RECORDER_KEY_ANCHOR) || - STR_EQ(param, CTX_SENSOR_RECORDER_KEY_INTERVAL), E_PARAM); + STR_EQ(param, CTX_SENSOR_RECORDER_KEY_INTERVAL) || + STR_EQ(param, CTX_SENSOR_RECORDER_KEY_START_TIME) || + STR_EQ(param, CTX_SENSOR_RECORDER_KEY_END_TIME), E_PARAM); return E_NONE; } @@ -90,7 +97,8 @@ EXPORT_API int ctx_sensor_rec_query_set_int(ctx_sensor_rec_query_h query, const EXPORT_API int ctx_sensor_rec_query_set_time(ctx_sensor_rec_query_h query, const char* param, time_t t) { IF_FAIL_RETURN(query, E_PARAM); - IF_FAIL_RETURN(STR_EQ(param, CTX_SENSOR_RECORDER_KEY_START_TIME) || + IF_FAIL_RETURN(STR_EQ(param, CTX_SENSOR_RECORDER_KEY_ANCHOR) || + STR_EQ(param, CTX_SENSOR_RECORDER_KEY_START_TIME) || STR_EQ(param, CTX_SENSOR_RECORDER_KEY_END_TIME), E_PARAM); return E_NONE; -- 2.7.4 From df6c948c2efe45c0d9e2c122bd86dd4f7892ecff Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Wed, 12 Apr 2017 16:40:18 +0900 Subject: [PATCH 03/16] Fix compile warnings - unused function: __getQuery() - delete void pointer Change-Id: I157f9112e646b4da40114bab1a31f901b612ba18 Signed-off-by: Mu-Woong Lee --- src/client-dummy/sensor_recorder.cpp | 5 ----- src/client/sensor_recorder.cpp | 9 ++------- 2 files changed, 2 insertions(+), 12 deletions(-) diff --git a/src/client-dummy/sensor_recorder.cpp b/src/client-dummy/sensor_recorder.cpp index 413ee26..5ae08ec 100644 --- a/src/client-dummy/sensor_recorder.cpp +++ b/src/client-dummy/sensor_recorder.cpp @@ -67,11 +67,6 @@ EXPORT_API int ctx_sensor_rec_query_set_time(ctx_sensor_rec_query_h query, const return E_SUPPORT; } -static int __getQuery(ctx_sensor_rec_query_h query, int& startTime, int& endTime, int& anchor, int& interval) -{ - return E_SUPPORT; -} - EXPORT_API int ctx_sensor_rec_read(const char* subject, ctx_sensor_rec_query_h query, ctx_sensor_rec_data_cb cb, void *user_data) { return E_SUPPORT; diff --git a/src/client/sensor_recorder.cpp b/src/client/sensor_recorder.cpp index 96edc11..12c2322 100644 --- a/src/client/sensor_recorder.cpp +++ b/src/client/sensor_recorder.cpp @@ -68,7 +68,7 @@ EXPORT_API int ctx_sensor_rec_create_query(ctx_sensor_rec_query_h *query) { IF_FAIL_RETURN(query, E_PARAM); - *query = new(std::nothrow) ctx_sensor_rec_query_t(); + *query = new(std::nothrow) ctx_sensor_rec_query_t; IF_FAIL_RETURN(query, E_NO_MEM); return E_NONE; @@ -78,7 +78,7 @@ EXPORT_API int ctx_sensor_rec_destroy_query(ctx_sensor_rec_query_h query) { IF_FAIL_RETURN(query, E_PARAM); - delete query; + delete static_cast(query); return E_NONE; } @@ -104,11 +104,6 @@ EXPORT_API int ctx_sensor_rec_query_set_time(ctx_sensor_rec_query_h query, const return E_NONE; } -static int __getQuery(ctx_sensor_rec_query_h query, int& startTime, int& endTime, int& anchor, int& interval) -{ - return E_SUPPORT; -} - EXPORT_API int ctx_sensor_rec_read(const char* subject, ctx_sensor_rec_query_h query, ctx_sensor_rec_data_cb cb, void *user_data) { IF_FAIL_RETURN(query, E_PARAM); -- 2.7.4 From ec2ff7fde02250692f1c1b8c79ce3a81d01ba688 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Wed, 12 Apr 2017 20:40:32 +0900 Subject: [PATCH 04/16] Simplify include directory setting Change-Id: Iaf208bbe043c327ce10fcdf9c45b1fa042bd28fd Signed-off-by: Mu-Woong Lee --- CMakeLists.txt | 2 ++ src/client-dummy/CMakeLists.txt | 4 ---- src/client/CMakeLists.txt | 4 ---- src/server-dummy/CMakeLists.txt | 4 ---- src/server/CMakeLists.txt | 4 ---- 5 files changed, 2 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b735be0..94cb00a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,6 +8,8 @@ SET(INCDIR "${CMAKE_INSTALL_INCLUDEDIR}/context-service") INCLUDE_DIRECTORIES( ${CMAKE_INSTALL_PREFIX}/${INCDIR}/private ${CMAKE_SOURCE_DIR}/src/shared + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include/private ) ADD_DEFINITIONS(-O2 -Wall -fPIC -fdata-sections -ffunction-sections -fvisibility=hidden) diff --git a/src/client-dummy/CMakeLists.txt b/src/client-dummy/CMakeLists.txt index e768488..536f8a1 100644 --- a/src/client-dummy/CMakeLists.txt +++ b/src/client-dummy/CMakeLists.txt @@ -2,10 +2,6 @@ SET(target "${PROJECT_NAME}-client") SET(DEPS "${DEPS} context-common-client") -INCLUDE_DIRECTORIES( - ${CMAKE_SOURCE_DIR}/include -) - FILE(GLOB_RECURSE SRCS *.cpp) MESSAGE("Sources: ${SRCS}") diff --git a/src/client/CMakeLists.txt b/src/client/CMakeLists.txt index 2e6ef32..8f551d7 100644 --- a/src/client/CMakeLists.txt +++ b/src/client/CMakeLists.txt @@ -2,10 +2,6 @@ SET(target "${PROJECT_NAME}-client-genuine") SET(DEPS "${DEPS} context-common-client") -INCLUDE_DIRECTORIES( - ${CMAKE_SOURCE_DIR}/include -) - FILE(GLOB_RECURSE SRCS *.cpp ../shared/*.cpp) MESSAGE("Sources: ${SRCS}") diff --git a/src/server-dummy/CMakeLists.txt b/src/server-dummy/CMakeLists.txt index 62ba1e9..e0dcdd5 100644 --- a/src/server-dummy/CMakeLists.txt +++ b/src/server-dummy/CMakeLists.txt @@ -2,10 +2,6 @@ SET(target "${PROJECT_NAME}-server") SET(DEPS "${DEPS} context-common-server") -INCLUDE_DIRECTORIES( - ${CMAKE_SOURCE_DIR}/include/private -) - FILE(GLOB_RECURSE SRCS *.cpp) MESSAGE("Sources: ${SRCS}") diff --git a/src/server/CMakeLists.txt b/src/server/CMakeLists.txt index 839d274..64a741f 100644 --- a/src/server/CMakeLists.txt +++ b/src/server/CMakeLists.txt @@ -2,10 +2,6 @@ SET(target "${PROJECT_NAME}-server-genuine") SET(DEPS "${DEPS} context-common-server") -INCLUDE_DIRECTORIES( - ${CMAKE_SOURCE_DIR}/include/private -) - FILE(GLOB_RECURSE SRCS *.cpp ../shared/*.cpp) MESSAGE("Sources: ${SRCS}") -- 2.7.4 From f4ecb4aa70e8369206a8b3a74f97bcfd65efe2df Mon Sep 17 00:00:00 2001 From: "kibak.yoon" Date: Fri, 14 Apr 2017 18:05:13 +0900 Subject: [PATCH 05/16] Add compile options to suppress verbose messages and enable colored diagnostics Change-Id: Iec20dcd50443f7733f46c42a1eac1aac7d50432e Signed-off-by: kibak.yoon --- CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 94cb00a..745ada6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,8 +13,10 @@ INCLUDE_DIRECTORIES( ) ADD_DEFINITIONS(-O2 -Wall -fPIC -fdata-sections -ffunction-sections -fvisibility=hidden) +ADD_DEFINITIONS(-fdiagnostics-color) ADD_DEFINITIONS(-DLOG_TAG="CONTEXT-SENSOR") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fPIC -Wl,--as-needed -Wl,--gc-sections -Wl,--print-gc-sections") +SET(CMAKE_VERBOSE_MAKEFILE OFF) SET(VERSION ${FULLVER}) SET(PREFIX ${CMAKE_INSTALL_PREFIX}) -- 2.7.4 From d50f51e099b0b54492b4e4b55c789e0064b01b9e Mon Sep 17 00:00:00 2001 From: "kibak.yoon" Date: Thu, 27 Apr 2017 21:36:09 +0900 Subject: [PATCH 06/16] sensor-rec: allocate/deallocate memory of sensor option handle Change-Id: I207522adfdb63d401e4ee360f14ab69a73142865 Signed-off-by: kibak.yoon --- src/client/sensor_recorder.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/client/sensor_recorder.cpp b/src/client/sensor_recorder.cpp index 12c2322..8b46ad5 100644 --- a/src/client/sensor_recorder.cpp +++ b/src/client/sensor_recorder.cpp @@ -45,6 +45,9 @@ EXPORT_API int ctx_sensor_rec_create_option(ctx_sensor_rec_option_h *option) { IF_FAIL_RETURN(option, E_PARAM); + *option = new(std::nothrow) ctx_sensor_rec_option_t; + IF_FAIL_RETURN(*option, E_NO_MEM); + return E_NONE; } @@ -52,6 +55,8 @@ EXPORT_API int ctx_sensor_rec_destroy_option(ctx_sensor_rec_option_h option) { IF_FAIL_RETURN(option, E_PARAM); + delete static_cast(option); + return E_NONE; } @@ -69,7 +74,7 @@ EXPORT_API int ctx_sensor_rec_create_query(ctx_sensor_rec_query_h *query) IF_FAIL_RETURN(query, E_PARAM); *query = new(std::nothrow) ctx_sensor_rec_query_t; - IF_FAIL_RETURN(query, E_NO_MEM); + IF_FAIL_RETURN(*query, E_NO_MEM); return E_NONE; } -- 2.7.4 From e1c30af5bc4eb599c155fb7a441f08fcc36a76d1 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 19 May 2017 11:16:56 +0900 Subject: [PATCH 07/16] Import the legacy sensor-recorder implementation from context-provider Change-Id: I626238fc6def0458cab6192ebb7fd40c32549c52 Signed-off-by: Mu-Woong Lee --- src/server/CMakeLists.txt | 2 +- src/server/legacy/ClientInfo.cpp | 203 +++++++++++++++++++++++ src/server/legacy/ClientInfo.h | 51 ++++++ src/server/legacy/CreateProvider.cpp | 34 ++++ src/server/legacy/Querier.cpp | 85 ++++++++++ src/server/legacy/Querier.h | 49 ++++++ src/server/legacy/SensorLogger.cpp | 60 +++++++ src/server/legacy/SensorLogger.h | 44 +++++ src/server/legacy/SensorProvider.cpp | 187 +++++++++++++++++++++ src/server/legacy/SensorProvider.h | 56 +++++++ src/server/legacy/SensorProxy.cpp | 124 ++++++++++++++ src/server/legacy/SensorProxy.h | 59 +++++++ src/server/legacy/TimeUtil.cpp | 74 +++++++++ src/server/legacy/TimeUtil.h | 36 ++++ src/server/legacy/TypesInternal.h | 46 +++++ src/server/legacy/UninstallMonitor.cpp | 49 ++++++ src/server/legacy/UninstallMonitor.h | 38 +++++ src/server/legacy/heartrate/HeartRate.cpp | 70 ++++++++ src/server/legacy/heartrate/HeartRate.h | 38 +++++ src/server/legacy/heartrate/HeartRateLogger.cpp | 156 +++++++++++++++++ src/server/legacy/heartrate/HeartRateLogger.h | 52 ++++++ src/server/legacy/heartrate/HeartRateQuerier.cpp | 55 ++++++ src/server/legacy/heartrate/HeartRateQuerier.h | 34 ++++ src/server/legacy/pedometer/Pedometer.cpp | 54 ++++++ src/server/legacy/pedometer/Pedometer.h | 37 +++++ src/server/legacy/pedometer/PedometerLogger.cpp | 188 +++++++++++++++++++++ src/server/legacy/pedometer/PedometerLogger.h | 56 +++++++ src/server/legacy/pedometer/PedometerQuerier.cpp | 95 +++++++++++ src/server/legacy/pedometer/PedometerQuerier.h | 35 ++++ src/server/legacy/pressure/Pressure.cpp | 49 ++++++ src/server/legacy/pressure/Pressure.h | 36 ++++ src/server/legacy/pressure/PressureLogger.cpp | 117 +++++++++++++ src/server/legacy/pressure/PressureLogger.h | 47 ++++++ src/server/legacy/pressure/PressureQuerier.cpp | 92 ++++++++++ src/server/legacy/pressure/PressureQuerier.h | 35 ++++ src/server/legacy/sleep/Sleep.cpp | 54 ++++++ src/server/legacy/sleep/Sleep.h | 37 +++++ src/server/legacy/sleep/SleepDetector.cpp | 58 +++++++ src/server/legacy/sleep/SleepDetector.h | 41 +++++ src/server/legacy/sleep/SleepLogger.cpp | 170 +++++++++++++++++++ src/server/legacy/sleep/SleepLogger.h | 51 ++++++ src/server/legacy/sleep/SleepMonitor.cpp | 75 +++++++++ src/server/legacy/sleep/SleepMonitor.h | 44 +++++ src/server/legacy/sleep/SleepQuerier.cpp | 55 ++++++ src/server/legacy/sleep/SleepQuerier.h | 34 ++++ 45 files changed, 3061 insertions(+), 1 deletion(-) create mode 100644 src/server/legacy/ClientInfo.cpp create mode 100644 src/server/legacy/ClientInfo.h create mode 100644 src/server/legacy/CreateProvider.cpp create mode 100644 src/server/legacy/Querier.cpp create mode 100644 src/server/legacy/Querier.h create mode 100644 src/server/legacy/SensorLogger.cpp create mode 100644 src/server/legacy/SensorLogger.h create mode 100644 src/server/legacy/SensorProvider.cpp create mode 100644 src/server/legacy/SensorProvider.h create mode 100644 src/server/legacy/SensorProxy.cpp create mode 100644 src/server/legacy/SensorProxy.h create mode 100644 src/server/legacy/TimeUtil.cpp create mode 100644 src/server/legacy/TimeUtil.h create mode 100644 src/server/legacy/TypesInternal.h create mode 100644 src/server/legacy/UninstallMonitor.cpp create mode 100644 src/server/legacy/UninstallMonitor.h create mode 100644 src/server/legacy/heartrate/HeartRate.cpp create mode 100644 src/server/legacy/heartrate/HeartRate.h create mode 100644 src/server/legacy/heartrate/HeartRateLogger.cpp create mode 100644 src/server/legacy/heartrate/HeartRateLogger.h create mode 100644 src/server/legacy/heartrate/HeartRateQuerier.cpp create mode 100644 src/server/legacy/heartrate/HeartRateQuerier.h create mode 100644 src/server/legacy/pedometer/Pedometer.cpp create mode 100644 src/server/legacy/pedometer/Pedometer.h create mode 100644 src/server/legacy/pedometer/PedometerLogger.cpp create mode 100644 src/server/legacy/pedometer/PedometerLogger.h create mode 100644 src/server/legacy/pedometer/PedometerQuerier.cpp create mode 100644 src/server/legacy/pedometer/PedometerQuerier.h create mode 100644 src/server/legacy/pressure/Pressure.cpp create mode 100644 src/server/legacy/pressure/Pressure.h create mode 100644 src/server/legacy/pressure/PressureLogger.cpp create mode 100644 src/server/legacy/pressure/PressureLogger.h create mode 100644 src/server/legacy/pressure/PressureQuerier.cpp create mode 100644 src/server/legacy/pressure/PressureQuerier.h create mode 100644 src/server/legacy/sleep/Sleep.cpp create mode 100644 src/server/legacy/sleep/Sleep.h create mode 100644 src/server/legacy/sleep/SleepDetector.cpp create mode 100644 src/server/legacy/sleep/SleepDetector.h create mode 100644 src/server/legacy/sleep/SleepLogger.cpp create mode 100644 src/server/legacy/sleep/SleepLogger.h create mode 100644 src/server/legacy/sleep/SleepMonitor.cpp create mode 100644 src/server/legacy/sleep/SleepMonitor.h create mode 100644 src/server/legacy/sleep/SleepQuerier.cpp create mode 100644 src/server/legacy/sleep/SleepQuerier.h diff --git a/src/server/CMakeLists.txt b/src/server/CMakeLists.txt index 64a741f..df2de9c 100644 --- a/src/server/CMakeLists.txt +++ b/src/server/CMakeLists.txt @@ -2,7 +2,7 @@ SET(target "${PROJECT_NAME}-server-genuine") SET(DEPS "${DEPS} context-common-server") -FILE(GLOB_RECURSE SRCS *.cpp ../shared/*.cpp) +FILE(GLOB SRCS *.cpp ../shared/*.cpp) MESSAGE("Sources: ${SRCS}") INCLUDE(FindPkgConfig) diff --git a/src/server/legacy/ClientInfo.cpp b/src/server/legacy/ClientInfo.cpp new file mode 100644 index 0000000..6c5955d --- /dev/null +++ b/src/server/legacy/ClientInfo.cpp @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "TypesInternal.h" +#include "SensorProvider.h" +#include "ClientInfo.h" + +using namespace ctx; + +unsigned int ClientInfo::__refCnt = 0; +DatabaseManager *ClientInfo::__dbMgr = NULL; +UninstallMonitor *ClientInfo::__uninstallMonitor = NULL; + +ClientInfo::ClientInfo() +{ + if (++__refCnt != 1) + return; + + __uninstallMonitor = new(std::nothrow) UninstallMonitor(); + IF_FAIL_VOID_TAG(__uninstallMonitor, _E, "Memory allocation failed"); + + __dbMgr = new(std::nothrow) DatabaseManager(); + IF_FAIL_VOID_TAG(__dbMgr, _E, "Memory allocation failed"); + + bool ret = __dbMgr->executeSync( + "CREATE TABLE IF NOT EXISTS " CLIENT_INFO " (" \ + KEY_SUBJECT " TEXT NOT NULL," \ + KEY_PKG_ID " TEXT NOT NULL," \ + KEY_OPTION " TEXT NOT NULL," \ + KEY_RETENTION " INTEGER NOT NULL," \ + "PRIMARY KEY (" KEY_SUBJECT "," KEY_PKG_ID ")" \ + ")", NULL); + + IF_FAIL_VOID_TAG(ret, _E, "Table creation failed"); +} + +ClientInfo::~ClientInfo() +{ + if (--__refCnt != 0) + return; + + delete __dbMgr; + __dbMgr = NULL; + + delete __uninstallMonitor; + __uninstallMonitor = NULL; +} + +int ClientInfo::get(std::string subject, std::string pkgId, Json& option) +{ + IF_FAIL_RETURN_TAG(__dbMgr, ERR_OPERATION_FAILED, _W, "DB not initialized"); + + bool ret; + std::string optStr; + std::vector records; + char *query = sqlite3_mprintf( + "SELECT " KEY_OPTION " FROM " CLIENT_INFO " WHERE " \ + KEY_SUBJECT "='%q' AND " KEY_PKG_ID "='%q'", + subject.c_str(), pkgId.c_str()); + + ret = __dbMgr->executeSync(query, &records); + sqlite3_free(query); + + IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); + IF_FAIL_RETURN(!records.empty(), ERR_NO_DATA); + IF_FAIL_RETURN(records[0].get(NULL, KEY_OPTION, &optStr), ERR_OPERATION_FAILED); + + option = optStr; + + return ERR_NONE; +} + +int ClientInfo::get(std::string subject, std::vector& options) +{ + IF_FAIL_RETURN_TAG(__dbMgr, ERR_OPERATION_FAILED, _W, "DB not initialized"); + + bool ret; + std::string optStr; + std::vector records; + char *query = sqlite3_mprintf( + "SELECT " KEY_OPTION " FROM " CLIENT_INFO " WHERE " \ + KEY_SUBJECT "='%q'", + subject.c_str()); + + ret = __dbMgr->executeSync(query, &records); + sqlite3_free(query); + + IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); + IF_FAIL_RETURN(!records.empty(), ERR_NO_DATA); + + for (Json& jObj : records) { + if (!jObj.get(NULL, KEY_OPTION, &optStr)) + continue; + options.push_back(Json(optStr)); + } + + return ERR_NONE; +} + +bool ClientInfo::exist(std::string subject) +{ + IF_FAIL_RETURN_TAG(__dbMgr, ERR_OPERATION_FAILED, _W, "DB not initialized"); + + bool ret; + std::vector records; + char *query = sqlite3_mprintf( + "SELECT " KEY_PKG_ID " FROM " CLIENT_INFO " WHERE " \ + KEY_SUBJECT "='%q' LIMIT 1", + subject.c_str()); + + ret = __dbMgr->executeSync(query, &records); + sqlite3_free(query); + + IF_FAIL_RETURN(ret, false); + IF_FAIL_RETURN(!records.empty(), false); + + return true; +} + +bool ClientInfo::set(std::string subject, std::string pkgId, Json option, int retentionPeriod) +{ + IF_FAIL_RETURN_TAG(__dbMgr, false, _W, "DB not initialized"); + + bool ret; + char *query = sqlite3_mprintf( + "INSERT INTO " CLIENT_INFO " VALUES ('%q', '%q', '%q', %d)", + subject.c_str(), pkgId.c_str(), option.str().c_str(), retentionPeriod); + + ret = __dbMgr->executeSync(query, NULL); + sqlite3_free(query); + + return ret; +} + +bool ClientInfo::remove(std::string subject, std::string pkgId) +{ + IF_FAIL_RETURN_TAG(__dbMgr, false, _W, "DB not initialized"); + + bool ret; + char *query = sqlite3_mprintf( + "DELETE FROM " CLIENT_INFO " WHERE " \ + KEY_SUBJECT "='%q' AND " KEY_PKG_ID "='%q'", + subject.c_str(), pkgId.c_str()); + + ret = __dbMgr->executeSync(query, NULL); + sqlite3_free(query); + + return ret; +} + +void ClientInfo::getParam(std::vector &options, const char *key, float *min, float *max) +{ + double val; + + for (Json& opt : options) { + if (!opt.get(NULL, key, &val)) + continue; + if (min) + *min = MIN(*min, static_cast(val)); + if (max) + *max = MAX(*max, static_cast(val)); + } +} + +void ClientInfo::purgeClient(std::string pkgId) +{ + IF_FAIL_VOID_TAG(__dbMgr, _W, "DB not initialized"); + + bool ret; + std::string subject; + std::vector records; + + char *query = sqlite3_mprintf( + "SELECT " KEY_SUBJECT " FROM " CLIENT_INFO " WHERE " KEY_PKG_ID "='%q'", + pkgId.c_str()); + + ret = __dbMgr->executeSync(query, &records); + sqlite3_free(query); + IF_FAIL_VOID(ret); + + for (Json& jObj : records) { + if (!jObj.get(NULL, KEY_SUBJECT, &subject)) + continue; + _I("Stop recording '%s' for '%s'", subject.c_str(), pkgId.c_str()); + SensorProvider::removeClient(subject, pkgId); + } +} diff --git a/src/server/legacy/ClientInfo.h b/src/server/legacy/ClientInfo.h new file mode 100644 index 0000000..e3ee643 --- /dev/null +++ b/src/server/legacy/ClientInfo.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_CLIENT_INFO_H__ +#define __CONTEXT_CLIENT_INFO_H__ + +#include +#include +#include +#include +#include "UninstallMonitor.h" + +namespace ctx { + + class ClientInfo { + public: + ClientInfo(); + ~ClientInfo(); + + int get(std::string subject, std::string pkgId, Json& option); + int get(std::string subject, std::vector& options); + bool exist(std::string subject); + + bool set(std::string subject, std::string pkgId, Json option, int retentionPeriod); + bool remove(std::string subject, std::string pkgId); + + void getParam(std::vector& options, const char *key, float *min, float *max); + + static void purgeClient(std::string pkgId); + + private: + static unsigned int __refCnt; + static DatabaseManager *__dbMgr; + static UninstallMonitor *__uninstallMonitor; + }; +} + +#endif /* _CONTEXT_CLIENT_INFO_H_ */ diff --git a/src/server/legacy/CreateProvider.cpp b/src/server/legacy/CreateProvider.cpp new file mode 100644 index 0000000..73e9f19 --- /dev/null +++ b/src/server/legacy/CreateProvider.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "pedometer/Pedometer.h" +#include "pressure/Pressure.h" +#include "sleep/Sleep.h" +#include "heartrate/HeartRate.h" + +using namespace ctx; + +extern "C" SO_EXPORT ContextProvider* CreateProvider(const char *subject) +{ + ADD_PROVIDER(SUBJ_SENSOR_PEDOMETER, PedometerProvider); + ADD_PROVIDER(SUBJ_SENSOR_PRESSURE, PressureProvider); + ADD_PROVIDER(SUBJ_SENSOR_SLEEP_MONITOR, SleepProvider); + ADD_PROVIDER(SUBJ_SENSOR_HEART_RATE, HeartRateProvider); + + return NULL; +} diff --git a/src/server/legacy/Querier.cpp b/src/server/legacy/Querier.cpp new file mode 100644 index 0000000..feec0b3 --- /dev/null +++ b/src/server/legacy/Querier.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "Querier.h" + +using namespace ctx; + +Querier::Querier(ContextProvider *provider, Json option) : + __provider(provider), + __option(option) +{ +} + +Querier::~Querier() +{ +} + +int Querier::query(const char *sql) +{ + return __dbMgr.execute(0, sql, this) ? ERR_NONE : ERR_OPERATION_FAILED; +} + +int Querier::queryRaw(int startTime, int endTime) +{ + return ERR_INVALID_PARAMETER; +} + +int Querier::query(int startTime, int endTime) +{ + return ERR_INVALID_PARAMETER; +} + +int Querier::query(int startTime, int endTime, int anchor, int interval) +{ + _D("Ignore anchor & interval"); + return query(startTime, endTime); +} + +void Querier::onTableCreated(unsigned int queryId, int error) +{ +} + +void Querier::onInserted(unsigned int queryId, int error, int64_t rowId) +{ +} + +void Querier::onExecuted(unsigned int queryId, int error, std::vector& records) +{ + Json response; + __convertToResponse(records, response); + __provider->replyToRead(__option, error, response); + delete this; +} + +void Querier::__convertToResponse(std::vector &sqlResult, Json &response) +{ + std::list keys; + std::string val; + + response.set(NULL, KEY_RESULT_SIZE, static_cast(sqlResult.size())); + + for (Json &tuple : sqlResult) { + tuple.getKeys(&keys); + for (std::string &key : keys) { + tuple.get(NULL, key.c_str(), &val); + response.append(NULL, key.c_str(), val); + } + keys.clear(); + } +} diff --git a/src/server/legacy/Querier.h b/src/server/legacy/Querier.h new file mode 100644 index 0000000..0eed203 --- /dev/null +++ b/src/server/legacy/Querier.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_QUERIER_H__ +#define __CONTEXT_QUERIER_H__ + +#include +#include + +namespace ctx { + + class Querier : public IDatabaseListener { + public: + Querier(ContextProvider *provider, Json option); + virtual ~Querier(); + + virtual int queryRaw(int startTime, int endTime); + virtual int query(int startTime, int endTime); + virtual int query(int startTime, int endTime, int anchor, int interval); + + protected: + int query(const char *sql); + void onTableCreated(unsigned int queryId, int error); + void onInserted(unsigned int queryId, int error, int64_t rowId); + void onExecuted(unsigned int queryId, int error, std::vector& records); + + private: + void __convertToResponse(std::vector &sqlResult, Json &response); + + DatabaseManager __dbMgr; + ContextProvider *__provider; + Json __option; + }; +} + +#endif /* __CONTEXT_QUERIER_H__ */ diff --git a/src/server/legacy/SensorLogger.cpp b/src/server/legacy/SensorLogger.cpp new file mode 100644 index 0000000..6bc92ea --- /dev/null +++ b/src/server/legacy/SensorLogger.cpp @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "TypesInternal.h" +#include "TimeUtil.h" +#include "SensorLogger.h" + +using namespace ctx; + +SensorLogger::SensorLogger() : + __lastRemovalTime(0) +{ +} + +SensorLogger::~SensorLogger() +{ +} + +void SensorLogger::flushCache(bool force) +{ +} + +bool SensorLogger::executeQuery(const char *query) +{ + return __dbMgr.execute(0, query, NULL); +} + +void SensorLogger::removeExpired(const char *subject, const char *tableName, const char *timeKey) +{ + uint64_t timestamp = TimeUtil::getTime(); + + if (timestamp - __lastRemovalTime < SEC_TO_MS(SECONDS_PER_HOUR)) + return; + + char *query = sqlite3_mprintf( + "DELETE FROM %s WHERE %s < " \ + "%llu - (SELECT MAX(" KEY_RETENTION ") * 1000 FROM " CLIENT_INFO \ + " WHERE " KEY_SUBJECT "='%s')", + tableName, timeKey, timestamp, subject); + + __dbMgr.execute(0, query, NULL); + sqlite3_free(query); + + __lastRemovalTime = timestamp; +} diff --git a/src/server/legacy/SensorLogger.h b/src/server/legacy/SensorLogger.h new file mode 100644 index 0000000..76d7ec6 --- /dev/null +++ b/src/server/legacy/SensorLogger.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_SENSOR_LOGGER_H__ +#define __CONTEXT_SENSOR_LOGGER_H__ + +#include + +namespace ctx { + + class SensorLogger { + public: + SensorLogger(); + virtual ~SensorLogger(); + + virtual bool start() = 0; + virtual void stop() = 0; + virtual void flushCache(bool force = false); + + protected: + bool executeQuery(const char *query); + + virtual void removeExpired(const char *subject, const char *tableName, const char *timeKey); + + private: + uint64_t __lastRemovalTime; + DatabaseManager __dbMgr; + }; +} + +#endif /* __CONTEXT_SENSOR_LOGGER_H__ */ diff --git a/src/server/legacy/SensorProvider.cpp b/src/server/legacy/SensorProvider.cpp new file mode 100644 index 0000000..47d5269 --- /dev/null +++ b/src/server/legacy/SensorProvider.cpp @@ -0,0 +1,187 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "TypesInternal.h" +#include "SensorProvider.h" + +using namespace ctx; + +std::map SensorProvider::__providerMap; + +SensorProvider::SensorProvider(const char *subject) : + ContextProvider(subject), + sensorLogger(NULL) +{ + __providerMap[subject] = this; +} + +SensorProvider::~SensorProvider() +{ + __providerMap.erase(getSubject()); + delete sensorLogger; +} + +int SensorProvider::subscribe(Json option, Json *requestResult) +{ + return ERR_NONE; +} + +int SensorProvider::unsubscribe(Json option) +{ + return ERR_NONE; +} + +int SensorProvider::read(Json option, Json *requestResult) +{ + int endTime = static_cast(time(NULL)) + 1; + int startTime = endTime - DEFAULT_QUERY_PERIOD - 1; + int anchor = -1; + int interval = -1; + + if (option.get(NULL, KEY_START_TIME, &startTime)) + IF_FAIL_RETURN(startTime >= 0, ERR_INVALID_PARAMETER); + + if (option.get(NULL, KEY_END_TIME, &endTime)) + IF_FAIL_RETURN(endTime >= 0, ERR_INVALID_PARAMETER); + + if (option.get(NULL, KEY_ANCHOR, &anchor)) + IF_FAIL_RETURN(anchor >= 0, ERR_INVALID_PARAMETER); + + if (option.get(NULL, KEY_INTERVAL, &interval)) + IF_FAIL_RETURN(interval >= 0, ERR_INVALID_PARAMETER); + + if (endTime >= 0 && startTime >= endTime) + return ERR_INVALID_PARAMETER; + + if (interval > 0 && anchor < 0) + anchor = endTime; + + if (anchor >= 0 && interval < 0) + interval = static_cast(ceil(static_cast(endTime - startTime) / SECONDS_PER_MINUTE)); + + int ret; + Querier *querier = getQuerier(option); + IF_FAIL_RETURN(querier, ERR_OPERATION_FAILED); + + sensorLogger->flushCache(true); + + if (interval == 0) + ret = querier->queryRaw(startTime, endTime); + else if (interval > 0) + ret = querier->query(startTime, endTime, anchor, interval * SECONDS_PER_MINUTE); + else + ret = querier->query(startTime, endTime); + + if (ret != ERR_NONE) + delete querier; + + return ret; +} + +int SensorProvider::write(Json data, Json *requestResult) +{ + IF_FAIL_RETURN(sensorLogger, ERR_OPERATION_FAILED); + + std::string operation; + std::string pkgId; + Json option; + int retentionPeriod = DEFAULT_RETENTION; + + _J("Data", data); + + IF_FAIL_RETURN(data.get(NULL, KEY_OPERATION, &operation), ERR_INVALID_PARAMETER); + IF_FAIL_RETURN(data.get(NULL, KEY_CLIENT_PKG_ID, &pkgId), ERR_INVALID_PARAMETER); + + data.get(NULL, KEY_OPTION, &option); + + if (option.get(NULL, KEY_RETENTION, &retentionPeriod)) { + retentionPeriod *= SECONDS_PER_HOUR; + option.remove(NULL, KEY_RETENTION); + } + + IF_FAIL_RETURN(verifyOption(option), ERR_INVALID_PARAMETER); + + if (operation == VAL_START) + return __addClient(pkgId, retentionPeriod, option); + else if (operation == VAL_STOP) + return __removeClient(pkgId); + + return ERR_NOT_SUPPORTED; +} + +bool SensorProvider::verifyOption(Json option) +{ + std::list keys; + option.getKeys(&keys); + return keys.size() == 0; +} + +int SensorProvider::__addClient(std::string pkgId, int retentionPeriod, Json option) +{ + Json tmp; + int ret; + + /* Validate the retention period */ + IF_FAIL_RETURN(retentionPeriod > 0 && retentionPeriod <= MAX_RETENTION_PERIOD, ERR_INVALID_PARAMETER); + + /* Check if the app already started Sensor recording */ + ret = __clientInfo.get(getSubject(), pkgId, tmp); + IF_FAIL_RETURN(ret != ERR_NONE, ERR_ALREADY_STARTED); + IF_FAIL_RETURN(ret == ERR_NO_DATA, ERR_OPERATION_FAILED); + + /* Store the app's request */ + if (!__clientInfo.set(getSubject(), pkgId, option, retentionPeriod)) + return ERR_OPERATION_FAILED; + + /* If not listening the sensor yet, start */ + sensorLogger->start(); + + return ERR_NONE; +} + +int SensorProvider::__removeClient(std::string pkgId) +{ + std::vector options; + int ret; + + /* Remove the app's request first */ + IF_FAIL_RETURN(__clientInfo.remove(getSubject(), pkgId), ERR_OPERATION_FAILED); + + /* Check if there is no client anymore */ + ret = __clientInfo.get(getSubject(), options); + + if (ret == ERR_NONE) { + /* Still, one or more clients exist */ + /* If necessary, the logger restarts its logging logic with updated parameters */ + sensorLogger->start(); + return ERR_NONE; + + } else if (ret == ERR_NO_DATA) { + /* No client */ + sensorLogger->stop(); + return ERR_NONE; + } + + return ERR_OPERATION_FAILED; +} + +void SensorProvider::removeClient(std::string subject, std::string pkgId) +{ + __providerMap[subject]->__removeClient(pkgId); +} diff --git a/src/server/legacy/SensorProvider.h b/src/server/legacy/SensorProvider.h new file mode 100644 index 0000000..5b806a0 --- /dev/null +++ b/src/server/legacy/SensorProvider.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_SENSOR_PROVIDER_H__ +#define __CONTEXT_SENSOR_PROVIDER_H__ + +#include +#include +#include "ClientInfo.h" +#include "SensorLogger.h" +#include "Querier.h" + +namespace ctx { + + class SensorProvider : public ContextProvider { + public: + SensorProvider(const char *subject); + virtual ~SensorProvider(); + + virtual int subscribe(Json option, Json *requestResult); + virtual int unsubscribe(Json option); + virtual int read(Json option, Json *requestResult); + virtual int write(Json data, Json *requestResult); + + static void removeClient(std::string subject, std::string pkgId); + + protected: + virtual Querier* getQuerier(Json option) = 0; + virtual bool verifyOption(Json option); + + SensorLogger *sensorLogger; + + private: + int __addClient(std::string pkgId, int retentionPeriod, Json option); + int __removeClient(std::string pkgId); + + ClientInfo __clientInfo; + + static std::map __providerMap; + }; +} + +#endif /* _CONTEXT_SENSOR_PROVIDER_H_ */ diff --git a/src/server/legacy/SensorProxy.cpp b/src/server/legacy/SensorProxy.cpp new file mode 100644 index 0000000..98dd0a6 --- /dev/null +++ b/src/server/legacy/SensorProxy.cpp @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include "SensorProxy.h" + +#define SENSOR_EVENT(X) (((int)(X) << 16) | 0x01) + +using namespace ctx; + +SensorProxy::SensorProxy() : + sensorHandle(-1), + sensorType(UNKNOWN_SENSOR), + powerSave(true), + samplingInterval(0), + batchLatency(0), + userData(NULL) +{ +} + +SensorProxy::~SensorProxy() +{ + unlisten(); +} + +void SensorProxy::setSensor(sensor_type_t type) +{ + sensorType = type; +} + +void SensorProxy::setPowerSave(bool ps) +{ + powerSave = ps; +} + +void SensorProxy::setSamplingInterval(unsigned int interval) +{ + samplingInterval = interval; +} + +void SensorProxy::setBatchLatency(unsigned int latency) +{ + batchLatency = latency; +} + +void SensorProxy::setUserData(void *data) +{ + userData = data; +} + +bool SensorProxy::listen() +{ + _D("#Sensor = %#x", sensorType); + + sensor_t sensor = sensord_get_sensor(sensorType); + IF_FAIL_RETURN_TAG(sensor, false, _E, "Getting sensor failed"); + + sensorHandle = sensord_connect(sensor); + IF_FAIL_RETURN_TAG(sensorHandle >= 0, false, _E, "Connection failed"); + + if (!sensord_register_event(sensorHandle, SENSOR_EVENT(sensorType), samplingInterval, batchLatency, __eventCb, this)) { + _E("Event registration failed"); + sensord_disconnect(sensorHandle); + sensorHandle = -1; + return false; + } + + if (!sensord_start(sensorHandle, powerSave ? SENSOR_OPTION_DEFAULT : SENSOR_OPTION_ALWAYS_ON)) { + _E("Starting failed"); + sensord_unregister_event(sensorHandle, SENSOR_EVENT(sensorType)); + sensord_disconnect(sensorHandle); + sensorHandle = -1; + return false; + } + + return true; +} + +void SensorProxy::unlisten() +{ + IF_FAIL_VOID(sensorHandle >= 0); + + sensord_stop(sensorHandle); + sensord_unregister_event(sensorHandle, SENSOR_EVENT(sensorType)); + sensord_disconnect(sensorHandle); + sensorHandle = -1; +} + +void SensorProxy::flush() +{ + IF_FAIL_VOID(sensorHandle >= 0); + sensord_flush(sensorHandle); +} + +bool SensorProxy::isRunning() +{ + return sensorHandle >= 0; +} + +bool SensorProxy::isSupported(sensor_type_t type) +{ + sensor_t sensor = sensord_get_sensor(type); + return (sensor != NULL); +} + +void SensorProxy::__eventCb(sensor_t sensor, unsigned int eventType, sensor_data_t *eventData, void *cbData) +{ + SensorProxy *instance = static_cast(cbData); + instance->onEvent(eventData); +} diff --git a/src/server/legacy/SensorProxy.h b/src/server/legacy/SensorProxy.h new file mode 100644 index 0000000..7ae1c87 --- /dev/null +++ b/src/server/legacy/SensorProxy.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef __CONTEXT_SENSOR_PROXY_H__ +#define __CONTEXT_SENSOR_PROXY_H__ + +#include + +namespace ctx { + + class SensorProxy { + public: + SensorProxy(); + virtual ~SensorProxy(); + + void setSensor(sensor_type_t type); + void setPowerSave(bool ps); + void setSamplingInterval(unsigned int interval); + void setBatchLatency(unsigned int latency); + void setUserData(void *data); + + bool listen(); + void unlisten(); + bool isRunning(); + void flush(); + + protected: + int sensorHandle; + sensor_type_t sensorType; + bool powerSave; + unsigned int samplingInterval; + unsigned int batchLatency; + void *userData; + + static bool isSupported(sensor_type_t type); + + virtual void onEvent(sensor_data_t *eventData) = 0; + + private: + static void __eventCb(sensor_t sensor, unsigned int eventType, sensor_data_t *eventData, void *cbData); + }; + +} + +#endif /* __CONTEXT_SENSOR_PROXY_H__ */ diff --git a/src/server/legacy/TimeUtil.cpp b/src/server/legacy/TimeUtil.cpp new file mode 100644 index 0000000..2e37da6 --- /dev/null +++ b/src/server/legacy/TimeUtil.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include +#include "TypesInternal.h" +#include "TimeUtil.h" + +/* NOTE: CLOCK_BOOTTIME is defined in linux/time.h. + But if it is included, we encounters the redefinition error of timespec. */ +#define CLOCK_BOOTTIME 7 + +#define DIFF(X, Y) ((X) > (Y) ? (X) - (Y) : (Y) - (X)) +#define SEC_TO_MSEC(X) ((uint64_t)(X) * 1000ull) +#define USEC_TO_MSEC(X) ((uint64_t)(X) / 1000ull) +#define NSEC_TO_MSEC(X) ((uint64_t)(X) / 1000000ull) +#define EPSILON 3ull + +using namespace ctx; + +TimeUtil::TimeUtil() +{ +} + +uint64_t TimeUtil::getTime() +{ + struct timespec ts; + uint64_t epochInMSec; + + clock_gettime(CLOCK_REALTIME_COARSE, &ts); + epochInMSec = SEC_TO_MSEC(ts.tv_sec) + NSEC_TO_MSEC(ts.tv_nsec); + + return epochInMSec; +} + +uint64_t TimeUtil::getTime(unsigned long long sensorTimestamp) +{ + uint64_t currentEpoch = getTime(); + uint64_t sensorTimeMSec = USEC_TO_MSEC(sensorTimestamp); + + bool isEpoch = DIFF(currentEpoch, sensorTimeMSec) < SEC_TO_MSEC(SECONDS_PER_DAY); + + if (isEpoch) + return sensorTimeMSec; + + + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + + uint64_t currentMonotonic = SEC_TO_MSEC(ts.tv_sec) + NSEC_TO_MSEC(ts.tv_nsec); + bool isMonotonic = currentMonotonic + EPSILON > sensorTimeMSec; + + if (isMonotonic) + return currentEpoch - currentMonotonic + sensorTimeMSec; + + + clock_gettime(CLOCK_BOOTTIME, &ts); + uint64_t currentBootTime = SEC_TO_MSEC(ts.tv_sec) + NSEC_TO_MSEC(ts.tv_nsec); + + return currentEpoch - currentBootTime + sensorTimeMSec; +} diff --git a/src/server/legacy/TimeUtil.h b/src/server/legacy/TimeUtil.h new file mode 100644 index 0000000..bdacf06 --- /dev/null +++ b/src/server/legacy/TimeUtil.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef __CONTEXT_TIME_UTIL_H__ +#define __CONTEXT_TIME_UTIL_H__ + +#include + +namespace ctx { + + class TimeUtil { + public: + static uint64_t getTime(); + static uint64_t getTime(unsigned long long sensorTimestamp); + + private: + TimeUtil(); + }; + +} + +#endif /* __CONTEXT_TIME_UTIL_H__ */ diff --git a/src/server/legacy/TypesInternal.h b/src/server/legacy/TypesInternal.h new file mode 100644 index 0000000..0bd3cb5 --- /dev/null +++ b/src/server/legacy/TypesInternal.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_SENSOR_RECORDER_TYPES_INTERNAL_H__ +#define __CONTEXT_SENSOR_RECORDER_TYPES_INTERNAL_H__ + +/* Tables */ +#define CLIENT_INFO "SensorClientInfo" + +#define PEDOMETER_RECORD "SensorPedometerRecord" +#define PRESSURE_RECORD "SensorPressureRecord" +#define SLEEP_MONITOR_RECORD "SensorSleepMonitorRecord" +#define HEART_RATE_RECORD "SensorHeartRateRecord" + +/* Privileges */ +#define PRIV_HEALTHINFO "healthinfo" + +/* Constants */ +#define SECONDS_PER_MINUTE 60 +#define SECONDS_PER_HOUR 3600 +#define SECONDS_PER_DAY 86400 + +#define MAX_RETENTION_PERIOD 2678400 /* 1 month (31 days) */ +#define DEFAULT_RETENTION SECONDS_PER_HOUR /* 1 hour */ +#define DEFAULT_QUERY_PERIOD SECONDS_PER_DAY /* 1 day */ + +/* Time Conversions */ +#define SEC_TO_MS(X) ((X) * 1000) + +/* SQL Helper */ +#define TIME_QUANTIZER(key) "ROUND((CAST(" key " AS REAL) - %llu)/CAST(%llu AS REAL) + 0.5)" + +#endif /* __CONTEXT_SENSOR_RECORDER_TYPES_INTERNAL_H__ */ diff --git a/src/server/legacy/UninstallMonitor.cpp b/src/server/legacy/UninstallMonitor.cpp new file mode 100644 index 0000000..026ea10 --- /dev/null +++ b/src/server/legacy/UninstallMonitor.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * 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 "ClientInfo.h" +#include "UninstallMonitor.h" + +using namespace ctx; + +UninstallMonitor::UninstallMonitor() : + __dbusSignalId(-1), + __dbusWatcher(DBusType::SYSTEM) +{ + __dbusSignalId = __dbusWatcher.watch(NULL, + "/org/tizen/pkgmgr/signal", "org.tizen.pkgmgr.signal", "uninstall", this); +} + +UninstallMonitor::~UninstallMonitor() +{ + if (__dbusSignalId > 0) + __dbusWatcher.unwatch(__dbusSignalId); +} + +void UninstallMonitor::onSignal(const char *sender, const char *path, const char *iface, const char *name, GVariant *param) +{ + const gchar *pkgId = NULL; + const gchar *key = NULL; + const gchar *val = NULL; + + g_variant_get(param, "(u&s&s&s&s&s&s)", NULL, NULL, NULL, &pkgId, NULL, &key, &val); + _D("%s, %s, %s", pkgId, key, val); + + IF_FAIL_VOID(pkgId && STR_EQ(key, "end") && STR_EQ(val, "ok")); + + _I("'%s' has been removed", pkgId); + ClientInfo::purgeClient(pkgId); +} diff --git a/src/server/legacy/UninstallMonitor.h b/src/server/legacy/UninstallMonitor.h new file mode 100644 index 0000000..baa3659 --- /dev/null +++ b/src/server/legacy/UninstallMonitor.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_UNINSTALL_MONITOR_H__ +#define __CONTEXT_UNINSTALL_MONITOR_H__ + +#include + +namespace ctx { + + class UninstallMonitor : public IDBusSignalListener { + public: + UninstallMonitor(); + ~UninstallMonitor(); + + void onSignal(const char *sender, const char *path, const char *iface, const char *name, GVariant *param); + + private: + int64_t __dbusSignalId; + DBusSignalWatcher __dbusWatcher; + }; + +} + +#endif /* __CONTEXT_UNINSTALL_MONITOR_H__ */ diff --git a/src/server/legacy/heartrate/HeartRate.cpp b/src/server/legacy/heartrate/HeartRate.cpp new file mode 100644 index 0000000..3afa98e --- /dev/null +++ b/src/server/legacy/heartrate/HeartRate.cpp @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "../TypesInternal.h" +#include "HeartRateLogger.h" +#include "HeartRateQuerier.h" +#include "HeartRate.h" + +using namespace ctx; + +HeartRateProvider::HeartRateProvider() : + SensorProvider(SUBJ_SENSOR_HEART_RATE) +{ + IF_FAIL_VOID(isSupported()); + + sensorLogger = new(std::nothrow) HeartRateLogger(); + IF_FAIL_VOID_TAG(sensorLogger, _E, "Memory allocation failed"); +} + +HeartRateProvider::~HeartRateProvider() +{ +} + +void HeartRateProvider::getPrivilege(std::vector &privilege) +{ + privilege.push_back(PRIV_HEALTHINFO); +} + +bool HeartRateProvider::isSupported() +{ + return util::getSystemInfoBool("tizen.org/feature/sensor.heart_rate_monitor"); +} + +Querier* HeartRateProvider::getQuerier(Json option) +{ + HeartRateQuerier *querier = new(std::nothrow) HeartRateQuerier(this, option); + IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); + return querier; +} + +bool HeartRateProvider::verifyOption(Json option) +{ + std::list keys; + option.getKeys(&keys); + + IF_FAIL_RETURN(keys.size() <= 1, false); + + int interval = 0; + if (option.get(NULL, KEY_INTERVAL, &interval)) { + if (interval < MIN_MEASURING_INTERVAL || interval > MAX_MEASURING_INTERVAL) + return false; + } + + return true; +} diff --git a/src/server/legacy/heartrate/HeartRate.h b/src/server/legacy/heartrate/HeartRate.h new file mode 100644 index 0000000..71f0812 --- /dev/null +++ b/src/server/legacy/heartrate/HeartRate.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_HEARTRATE_PROVIDER_H__ +#define __CONTEXT_HEARTRATE_PROVIDER_H__ + +#include "../SensorProvider.h" + +namespace ctx { + + class HeartRateProvider : public SensorProvider { + public: + HeartRateProvider(); + ~HeartRateProvider(); + + bool isSupported(); + void getPrivilege(std::vector &privilege); + + protected: + Querier* getQuerier(Json option); + bool verifyOption(Json option); + }; +} + +#endif /* _CONTEXT_HEARTRATE_PROVIDER_H_ */ diff --git a/src/server/legacy/heartrate/HeartRateLogger.cpp b/src/server/legacy/heartrate/HeartRateLogger.cpp new file mode 100644 index 0000000..8ef6895 --- /dev/null +++ b/src/server/legacy/heartrate/HeartRateLogger.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "../TypesInternal.h" +#include "../ClientInfo.h" +#include "../TimeUtil.h" +#include "HeartRateLogger.h" + +#define SAMPLING_INTERVAL 200 /* ms */ +#define VALID_HR_LB 30 /* BPM */ +#define MIN_VALID_COUNT 3 +#define MEASURING_LIMIT 10000 /* ms */ + +using namespace ctx; + +HeartRateLogger::HeartRateLogger() : + __timerMgr(NULL), + __timerId(-1), + __timerInterval(INT_MAX), + __expiredTime(0) +{ + setSensor(HRM_SENSOR); + setPowerSave(false); + setSamplingInterval(SAMPLING_INTERVAL); + + /* Create the log table */ + executeQuery( + "CREATE TABLE IF NOT EXISTS " HEART_RATE_RECORD " (" \ + KEY_UNIV_TIME " INTEGER NOT NULL PRIMARY KEY, " \ + KEY_HEART_RATE " REAL NOT NULL" \ + ")"); + + ClientInfo clientInfo; + if (clientInfo.exist(SUBJ_SENSOR_HEART_RATE)) + start(); +} + +HeartRateLogger::~HeartRateLogger() +{ + stop(); +} + +bool HeartRateLogger::start() +{ + std::vector options; + ClientInfo clientInfo; + float interval = MAX_MEASURING_INTERVAL; + + if (clientInfo.get(SUBJ_SENSOR_HEART_RATE, options) != ERR_NONE) + return false; + + clientInfo.getParam(options, KEY_INTERVAL, &interval, NULL); + + if (!__timerMgr) { + __timerMgr = new(std::nothrow) TimerManager; + IF_FAIL_RETURN_TAG(__timerMgr, false, _E, "Memory allocation failed"); + } + + if (interval == __timerInterval) + return true; + + __timerInterval = interval; + + _I(GREEN("Start to record (at every %d minutes)"), __timerInterval); + + if (__timerId > 0) + __timerMgr->remove(__timerId); + + __timerId = __timerMgr->setFor(__timerInterval, this); + + if (__timerId < 0) { + _E("Setting timer failed"); + __timerInterval = INT_MAX; + return false; + } + + return true; +} + +void HeartRateLogger::stop() +{ + _I(GREEN("Stop recording")); + + if (__timerMgr) + delete __timerMgr; + + __timerMgr = NULL; + __timerId = -1; + __timerInterval = INT_MAX; + + unlisten(); +} + +void HeartRateLogger::flushCache(bool force) +{ +} + +bool HeartRateLogger::onTimerExpired(int timerId) +{ + IF_FAIL_RETURN(!isRunning(), true); + + if (!listen()) + _W("Starting sensor failed"); + + __expiredTime = TimeUtil::getTime(); + _I("Measuring starts at %llu", __expiredTime); + return true; +} + +void HeartRateLogger::onEvent(sensor_data_t *eventData) +{ + static int validCnt = 0; + uint64_t receivedTime = TimeUtil::getTime(); + + IF_FAIL_CATCH_TAG(receivedTime - __expiredTime < MEASURING_LIMIT, _I, "Measuring failed (timeout)"); + + if (eventData->values[0] > VALID_HR_LB) + ++validCnt; + else + validCnt = 0; + + if (validCnt < MIN_VALID_COUNT) + return; + + __record(eventData->values[0], receivedTime); + +CATCH: + removeExpired(SUBJ_SENSOR_HEART_RATE, HEART_RATE_RECORD, KEY_UNIV_TIME); + unlisten(); +} + +void HeartRateLogger::__record(float heartrate, uint64_t eventTime) +{ + char *query = sqlite3_mprintf( + "INSERT INTO " HEART_RATE_RECORD \ + " (" KEY_UNIV_TIME ", " KEY_HEART_RATE ") VALUES (%llu, %.3f)", + eventTime, heartrate); + executeQuery(query); + sqlite3_free(query); +} diff --git a/src/server/legacy/heartrate/HeartRateLogger.h b/src/server/legacy/heartrate/HeartRateLogger.h new file mode 100644 index 0000000..fa12aa6 --- /dev/null +++ b/src/server/legacy/heartrate/HeartRateLogger.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_HEARTRATE_LOGGER_H__ +#define __CONTEXT_HEARTRATE_LOGGER_H__ + +#include +#include "../SensorLogger.h" +#include "../SensorProxy.h" + +#define MIN_MEASURING_INTERVAL 10 /* minutes */ +#define MAX_MEASURING_INTERVAL 1440 /* minutes */ + +namespace ctx { + + class HeartRateLogger : public SensorLogger, public SensorProxy, public ITimerListener { + public: + HeartRateLogger(); + ~HeartRateLogger(); + + bool start(); + void stop(); + void flushCache(bool force = false); + + protected: + bool onTimerExpired(int timerId); + void onEvent(sensor_data_t *eventData); + + private: + void __record(float heartrate, uint64_t eventTime); + + TimerManager *__timerMgr; + int __timerId; + int __timerInterval; + uint64_t __expiredTime; + }; +} + +#endif /* __CONTEXT_HEARTRATE_LOGGER_H__ */ diff --git a/src/server/legacy/heartrate/HeartRateQuerier.cpp b/src/server/legacy/heartrate/HeartRateQuerier.cpp new file mode 100644 index 0000000..1bae5a6 --- /dev/null +++ b/src/server/legacy/heartrate/HeartRateQuerier.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "../TypesInternal.h" +#include "HeartRateQuerier.h" + +#define PROJECTION \ + KEY_HEART_RATE ", " \ + KEY_UNIV_TIME " AS " KEY_START_TIME ", " \ + KEY_UNIV_TIME " AS " KEY_END_TIME + +using namespace ctx; + +HeartRateQuerier::HeartRateQuerier(ContextProvider *provider, Json option) : + Querier(provider, option) +{ +} + +HeartRateQuerier::~HeartRateQuerier() +{ +} + +int HeartRateQuerier::queryRaw(int startTime, int endTime) +{ + return query(startTime, endTime); +} + +int HeartRateQuerier::query(int startTime, int endTime) +{ + char *sql = sqlite3_mprintf( + "SELECT " PROJECTION \ + " FROM " HEART_RATE_RECORD \ + " WHERE " KEY_UNIV_TIME " > %llu AND " KEY_UNIV_TIME " <= %llu", + SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); + + int ret = Querier::query(sql); + sqlite3_free(sql); + + return ret; +} diff --git a/src/server/legacy/heartrate/HeartRateQuerier.h b/src/server/legacy/heartrate/HeartRateQuerier.h new file mode 100644 index 0000000..335d902 --- /dev/null +++ b/src/server/legacy/heartrate/HeartRateQuerier.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_HEARTRATE_QUERIER_H__ +#define __CONTEXT_HEARTRATE_QUERIER_H__ + +#include "../Querier.h" + +namespace ctx { + + class HeartRateQuerier : public Querier { + public: + HeartRateQuerier(ContextProvider *provider, Json option); + ~HeartRateQuerier(); + + int queryRaw(int startTime, int endTime); + int query(int startTime, int endTime); + }; +} + +#endif /* __CONTEXT_HEARTRATE_QUERIER_H__ */ diff --git a/src/server/legacy/pedometer/Pedometer.cpp b/src/server/legacy/pedometer/Pedometer.cpp new file mode 100644 index 0000000..8752754 --- /dev/null +++ b/src/server/legacy/pedometer/Pedometer.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "../TypesInternal.h" +#include "PedometerLogger.h" +#include "PedometerQuerier.h" +#include "Pedometer.h" + +using namespace ctx; + +PedometerProvider::PedometerProvider() : + SensorProvider(SUBJ_SENSOR_PEDOMETER) +{ + IF_FAIL_VOID(isSupported()); + + sensorLogger = new(std::nothrow) PedometerLogger(); + IF_FAIL_VOID_TAG(sensorLogger, _E, "Memory allocation failed"); +} + +PedometerProvider::~PedometerProvider() +{ +} + +void PedometerProvider::getPrivilege(std::vector &privilege) +{ + privilege.push_back(PRIV_HEALTHINFO); +} + +bool PedometerProvider::isSupported() +{ + return util::getSystemInfoBool("tizen.org/feature/sensor.pedometer"); +} + +Querier* PedometerProvider::getQuerier(Json option) +{ + PedometerQuerier *querier = new(std::nothrow) PedometerQuerier(this, option); + IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); + return querier; +} diff --git a/src/server/legacy/pedometer/Pedometer.h b/src/server/legacy/pedometer/Pedometer.h new file mode 100644 index 0000000..7fee01f --- /dev/null +++ b/src/server/legacy/pedometer/Pedometer.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_PEDOMETER_PROVIDER_H__ +#define __CONTEXT_PEDOMETER_PROVIDER_H__ + +#include "../SensorProvider.h" + +namespace ctx { + + class PedometerProvider : public SensorProvider { + public: + PedometerProvider(); + ~PedometerProvider(); + + bool isSupported(); + void getPrivilege(std::vector &privilege); + + protected: + Querier* getQuerier(Json option); + }; +} + +#endif /* _CONTEXT_PEDOMETER_PROVIDER_H_ */ diff --git a/src/server/legacy/pedometer/PedometerLogger.cpp b/src/server/legacy/pedometer/PedometerLogger.cpp new file mode 100644 index 0000000..cc44856 --- /dev/null +++ b/src/server/legacy/pedometer/PedometerLogger.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "../TypesInternal.h" +#include "../ClientInfo.h" +#include "../TimeUtil.h" +#include "PedometerLogger.h" + +#define MIN_INTERVAL 60000 + +using namespace ctx; + +PedometerLogger::PedometerLogger() : + __firstEvent(true) +{ + setSensor(HUMAN_PEDOMETER_SENSOR); + setPowerSave(false); + + /* Create the log table */ + executeQuery( + "CREATE TABLE IF NOT EXISTS " PEDOMETER_RECORD " (" \ + KEY_START_TIME " INTEGER NOT NULL, " \ + KEY_END_TIME " INTEGER NOT NULL PRIMARY KEY, " \ + KEY_WALK_STEPS " INTEGER NOT NULL, " \ + KEY_RUN_STEPS " INTEGER NOT NULL, " \ + KEY_DISTANCE " REAL NOT NULL, " \ + KEY_CALORIES " REAL NOT NULL" \ + ")"); + + ClientInfo clientInfo; + if (clientInfo.exist(SUBJ_SENSOR_PEDOMETER)) + start(); +} + +PedometerLogger::~PedometerLogger() +{ + stop(); +} + +bool PedometerLogger::start() +{ + IF_FAIL_RETURN_TAG(!isRunning(), true, _D, "Started already"); + _I(GREEN("Start to record")); + + if (listen()) { + flush(); + return true; + } + + return false; +} + +void PedometerLogger::stop() +{ + IF_FAIL_VOID_TAG(isRunning(), _D, "Stopped already"); + _I(GREEN("Stop recording")); + + unlisten(); + __firstEvent = true; + + flushCache(true); +} + +void PedometerLogger::flushCache(bool force) +{ + DataRecord record; + record.walkSteps = __lastRecord.walkSteps - __baseline.walkSteps; + record.runSteps = __lastRecord.runSteps - __baseline.runSteps; + record.distance = __lastRecord.distance - __baseline.distance; + record.calories = __lastRecord.calories - __baseline.calories; + + if (record.walkSteps + record.runSteps > 0) { + char *query = sqlite3_mprintf( + "INSERT INTO " PEDOMETER_RECORD " (" \ + KEY_START_TIME ", " \ + KEY_END_TIME ", " \ + KEY_WALK_STEPS ", " \ + KEY_RUN_STEPS ", " \ + KEY_DISTANCE ", " \ + KEY_CALORIES ") " \ + "VALUES (%llu, %llu, %u, %u, %.3f, %.3f)", + __baseline.timestamp, __lastRecord.timestamp, record.walkSteps, record.runSteps, record.distance, record.calories); + executeQuery(query); + sqlite3_free(query); + } + + __baseline = __lastRecord; +} + +void PedometerLogger::onEvent(sensor_data_t *eventData) +{ + sensor_pedometer_data_t *pedometerData = reinterpret_cast(eventData); + uint64_t timestamp = TimeUtil::getTime(); + + if (__firstEvent) { + __firstEvent = false; + __setRecord(__lastRecord, timestamp, pedometerData); + __baseline = __lastRecord; + + _SD("Baseline: %u, %u, %.3f, %.3f", + __baseline.walkSteps, __baseline.runSteps, __baseline.distance, __baseline.calories); + + } else if (pedometerData->diffs_count == 0) { + _SD("Single: %.0f, %.0f, %.3f, %.3f", + eventData->values[1], eventData->values[2], eventData->values[3], eventData->values[4]); + __recordSingle(pedometerData, timestamp); + + } else { + _SD("Batch [%d]: %.0f, %.0f, %.3f, %.3f", + pedometerData->diffs_count, + eventData->values[1], eventData->values[2], eventData->values[3], eventData->values[4]); + __recordBatch(pedometerData, timestamp); + } + + removeExpired(SUBJ_SENSOR_PEDOMETER, PEDOMETER_RECORD, KEY_END_TIME); +} + +void PedometerLogger::__recordSingle(sensor_pedometer_data_t *eventData, uint64_t timestamp) +{ + if (timestamp - __baseline.timestamp >= MIN_INTERVAL) + flushCache(); + + __setRecord(__lastRecord, timestamp, eventData); +} + +void PedometerLogger::__recordBatch(sensor_pedometer_data_t *eventData, uint64_t timestamp) +{ + flushCache(); + + std::string query("INSERT INTO " PEDOMETER_RECORD " (" \ + KEY_START_TIME ", " \ + KEY_END_TIME ", " \ + KEY_WALK_STEPS ", " \ + KEY_RUN_STEPS ", " \ + KEY_DISTANCE ", " \ + KEY_CALORIES ") VALUES "); + char buffer[256]; + + for (int i = 0; i < eventData->diffs_count; ++i) { + if (eventData->diffs[i].walk_steps + eventData->diffs[i].run_steps == 0) { + _D("Skipping zero-count event"); + continue; + } + + /* TODO: check the timestamps.. they look strange.. */ + g_snprintf(buffer, sizeof(buffer), "(%" PRIu64 ", %" PRIu64 ", %d, %d, %.3f, %.3f),", + i == 0 ? __baseline.timestamp : SEC_TO_MS(static_cast(eventData->diffs[i-1].timestamp)), + SEC_TO_MS(static_cast(eventData->diffs[i].timestamp)), + eventData->diffs[i].walk_steps, + eventData->diffs[i].run_steps, + eventData->diffs[i].distance, + eventData->diffs[i].calories); + query += buffer; + } + + query.resize(query.size() - 1); + IF_FAIL_VOID_TAG(query.at(query.size() - 1) == ')', _D, "No records"); + + executeQuery(query.c_str()); + + __setRecord(__lastRecord, timestamp, eventData); + __baseline = __lastRecord; +} + +void PedometerLogger::__setRecord(DataRecord &record, uint64_t timestamp, sensor_pedometer_data_t *eventData) +{ + record.timestamp = timestamp; + record.walkSteps = static_cast(eventData->values[1]); + record.runSteps = static_cast(eventData->values[2]); + record.distance = eventData->values[3]; + record.calories = eventData->values[4]; +} diff --git a/src/server/legacy/pedometer/PedometerLogger.h b/src/server/legacy/pedometer/PedometerLogger.h new file mode 100644 index 0000000..f4b32f9 --- /dev/null +++ b/src/server/legacy/pedometer/PedometerLogger.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_PEDOMETER_LOGGER_H__ +#define __CONTEXT_PEDOMETER_LOGGER_H__ + +#include "../SensorLogger.h" +#include "../SensorProxy.h" + +namespace ctx { + + class PedometerLogger : public SensorLogger, public SensorProxy { + public: + PedometerLogger(); + ~PedometerLogger(); + + bool start(); + void stop(); + void flushCache(bool force = false); + + protected: + void onEvent(sensor_data_t *eventData); + + private: + struct DataRecord { + uint64_t timestamp; + unsigned int walkSteps; + unsigned int runSteps; + float distance; + float calories; + }; + + void __recordSingle(sensor_pedometer_data_t *eventData, uint64_t timestamp); + void __recordBatch(sensor_pedometer_data_t *eventData, uint64_t timestamp); + void __setRecord(DataRecord &record, uint64_t timestamp, sensor_pedometer_data_t *eventData); + + bool __firstEvent; + DataRecord __baseline; + DataRecord __lastRecord; + }; +} + +#endif /* __CONTEXT_PEDOMETER_LOGGER_H__ */ diff --git a/src/server/legacy/pedometer/PedometerQuerier.cpp b/src/server/legacy/pedometer/PedometerQuerier.cpp new file mode 100644 index 0000000..3abf121 --- /dev/null +++ b/src/server/legacy/pedometer/PedometerQuerier.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "../TypesInternal.h" +#include "PedometerQuerier.h" + +#define PROJECTION \ + "SUM(" KEY_WALK_STEPS " + " KEY_RUN_STEPS ") AS " KEY_STEPS ", " \ + "SUM(" KEY_WALK_STEPS ") AS " KEY_WALK_STEPS ", " \ + "SUM(" KEY_RUN_STEPS ") AS " KEY_RUN_STEPS ", " \ + "SUM(" KEY_DISTANCE ") AS " KEY_DISTANCE ", " \ + "SUM(" KEY_CALORIES ") AS " KEY_CALORIES ", " \ + "MIN(" KEY_START_TIME ") AS " KEY_START_TIME ", " \ + "MAX(" KEY_END_TIME ") AS " KEY_END_TIME + +#define PROJECTION_RAW \ + KEY_WALK_STEPS " + " KEY_RUN_STEPS " AS " KEY_STEPS ", " \ + KEY_WALK_STEPS ", " \ + KEY_RUN_STEPS ", " \ + KEY_DISTANCE ", " \ + KEY_CALORIES ", " \ + KEY_START_TIME ", " \ + KEY_END_TIME + +using namespace ctx; + +PedometerQuerier::PedometerQuerier(ContextProvider *provider, Json option) : + Querier(provider, option) +{ +} + +PedometerQuerier::~PedometerQuerier() +{ +} + +int PedometerQuerier::queryRaw(int startTime, int endTime) +{ + char *sql = sqlite3_mprintf( + "SELECT " PROJECTION_RAW \ + " FROM " PEDOMETER_RECORD \ + " WHERE " KEY_END_TIME " > %llu AND " KEY_END_TIME " <= %llu" \ + " ORDER BY " KEY_END_TIME " ASC", + SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); + + int ret = Querier::query(sql); + sqlite3_free(sql); + + return ret; +} + +int PedometerQuerier::query(int startTime, int endTime) +{ + char *sql = sqlite3_mprintf( + "SELECT " PROJECTION \ + " FROM " PEDOMETER_RECORD \ + " WHERE " KEY_END_TIME " > %llu AND " KEY_END_TIME " <= %llu", + SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); + + int ret = Querier::query(sql); + sqlite3_free(sql); + + return ret; +} + +int PedometerQuerier::query(int startTime, int endTime, int anchor, int interval) +{ + char *sql = sqlite3_mprintf( + "SELECT " PROJECTION \ + " FROM " PEDOMETER_RECORD \ + " WHERE " KEY_END_TIME " > %llu AND " KEY_END_TIME " <= %llu" \ + " GROUP BY " TIME_QUANTIZER(KEY_END_TIME) \ + " ORDER BY " KEY_END_TIME " ASC", + SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime)), + SEC_TO_MS(static_cast(anchor)), SEC_TO_MS(static_cast(interval))); + + int ret = Querier::query(sql); + sqlite3_free(sql); + + return ret; +} diff --git a/src/server/legacy/pedometer/PedometerQuerier.h b/src/server/legacy/pedometer/PedometerQuerier.h new file mode 100644 index 0000000..21af1e1 --- /dev/null +++ b/src/server/legacy/pedometer/PedometerQuerier.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_PEDOMETER_QUERIER_H__ +#define __CONTEXT_PEDOMETER_QUERIER_H__ + +#include "../Querier.h" + +namespace ctx { + + class PedometerQuerier : public Querier { + public: + PedometerQuerier(ContextProvider *provider, Json option); + ~PedometerQuerier(); + + int queryRaw(int startTime, int endTime); + int query(int startTime, int endTime); + int query(int startTime, int endTime, int anchor, int interval); + }; +} + +#endif /* __CONTEXT_PEDOMETER_QUERIER_H__ */ diff --git a/src/server/legacy/pressure/Pressure.cpp b/src/server/legacy/pressure/Pressure.cpp new file mode 100644 index 0000000..76b60f4 --- /dev/null +++ b/src/server/legacy/pressure/Pressure.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "../TypesInternal.h" +#include "PressureLogger.h" +#include "PressureQuerier.h" +#include "Pressure.h" + +using namespace ctx; + +PressureProvider::PressureProvider() : + SensorProvider(SUBJ_SENSOR_PRESSURE) +{ + IF_FAIL_VOID(isSupported()); + + sensorLogger = new(std::nothrow) PressureLogger(); + IF_FAIL_VOID_TAG(sensorLogger, _E, "Memory allocation failed"); +} + +PressureProvider::~PressureProvider() +{ +} + +bool PressureProvider::isSupported() +{ + return util::getSystemInfoBool("tizen.org/feature/sensor.barometer"); +} + +Querier* PressureProvider::getQuerier(Json option) +{ + PressureQuerier *querier = new(std::nothrow) PressureQuerier(this, option); + IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); + return querier; +} diff --git a/src/server/legacy/pressure/Pressure.h b/src/server/legacy/pressure/Pressure.h new file mode 100644 index 0000000..419cfba --- /dev/null +++ b/src/server/legacy/pressure/Pressure.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_PRESSURE_PROVIDER_H__ +#define __CONTEXT_PRESSURE_PROVIDER_H__ + +#include "../SensorProvider.h" + +namespace ctx { + + class PressureProvider : public SensorProvider { + public: + PressureProvider(); + ~PressureProvider(); + + bool isSupported(); + + protected: + Querier* getQuerier(Json option); + }; +} + +#endif /* _CONTEXT_PRESSURE_PROVIDER_H_ */ diff --git a/src/server/legacy/pressure/PressureLogger.cpp b/src/server/legacy/pressure/PressureLogger.cpp new file mode 100644 index 0000000..0bb1fe4 --- /dev/null +++ b/src/server/legacy/pressure/PressureLogger.cpp @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "../TypesInternal.h" +#include "../ClientInfo.h" +#include "../TimeUtil.h" +#include "PressureLogger.h" + +#define SAMPLING_INTERVAL 60000 +#define BATCH_LATENCY INT_MAX + +#define RESAMPLING_INTERVAL 20000 +#define CACHE_LIMIT 20 + +using namespace ctx; + +PressureLogger::PressureLogger() +{ + setSensor(PRESSURE_SENSOR); + setPowerSave(false); + setSamplingInterval(SAMPLING_INTERVAL); + setBatchLatency(BATCH_LATENCY); + + /* Create the log table */ + executeQuery( + "CREATE TABLE IF NOT EXISTS " PRESSURE_RECORD " (" \ + KEY_UNIV_TIME " INTEGER NOT NULL PRIMARY KEY, " \ + KEY_PRESSURE " REAL NOT NULL" \ + ")"); + + ClientInfo clientInfo; + if (clientInfo.exist(SUBJ_SENSOR_PRESSURE)) + start(); +} + +PressureLogger::~PressureLogger() +{ + stop(); +} + +bool PressureLogger::start() +{ + IF_FAIL_RETURN_TAG(!isRunning(), true, _D, "Started already"); + _I(GREEN("Start to record")); + + __lastEventTime = 0; + __cacheCount = 0; + __resetInsertionQuery(); + + return listen(); +} + +void PressureLogger::stop() +{ + IF_FAIL_VOID_TAG(isRunning(), _D, "Stopped already"); + _I(GREEN("Stop recording")); + + unlisten(); + flushCache(true); +} + +void PressureLogger::flushCache(bool force) +{ + IF_FAIL_VOID(force || __cacheCount > CACHE_LIMIT); + + __insertionQuery.resize(__insertionQuery.size() - 1); + if (__insertionQuery.at(__insertionQuery.size() - 1) == ')') + executeQuery(__insertionQuery.c_str()); + + __cacheCount = 0; + __resetInsertionQuery(); +} + +void PressureLogger::onEvent(sensor_data_t *eventData) +{ + uint64_t eventTime = TimeUtil::getTime(eventData->timestamp); + __record(eventData->values[0], eventTime); + removeExpired(SUBJ_SENSOR_PRESSURE, PRESSURE_RECORD, KEY_UNIV_TIME); +} + +void PressureLogger::__record(float pressure, uint64_t eventTime) +{ + IF_FAIL_VOID(eventTime - __lastEventTime >= RESAMPLING_INTERVAL); + + char buffer[64]; + g_snprintf(buffer, sizeof(buffer), "(%" PRIu64 ", %.5f),", eventTime, pressure); + _D("[%u] %s", __cacheCount, buffer); + + __insertionQuery += buffer; + __lastEventTime = eventTime; + ++__cacheCount; + + flushCache(); +} + +void PressureLogger::__resetInsertionQuery() +{ + __insertionQuery = + "INSERT INTO " PRESSURE_RECORD \ + " (" KEY_UNIV_TIME ", " KEY_PRESSURE ") VALUES "; +} diff --git a/src/server/legacy/pressure/PressureLogger.h b/src/server/legacy/pressure/PressureLogger.h new file mode 100644 index 0000000..78b7fe5 --- /dev/null +++ b/src/server/legacy/pressure/PressureLogger.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_PRESSURE_LOGGER_H__ +#define __CONTEXT_PRESSURE_LOGGER_H__ + +#include "../SensorLogger.h" +#include "../SensorProxy.h" + +namespace ctx { + + class PressureLogger : public SensorLogger, public SensorProxy { + public: + PressureLogger(); + ~PressureLogger(); + + bool start(); + void stop(); + void flushCache(bool force = false); + + protected: + void onEvent(sensor_data_t *eventData); + + private: + void __record(float pressure, uint64_t eventTime); + void __resetInsertionQuery(); + + uint64_t __lastEventTime; + uint32_t __cacheCount; + std::string __insertionQuery; + }; +} + +#endif /* __CONTEXT_PRESSURE_LOGGER_H__ */ diff --git a/src/server/legacy/pressure/PressureQuerier.cpp b/src/server/legacy/pressure/PressureQuerier.cpp new file mode 100644 index 0000000..8d19638 --- /dev/null +++ b/src/server/legacy/pressure/PressureQuerier.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "../TypesInternal.h" +#include "PressureQuerier.h" + +#define PROJECTION \ + "AVG(" KEY_PRESSURE ") AS " KEY_PRESSURE ", " \ + "MIN(" KEY_PRESSURE ") AS " KEY_MIN_PRESSURE ", " \ + "MAX(" KEY_PRESSURE ") AS " KEY_MAX_PRESSURE ", " \ + "AVG(" KEY_PRESSURE ") AS " KEY_AVG_PRESSURE ", " \ + "MIN(" KEY_UNIV_TIME ") AS " KEY_START_TIME ", " \ + "MAX(" KEY_UNIV_TIME ") AS " KEY_END_TIME + +#define PROJECTION_RAW \ + KEY_PRESSURE ", " \ + KEY_PRESSURE " AS " KEY_MIN_PRESSURE ", " \ + KEY_PRESSURE " AS " KEY_MAX_PRESSURE ", " \ + KEY_PRESSURE " AS " KEY_AVG_PRESSURE ", " \ + KEY_UNIV_TIME " AS " KEY_START_TIME ", " \ + KEY_UNIV_TIME " AS " KEY_END_TIME + +using namespace ctx; + +PressureQuerier::PressureQuerier(ContextProvider *provider, Json option) : + Querier(provider, option) +{ +} + +PressureQuerier::~PressureQuerier() +{ +} + +int PressureQuerier::queryRaw(int startTime, int endTime) +{ + char *sql = sqlite3_mprintf( + "SELECT " PROJECTION_RAW \ + " FROM " PRESSURE_RECORD \ + " WHERE " KEY_UNIV_TIME " > %llu AND " KEY_UNIV_TIME " <= %llu", + SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); + + int ret = Querier::query(sql); + sqlite3_free(sql); + + return ret; +} + +int PressureQuerier::query(int startTime, int endTime) +{ + char *sql = sqlite3_mprintf( + "SELECT " PROJECTION \ + " FROM " PRESSURE_RECORD \ + " WHERE " KEY_UNIV_TIME " > %llu AND " KEY_UNIV_TIME " <= %llu", + SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); + + int ret = Querier::query(sql); + sqlite3_free(sql); + + return ret; +} + +int PressureQuerier::query(int startTime, int endTime, int anchor, int interval) +{ + char *sql = sqlite3_mprintf( + "SELECT " PROJECTION \ + " FROM " PRESSURE_RECORD \ + " WHERE " KEY_UNIV_TIME " > %llu AND " KEY_UNIV_TIME " <= %llu" \ + " GROUP BY " TIME_QUANTIZER(KEY_UNIV_TIME) \ + " ORDER BY " KEY_END_TIME " ASC", + SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime)), + SEC_TO_MS(static_cast(anchor)), SEC_TO_MS(static_cast(interval))); + + int ret = Querier::query(sql); + sqlite3_free(sql); + + return ret; +} diff --git a/src/server/legacy/pressure/PressureQuerier.h b/src/server/legacy/pressure/PressureQuerier.h new file mode 100644 index 0000000..1bd9aa6 --- /dev/null +++ b/src/server/legacy/pressure/PressureQuerier.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_PRESSURE_QUERIER_H__ +#define __CONTEXT_PRESSURE_QUERIER_H__ + +#include "../Querier.h" + +namespace ctx { + + class PressureQuerier : public Querier { + public: + PressureQuerier(ContextProvider *provider, Json option); + ~PressureQuerier(); + + int queryRaw(int startTime, int endTime); + int query(int startTime, int endTime); + int query(int startTime, int endTime, int anchor, int interval); + }; +} + +#endif /* __CONTEXT_PRESSURE_QUERIER_H__ */ diff --git a/src/server/legacy/sleep/Sleep.cpp b/src/server/legacy/sleep/Sleep.cpp new file mode 100644 index 0000000..3ae40c9 --- /dev/null +++ b/src/server/legacy/sleep/Sleep.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "../TypesInternal.h" +#include "SleepLogger.h" +#include "SleepQuerier.h" +#include "Sleep.h" + +using namespace ctx; + +SleepProvider::SleepProvider() : + SensorProvider(SUBJ_SENSOR_SLEEP_MONITOR) +{ + IF_FAIL_VOID(isSupported()); + + sensorLogger = new(std::nothrow) SleepLogger(); + IF_FAIL_VOID_TAG(sensorLogger, _E, "Memory allocation failed"); +} + +SleepProvider::~SleepProvider() +{ +} + +void SleepProvider::getPrivilege(std::vector &privilege) +{ + privilege.push_back(PRIV_HEALTHINFO); +} + +bool SleepProvider::isSupported() +{ + return util::getSystemInfoBool("tizen.org/feature/sensor.sleep_monitor"); +} + +Querier* SleepProvider::getQuerier(Json option) +{ + SleepQuerier *querier = new(std::nothrow) SleepQuerier(this, option); + IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); + return querier; +} diff --git a/src/server/legacy/sleep/Sleep.h b/src/server/legacy/sleep/Sleep.h new file mode 100644 index 0000000..c93310e --- /dev/null +++ b/src/server/legacy/sleep/Sleep.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_SLEEP_PROVIDER_H__ +#define __CONTEXT_SLEEP_PROVIDER_H__ + +#include "../SensorProvider.h" + +namespace ctx { + + class SleepProvider : public SensorProvider { + public: + SleepProvider(); + ~SleepProvider(); + + void getPrivilege(std::vector &privilege); + bool isSupported(); + + protected: + Querier* getQuerier(Json option); + }; +} + +#endif /* _CONTEXT_SLEEP_PROVIDER_H_ */ diff --git a/src/server/legacy/sleep/SleepDetector.cpp b/src/server/legacy/sleep/SleepDetector.cpp new file mode 100644 index 0000000..5367dac --- /dev/null +++ b/src/server/legacy/sleep/SleepDetector.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "../TimeUtil.h" +#include "SleepDetector.h" + +#define IDX_SLEEP_STATE 0 + +using namespace ctx; + +SleepDetector::SleepDetector(SleepLogger *logger) : + __logger(logger) +{ + setSensor(HUMAN_SLEEP_DETECTOR_SENSOR); + setPowerSave(false); +} + +SleepDetector::~SleepDetector() +{ +} + +bool SleepDetector::start() +{ + _D("START"); + return listen(); +} + +void SleepDetector::stop() +{ + _D("STOP"); + unlisten(); +} + +void SleepDetector::onEvent(sensor_data_t *eventData) +{ + _D("%d at %llu", (int)eventData->values[0], eventData->timestamp); + + uint64_t eventTime = TimeUtil::getTime(eventData->timestamp); + + if (static_cast(eventData->values[IDX_SLEEP_STATE])) + __logger->fallAsleep(eventTime); + else + __logger->wakeUp(eventTime); +} diff --git a/src/server/legacy/sleep/SleepDetector.h b/src/server/legacy/sleep/SleepDetector.h new file mode 100644 index 0000000..104678c --- /dev/null +++ b/src/server/legacy/sleep/SleepDetector.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_SLEEP_DETECTOR_H__ +#define __CONTEXT_SLEEP_DETECTOR_H__ + +#include "../SensorProxy.h" +#include "SleepLogger.h" + +namespace ctx { + + class SleepDetector : public SensorProxy { + public: + SleepDetector(SleepLogger *logger); + ~SleepDetector(); + + bool start(); + void stop(); + + protected: + void onEvent(sensor_data_t *eventData); + + private: + SleepLogger *__logger; + }; +} + +#endif /* __CONTEXT_SLEEP_DETECTOR_H__ */ diff --git a/src/server/legacy/sleep/SleepLogger.cpp b/src/server/legacy/sleep/SleepLogger.cpp new file mode 100644 index 0000000..171df5b --- /dev/null +++ b/src/server/legacy/sleep/SleepLogger.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "../TypesInternal.h" +#include "../ClientInfo.h" +#include "../TimeUtil.h" +#include "SleepDetector.h" +#include "SleepMonitor.h" +#include "SleepLogger.h" + +#define TIME_GAP 5000 + +using namespace ctx; + +static SleepDetector *__sleepDetector = NULL; +static SleepMonitor *__sleepMonitor = NULL; + +SleepLogger::SleepLogger() : + __startTime(0), + __endTime(0) +{ + __sleepDetector = NULL; + __sleepMonitor = NULL; + + /* Create the log table */ + executeQuery( + "CREATE TABLE IF NOT EXISTS " SLEEP_MONITOR_RECORD " (" \ + KEY_START_TIME " INTEGER NOT NULL, " \ + KEY_END_TIME " INTEGER NOT NULL PRIMARY KEY, " \ + KEY_STATE " INTEGER NOT NULL DEFAULT 1" \ + ")"); + + ClientInfo clientInfo; + if (clientInfo.exist(SUBJ_SENSOR_SLEEP_MONITOR)) + start(); +} + +SleepLogger::~SleepLogger() +{ + stop(); +} + +bool SleepLogger::start() +{ + if (!__sleepDetector) { + __sleepDetector = new(std::nothrow) SleepDetector(this); + __sleepMonitor = new(std::nothrow) SleepMonitor(this); + + if (!__sleepDetector || !__sleepMonitor) { + _E("Memory allocation failed"); + + delete __sleepDetector; + __sleepDetector = NULL; + + delete __sleepMonitor; + __sleepMonitor = NULL; + + return false; + } + } + + if (__sleepDetector->isRunning()) { + _D("Started already"); + return true; + } + + _I(GREEN("Start to record")); + + __startTime = 0; + __endTime = 0; + __resetInsertionQuery(); + + return __sleepDetector->start(); +} + +void SleepLogger::stop() +{ + IF_FAIL_VOID_TAG(__sleepDetector, _D, "Stopped already"); + _I(GREEN("Stop recording")); + + __sleepDetector->stop(); + __sleepMonitor->stop(); + + __appendQuery(__startTime, __endTime); + flushCache(); + + delete __sleepDetector; + __sleepDetector = NULL; + + delete __sleepMonitor; + __sleepMonitor = NULL; +} + +void SleepLogger::fallAsleep(uint64_t timestamp) +{ + _D("Fall asleep"); + record(timestamp, TimeUtil::getTime(), STATE_SLEEP); + __sleepMonitor->start(); +} + +void SleepLogger::wakeUp(uint64_t timestamp) +{ + _D("Wake up"); + __sleepMonitor->lazyStop(); +} + +void SleepLogger::record(uint64_t startTime, uint64_t endTime, int state) +{ + IF_FAIL_VOID(state == STATE_SLEEP); /* For now, we don't need to record the awaken state */ + IF_FAIL_VOID_TAG(startTime < endTime, _W, "Invalid parameter"); + + if (__startTime == 0) { + __startTime = startTime; + __endTime = endTime; + _D("Initial event: %llu ~ %llu", __startTime, __endTime); + return; + } + + if (startTime < __endTime + TIME_GAP) { + __endTime = MAX(endTime, __endTime); + _D("Merged event: %llu ~ %llu", __startTime, __endTime); + return; + } + + __appendQuery(__startTime, __endTime); + __startTime = startTime; + __endTime = endTime; + _D("Reset event: %llu ~ %llu", __startTime, __endTime); +} + +void SleepLogger::flushCache(bool force) +{ + __insertionQuery.resize(__insertionQuery.size() - 1); + if (__insertionQuery.at(__insertionQuery.size() - 1) == ')') + executeQuery(__insertionQuery.c_str()); + + __resetInsertionQuery(); +} + +void SleepLogger::__resetInsertionQuery() +{ + __insertionQuery = + "INSERT INTO " SLEEP_MONITOR_RECORD \ + " (" KEY_START_TIME ", " KEY_END_TIME ") VALUES "; +} + +void SleepLogger::__appendQuery(uint64_t startTime, uint64_t endTime) +{ + IF_FAIL_VOID(startTime > 0 && endTime > startTime); + + char buffer[64]; + g_snprintf(buffer, sizeof(buffer), "(%" PRIu64 ", %" PRIu64 "),", startTime, endTime); + __insertionQuery += buffer; +} diff --git a/src/server/legacy/sleep/SleepLogger.h b/src/server/legacy/sleep/SleepLogger.h new file mode 100644 index 0000000..5bf25d1 --- /dev/null +++ b/src/server/legacy/sleep/SleepLogger.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_SLEEP_LOGGER_H__ +#define __CONTEXT_SLEEP_LOGGER_H__ + +#include "../SensorLogger.h" + +#define STATE_SLEEP 1 +#define STATE_WAKE 0 + +namespace ctx { + + class SleepLogger : public SensorLogger { + public: + SleepLogger(); + ~SleepLogger(); + + bool start(); + void stop(); + + void fallAsleep(uint64_t timestamp); + void wakeUp(uint64_t timestamp); + + void record(uint64_t startTime, uint64_t endTime, int state); + void flushCache(bool force = false); + + private: + void __resetInsertionQuery(); + void __appendQuery(uint64_t startTime, uint64_t endTime); + + std::string __insertionQuery; + uint64_t __startTime; + uint64_t __endTime; + }; +} + +#endif /* __CONTEXT_SLEEP_LOGGER_H__ */ diff --git a/src/server/legacy/sleep/SleepMonitor.cpp b/src/server/legacy/sleep/SleepMonitor.cpp new file mode 100644 index 0000000..9b0b227 --- /dev/null +++ b/src/server/legacy/sleep/SleepMonitor.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "../TypesInternal.h" +#include "../TimeUtil.h" +#include "SleepMonitor.h" + +#define IDX_SLEEP_STATE 0 +#define IDX_REMAINING 6 + +using namespace ctx; + +SleepMonitor::SleepMonitor(SleepLogger *logger) : + __logger(logger), + __lazyStopOn(false) +{ + setSensor(HUMAN_SLEEP_MONITOR_SENSOR); + setPowerSave(false); +} + +SleepMonitor::~SleepMonitor() +{ +} + +bool SleepMonitor::start() +{ + _D("START"); + __lazyStopOn = false; + return listen(); +} + +void SleepMonitor::stop() +{ + _D("STOP"); + unlisten(); +} + +void SleepMonitor::lazyStop() +{ + if (!isRunning()) + return; + + __lazyStopOn = true; +} + +void SleepMonitor::onEvent(sensor_data_t *eventData) +{ + _D("%d at %llu", (int)eventData->values[IDX_SLEEP_STATE], eventData->timestamp); + + uint64_t timestamp = TimeUtil::getTime(eventData->timestamp); + __logger->record(timestamp - SEC_TO_MS(SECONDS_PER_MINUTE), timestamp, + static_cast(eventData->values[IDX_SLEEP_STATE])); + + if (static_cast(eventData->values[IDX_REMAINING]) > 0) + return; + + __logger->flushCache(); + + if (__lazyStopOn) + stop(); +} diff --git a/src/server/legacy/sleep/SleepMonitor.h b/src/server/legacy/sleep/SleepMonitor.h new file mode 100644 index 0000000..7aa37d9 --- /dev/null +++ b/src/server/legacy/sleep/SleepMonitor.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_SLEEP_MONITOR_H__ +#define __CONTEXT_SLEEP_MONITOR_H__ + +#include "../SensorProxy.h" +#include "SleepLogger.h" + +namespace ctx { + + class SleepMonitor : public SensorProxy { + public: + SleepMonitor(SleepLogger *logger); + ~SleepMonitor(); + + bool start(); + void stop(); + + void lazyStop(); + + protected: + void onEvent(sensor_data_t *eventData); + + private: + SleepLogger *__logger; + bool __lazyStopOn; + }; +} + +#endif /* __CONTEXT_SLEEP_MONITOR_H__ */ diff --git a/src/server/legacy/sleep/SleepQuerier.cpp b/src/server/legacy/sleep/SleepQuerier.cpp new file mode 100644 index 0000000..1a8f8dc --- /dev/null +++ b/src/server/legacy/sleep/SleepQuerier.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "../TypesInternal.h" +#include "SleepQuerier.h" + +#define PROJECTION \ + KEY_STATE ", " \ + KEY_START_TIME ", " \ + KEY_END_TIME + +using namespace ctx; + +SleepQuerier::SleepQuerier(ContextProvider *provider, Json option) : + Querier(provider, option) +{ +} + +SleepQuerier::~SleepQuerier() +{ +} + +int SleepQuerier::queryRaw(int startTime, int endTime) +{ + return query(startTime, endTime); +} + +int SleepQuerier::query(int startTime, int endTime) +{ + char *sql = sqlite3_mprintf( + "SELECT " PROJECTION \ + " FROM " SLEEP_MONITOR_RECORD \ + " WHERE " KEY_END_TIME " > %llu AND " KEY_START_TIME " <= %llu", + SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); + + int ret = Querier::query(sql); + sqlite3_free(sql); + + return ret; +} diff --git a/src/server/legacy/sleep/SleepQuerier.h b/src/server/legacy/sleep/SleepQuerier.h new file mode 100644 index 0000000..7ba674f --- /dev/null +++ b/src/server/legacy/sleep/SleepQuerier.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_SLEEP_QUERIER_H__ +#define __CONTEXT_SLEEP_QUERIER_H__ + +#include "../Querier.h" + +namespace ctx { + + class SleepQuerier : public Querier { + public: + SleepQuerier(ContextProvider *provider, Json option); + ~SleepQuerier(); + + int queryRaw(int startTime, int endTime); + int query(int startTime, int endTime); + }; +} + +#endif /* __CONTEXT_SLEEP_QUERIER_H__ */ -- 2.7.4 From 4f60360bdae35c94ce64275f341868676b05dfeb Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 19 May 2017 14:04:33 +0900 Subject: [PATCH 08/16] Integrate Tizen 3.0 implementation to the current architecture Change-Id: I047e83efa083994d2a004e7b8e9a76ca6d7fbb16 Signed-off-by: Mu-Woong Lee --- packaging/context-sensor-recorder.spec | 2 + src/client/QueryResultListener.cpp | 57 ++++++++ src/client/QueryResultListener.h | 46 ++++++ src/client/sensor_recorder.cpp | 144 ++++++++++++++++--- src/server/CMakeLists.txt | 4 +- src/server/SensorDatabase.cpp | 75 ++++++++++ src/server/SensorDatabase.h | 41 ++++++ src/server/SensorRecorderClient.cpp | 94 +++++++++++++ src/server/SensorRecorderClient.h | 9 ++ src/server/SensorRecorderService.cpp | 18 ++- src/server/SensorTimer.cpp | 54 +++++++ src/server/SensorTimer.h | 43 ++++++ src/server/legacy/CreateProvider.cpp | 34 ----- src/server/legacy/Querier.cpp | 59 ++------ src/server/legacy/Querier.h | 28 ++-- .../{ClientInfo.cpp => RecorderClientInfo.cpp} | 107 +++++++------- .../legacy/{ClientInfo.h => RecorderClientInfo.h} | 19 +-- src/server/legacy/SensorLogger.cpp | 7 +- src/server/legacy/SensorLogger.h | 3 - src/server/legacy/SensorProvider.cpp | 156 +++++++++++++-------- src/server/legacy/SensorProvider.h | 39 ++++-- src/server/legacy/SensorProxy.cpp | 38 ++++- src/server/legacy/SensorProxy.h | 1 + src/server/legacy/TypesInternal.h | 43 +++++- src/server/legacy/UninstallMonitor.cpp | 17 ++- src/server/legacy/UninstallMonitor.h | 13 +- src/server/legacy/heartrate/HeartRate.cpp | 26 ++-- src/server/legacy/heartrate/HeartRate.h | 11 +- src/server/legacy/heartrate/HeartRateLogger.cpp | 41 +++--- src/server/legacy/heartrate/HeartRateLogger.h | 11 +- src/server/legacy/heartrate/HeartRateQuerier.cpp | 18 ++- src/server/legacy/heartrate/HeartRateQuerier.h | 8 +- src/server/legacy/pedometer/Pedometer.cpp | 26 ++-- src/server/legacy/pedometer/Pedometer.h | 11 +- src/server/legacy/pedometer/PedometerLogger.cpp | 6 +- src/server/legacy/pedometer/PedometerLogger.h | 1 + src/server/legacy/pedometer/PedometerQuerier.cpp | 29 ++-- src/server/legacy/pedometer/PedometerQuerier.h | 10 +- src/server/legacy/pressure/Pressure.cpp | 22 ++- src/server/legacy/pressure/Pressure.h | 9 +- src/server/legacy/pressure/PressureLogger.cpp | 12 +- src/server/legacy/pressure/PressureQuerier.cpp | 29 ++-- src/server/legacy/pressure/PressureQuerier.h | 10 +- src/server/legacy/sleep/Sleep.cpp | 27 ++-- src/server/legacy/sleep/Sleep.h | 11 +- src/server/legacy/sleep/SleepDetector.cpp | 2 +- src/server/legacy/sleep/SleepLogger.cpp | 8 +- src/server/legacy/sleep/SleepLogger.h | 1 + src/server/legacy/sleep/SleepMonitor.cpp | 2 +- src/server/legacy/sleep/SleepQuerier.cpp | 19 ++- src/server/legacy/sleep/SleepQuerier.h | 8 +- src/shared/SensorRecorderTypesPrivate.h | 27 +++- 52 files changed, 1094 insertions(+), 442 deletions(-) create mode 100644 src/client/QueryResultListener.cpp create mode 100644 src/client/QueryResultListener.h create mode 100644 src/server/SensorDatabase.cpp create mode 100644 src/server/SensorDatabase.h create mode 100644 src/server/SensorTimer.cpp create mode 100644 src/server/SensorTimer.h delete mode 100644 src/server/legacy/CreateProvider.cpp rename src/server/legacy/{ClientInfo.cpp => RecorderClientInfo.cpp} (54%) rename src/server/legacy/{ClientInfo.h => RecorderClientInfo.h} (78%) diff --git a/packaging/context-sensor-recorder.spec b/packaging/context-sensor-recorder.spec index 223ebe8..3babfc1 100644 --- a/packaging/context-sensor-recorder.spec +++ b/packaging/context-sensor-recorder.spec @@ -10,7 +10,9 @@ BuildRequires: cmake BuildRequires: pkgconfig(glib-2.0) BuildRequires: pkgconfig(gio-2.0) BuildRequires: pkgconfig(dlog) +BuildRequires: pkgconfig(sensor) BuildRequires: pkgconfig(capi-base-common) +BuildRequires: pkgconfig(capi-system-info) BuildRequires: pkgconfig(context-common-server) BuildRequires: pkgconfig(context-common-client) diff --git a/src/client/QueryResultListener.cpp b/src/client/QueryResultListener.cpp new file mode 100644 index 0000000..501856a --- /dev/null +++ b/src/client/QueryResultListener.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "QueryResultListener.h" + +using namespace ctx; + +QueryResultListener::QueryResultListener(const char* subject, ctx_sensor_rec_data_cb cb, void* userData) : + __subject(subject), + __callback(cb), + __userData(userData) +{ +} + +void QueryResultListener::onSuccess(const std::string& methodName, GVariant* param) +{ + const char* schema = NULL; + GVariant* vals = NULL; + g_variant_get(param, "(&sv)", &schema, &vals); + + auto records = Tuple::buildFrom(vals); + int remains = records.size(); + + ctx_sensor_rec_data_s data; + data.keys = util::tokenizeString(schema, ","); + + _D("%d records received", remains); + + for (auto& tuple : records) { + data.tuple = tuple; + if (!__callback(__subject.c_str(), &data, --remains, E_NONE, __userData)) + break; + } + + delete this; +} + +void QueryResultListener::onError(const std::string& methodName, int error) +{ + __callback(__subject.c_str(), NULL, 0, error, __userData); + + delete this; +} diff --git a/src/client/QueryResultListener.h b/src/client/QueryResultListener.h new file mode 100644 index 0000000..dd3a51f --- /dev/null +++ b/src/client/QueryResultListener.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SENSOR_RECORDER_QUERY_RESULT_LISTENER_H__ +#define __SENSOR_RECORDER_QUERY_RESULT_LISTENER_H__ + +#include +#include +#include + +namespace ctx { + + struct ctx_sensor_rec_data_s { + std::vector keys; + std::shared_ptr tuple; + }; + + class QueryResultListener : public IServiceResultListener { + public: + QueryResultListener(const char* subject, ctx_sensor_rec_data_cb cb, void* userData); + + void onSuccess(const std::string& methodName, GVariant* param); + void onError(const std::string& methodName, int error); + + private: + std::string __subject; + ctx_sensor_rec_data_cb __callback; + void* __userData; + }; + +} + +#endif diff --git a/src/client/sensor_recorder.cpp b/src/client/sensor_recorder.cpp index 8b46ad5..f57fae3 100644 --- a/src/client/sensor_recorder.cpp +++ b/src/client/sensor_recorder.cpp @@ -14,31 +14,70 @@ * limitations under the License. */ +#include #include #include #include -#include -#include +#include "QueryResultListener.h" -typedef std::map ctx_sensor_rec_option_t; -typedef std::map ctx_sensor_rec_query_t; +#define STR_BUFFER_SIZE 128 using namespace ctx; +typedef std::map ctx_sensor_rec_option_t; +typedef std::map ctx_sensor_rec_query_t; + +static ServiceProxy* __getServiceProxy() +{ + static ServiceProxy proxy(CTX_SENSOR_RECORDER); + return &proxy; +} + +static std::string __mapToJson(const std::map& input) +{ + std::string output("{"); + char buf[STR_BUFFER_SIZE]; + + for (auto& elem : input) { + snprintf(buf, STR_BUFFER_SIZE, "\"%s\":%lld,", elem.first.c_str(), elem.second); + output += buf; + } + + if (output.back() == ',') + output.back() = '}'; + else + output += "}"; + + return output; +} + EXPORT_API int ctx_sensor_rec_is_supported(const char* subject, bool *supported) { - *supported = false; - return E_SUPPORT; + IF_FAIL_RETURN(subject && supported, E_PARAM); + + int error = __getServiceProxy()->call(METHOD_IS_SUPPORTED, g_variant_new("(s)", subject)); + *supported = (error == E_NONE); + + if (error == E_SUPPORT) + error = E_NONE; + + return error; } EXPORT_API int ctx_sensor_rec_start(const char* subject, ctx_sensor_rec_option_h option) { - return E_SUPPORT; + IF_FAIL_RETURN(subject && option, E_PARAM); + + std::string optionStr = __mapToJson(*static_cast(option)); + GVariant* param = g_variant_new("(ss)", subject, optionStr.c_str()); + + return __getServiceProxy()->call(METHOD_START_REC, param); } EXPORT_API int ctx_sensor_rec_stop(const char* subject) { - return E_SUPPORT; + IF_FAIL_RETURN(subject, E_PARAM); + return __getServiceProxy()->call(METHOD_STOP_REC, g_variant_new("(s)", subject)); } EXPORT_API int ctx_sensor_rec_create_option(ctx_sensor_rec_option_h *option) @@ -62,10 +101,12 @@ EXPORT_API int ctx_sensor_rec_destroy_option(ctx_sensor_rec_option_h option) EXPORT_API int ctx_sensor_rec_option_set_int(ctx_sensor_rec_option_h option, const char* param, int value) { - IF_FAIL_RETURN(option, E_PARAM); + IF_FAIL_RETURN(option && param, E_PARAM); IF_FAIL_RETURN(STR_EQ(param, CTX_SENSOR_RECORDER_KEY_INTERVAL) || STR_EQ(param, CTX_SENSOR_RECORDER_KEY_RETENTION), E_PARAM); + (*static_cast(option))[param] = static_cast(value); + return E_NONE; } @@ -90,52 +131,115 @@ EXPORT_API int ctx_sensor_rec_destroy_query(ctx_sensor_rec_query_h query) EXPORT_API int ctx_sensor_rec_query_set_int(ctx_sensor_rec_query_h query, const char* param, int value) { - IF_FAIL_RETURN(query, E_PARAM); + IF_FAIL_RETURN(query && param, E_PARAM); IF_FAIL_RETURN(STR_EQ(param, CTX_SENSOR_RECORDER_KEY_ANCHOR) || STR_EQ(param, CTX_SENSOR_RECORDER_KEY_INTERVAL) || STR_EQ(param, CTX_SENSOR_RECORDER_KEY_START_TIME) || STR_EQ(param, CTX_SENSOR_RECORDER_KEY_END_TIME), E_PARAM); + (*static_cast(query))[param] = static_cast(value); + return E_NONE; } EXPORT_API int ctx_sensor_rec_query_set_time(ctx_sensor_rec_query_h query, const char* param, time_t t) { - IF_FAIL_RETURN(query, E_PARAM); + IF_FAIL_RETURN(query && param, E_PARAM); IF_FAIL_RETURN(STR_EQ(param, CTX_SENSOR_RECORDER_KEY_ANCHOR) || STR_EQ(param, CTX_SENSOR_RECORDER_KEY_START_TIME) || STR_EQ(param, CTX_SENSOR_RECORDER_KEY_END_TIME), E_PARAM); + (*static_cast(query))[param] = static_cast(t); + return E_NONE; } EXPORT_API int ctx_sensor_rec_read(const char* subject, ctx_sensor_rec_query_h query, ctx_sensor_rec_data_cb cb, void *user_data) { - IF_FAIL_RETURN(query, E_PARAM); - IF_FAIL_RETURN(cb, E_PARAM); + IF_FAIL_RETURN(subject && query && cb, E_PARAM); - return E_SUPPORT; + std::string queryStr = __mapToJson(*static_cast(query)); + GVariant* param = g_variant_new("(ss)", subject, queryStr.c_str()); + + QueryResultListener* listener = new QueryResultListener(subject, cb, user_data); + int error = __getServiceProxy()->call(METHOD_READ_REC, param, listener); + + if (error != E_NONE) + delete listener; + + return error; } EXPORT_API int ctx_sensor_rec_read_sync(const char* subject, ctx_sensor_rec_query_h query, ctx_sensor_rec_data_cb cb, void *user_data) { - IF_FAIL_RETURN(query, E_PARAM); - IF_FAIL_RETURN(cb, E_PARAM); + IF_FAIL_RETURN(subject && query && cb, E_PARAM); + + std::string queryStr = __mapToJson(*static_cast(query)); + GVariant* param = g_variant_new("(ss)", subject, queryStr.c_str()); + + GVariant* outParam = NULL; + int error = __getServiceProxy()->call(METHOD_READ_REC, param, &outParam); + IF_FAIL_RETURN(error == E_NONE, error); - return E_SUPPORT; + QueryResultListener* listener = new QueryResultListener(subject, cb, user_data); + listener->onSuccess(METHOD_READ_REC, outParam); + + g_variant_unref(outParam); + return E_NONE; +} + +static bool __getValueFromData(ctx_sensor_rec_data_s* data, const char* key, const char** value) +{ + for (unsigned int i = 0; i < data->keys.size(); ++i) { + if (data->keys[i] != key) continue; + return data->tuple->getAt(i, value); + } + return false; } EXPORT_API int ctx_sensor_rec_data_get_time(ctx_sensor_rec_data_h data, time_t *start_time, time_t *end_time) { - return E_SUPPORT; + IF_FAIL_RETURN(data && start_time && end_time, E_PARAM); + + const char* buf = NULL; + + if (__getValueFromData(static_cast(data), CTX_SENSOR_RECORDER_KEY_START_TIME, &buf)) + *start_time = static_cast(g_ascii_strtoll(buf, NULL, 10)); + else + return E_PARAM; + + if (__getValueFromData(static_cast(data), CTX_SENSOR_RECORDER_KEY_END_TIME, &buf)) + *end_time = static_cast(g_ascii_strtoll(buf, NULL, 10)); + else + return E_PARAM; + + return E_NONE; } EXPORT_API int ctx_sensor_rec_data_get_int(ctx_sensor_rec_data_h data, const char* key, int *value) { - return E_SUPPORT; + IF_FAIL_RETURN(data && key && value, E_PARAM); + + const char* buf = NULL; + + if (__getValueFromData(static_cast(data), key, &buf)) + *value = static_cast(g_ascii_strtoll(buf, NULL, 10)); + else + return E_PARAM; + + return E_NONE; } EXPORT_API int ctx_sensor_rec_data_get_double(ctx_sensor_rec_data_h data, const char* key, double *value) { - return E_SUPPORT; + IF_FAIL_RETURN(data && key && value, E_PARAM); + + const char* buf = NULL; + + if (__getValueFromData(static_cast(data), key, &buf)) + *value = g_ascii_strtod(buf, NULL); + else + return E_PARAM; + + return E_NONE; } diff --git a/src/server/CMakeLists.txt b/src/server/CMakeLists.txt index df2de9c..ee007d8 100644 --- a/src/server/CMakeLists.txt +++ b/src/server/CMakeLists.txt @@ -1,8 +1,8 @@ SET(target "${PROJECT_NAME}-server-genuine") -SET(DEPS "${DEPS} context-common-server") +SET(DEPS "${DEPS} context-common-server capi-system-info sensor") -FILE(GLOB SRCS *.cpp ../shared/*.cpp) +FILE(GLOB_RECURSE SRCS *.cpp ../shared/*.cpp) MESSAGE("Sources: ${SRCS}") INCLUDE(FindPkgConfig) diff --git a/src/server/SensorDatabase.cpp b/src/server/SensorDatabase.cpp new file mode 100644 index 0000000..b08ce19 --- /dev/null +++ b/src/server/SensorDatabase.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "SensorDatabase.h" + +using namespace ctx; + +Database* SensorDatabase::__userDatabase = NULL; + +SensorDatabase::SensorDatabase() +{ +} + +bool SensorDatabase::open(uid_t uid) +{ + if (isReady()) { + _W("Closing the current DB"); + close(); + } + + __userDatabase = new PlatformDatabase(BASE_PATH, uid); + + if (!__userDatabase->open()) { + _E("DB open failed"); + delete __userDatabase; + __userDatabase = NULL; + return false; + } + + _I("User DB opened"); + return true; +} + +void SensorDatabase::close() +{ + if (!__userDatabase) + return; + + __userDatabase->close(); + _I("User DB closed"); + + delete __userDatabase; + __userDatabase = NULL; +} + +bool SensorDatabase::isReady() +{ + return (__userDatabase != NULL); +} + +bool SensorDatabase::execute(const std::string& query, const std::string& columnTypes, std::vector* columnNames, std::vector>* queryResult) +{ + IF_FAIL_RETURN_TAG(isReady(), false, _W, "DB not ready"); + return __userDatabase->execute(query, columnTypes, columnNames, queryResult); +} + +bool SensorDatabase::execute(const std::string& query, std::vector>* queryResult) +{ + IF_FAIL_RETURN_TAG(isReady(), false, _W, "DB not ready"); + return __userDatabase->execute(query, queryResult); +} diff --git a/src/server/SensorDatabase.h b/src/server/SensorDatabase.h new file mode 100644 index 0000000..a61375c --- /dev/null +++ b/src/server/SensorDatabase.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SENSOR_RECORDER_DATABASE_H__ +#define __SENSOR_RECORDER_DATABASE_H__ + +#include +#include + +namespace ctx { + + class SensorDatabase { + public: + static bool open(uid_t uid); + static void close(); + static bool isReady(); + static bool execute(const std::string& query, const std::string& columnTypes, std::vector* columnNames, std::vector>* queryResult); + static bool execute(const std::string& query, std::vector>* queryResult); + + private: + SensorDatabase(); + + static Database* __userDatabase; + }; + +} + +#endif /* __SENSOR_RECORDER_DATABASE_H__ */ diff --git a/src/server/SensorRecorderClient.cpp b/src/server/SensorRecorderClient.cpp index b61d0b9..87eed76 100644 --- a/src/server/SensorRecorderClient.cpp +++ b/src/server/SensorRecorderClient.cpp @@ -16,7 +16,12 @@ #include #include +#include #include "SensorRecorderClient.h" +#include "legacy/SensorProvider.h" + +#define IDX_SUBJECT 0 +#define IDX_OPTION 1 using namespace ctx; @@ -31,9 +36,98 @@ SensorRecorderClient::~SensorRecorderClient() void SensorRecorderClient::onMethodCalled(MethodCall* methodCall) { + try { + __verifyUid(methodCall->getUid()); + std::string subject = __extractParameter(methodCall->getParam(), IDX_SUBJECT); + _D("%s(%s)", methodCall->getMethodName().c_str(), subject.c_str()); + + SensorProvider* provider = SensorProvider::getInstance(subject); + + if (methodCall->getMethodName() == METHOD_IS_SUPPORTED) { + methodCall->reply(E_NONE); + + } else if (methodCall->getMethodName() == METHOD_START_REC) { + __startRecording(*provider, *methodCall); + + } else if (methodCall->getMethodName() == METHOD_STOP_REC) { + __stopRecording(*provider, *methodCall); + + } else if (methodCall->getMethodName() == METHOD_READ_REC) { + __readRecords(*provider, *methodCall); + } + + } catch (const int error) { + _W("Catch: %s", CTX_ERROR_STR(error)); + methodCall->reply(error); + } + delete methodCall; } void SensorRecorderClient::onDisconnected() { } + +void SensorRecorderClient::__verifyUid(uid_t uid) +{ + if (!isSystemUid(uid) && uid != ServiceBase::getActiveUser()) { + _E("Invalid Uid: %u != %u (ActiveUser)", uid, ServiceBase::getActiveUser()); + throw static_cast(E_ACCESS); + } +} + +std::string SensorRecorderClient::__extractParameter(GVariant* param, unsigned int idx) +{ + const char* val = NULL; + g_variant_get_child(param, idx, "&s", &val); + + if (!val) + throw static_cast(E_PARAM); + + return val; +} + +void SensorRecorderClient::__startRecording(SensorProvider& provider, MethodCall& methodCall) +{ + if (!hasPrivilege(provider.getPrivilege())) + throw static_cast(E_ACCESS); + + // TODO: use the 'real' package id, instead of the smack label + std::string pkgId = getClientId(); + std::string option = __extractParameter(methodCall.getParam(), IDX_OPTION); + _D("Option: %s", option.c_str()); + + int error = provider.startRecording(pkgId, option); + methodCall.reply(error); +} + +void SensorRecorderClient::__stopRecording(SensorProvider& provider, MethodCall& methodCall) +{ + // TODO: use the 'real' package id, instead of the smack label + std::string pkgId = getClientId(); + + int error = provider.stopRecording(pkgId); + methodCall.reply(error); +} + +void SensorRecorderClient::__readRecords(SensorProvider& provider, MethodCall& methodCall) +{ + if (!hasPrivilege(provider.getPrivilege())) + throw static_cast(E_ACCESS); + + // TODO: use the 'real' package id, instead of the smack label + std::string pkgId = getClientId(); + std::string option = __extractParameter(methodCall.getParam(), IDX_OPTION); + _D("Option: %s", option.c_str()); + + std::string projection; + std::vector> tuples; + + int error = provider.readRecords(option, &projection, &tuples); + if (error != E_NONE) + throw error; + if (tuples.empty()) + throw static_cast(E_NO_DATA); + + methodCall.reply(g_variant_new("(sv)", projection.c_str(), Tuple::toGVariant(tuples))); +} diff --git a/src/server/SensorRecorderClient.h b/src/server/SensorRecorderClient.h index 210d57f..45cc9fe 100644 --- a/src/server/SensorRecorderClient.h +++ b/src/server/SensorRecorderClient.h @@ -21,6 +21,8 @@ namespace ctx { + class SensorProvider; + class SensorRecorderClient : public ClientBase { public: SensorRecorderClient(ServiceBase* hostService, const std::string& busName); @@ -28,6 +30,13 @@ namespace ctx { void onMethodCalled(MethodCall* methodCall); void onDisconnected(); + + private: + void __verifyUid(uid_t uid); + std::string __extractParameter(GVariant* param, unsigned int idx); + void __startRecording(SensorProvider& provider, MethodCall& methodCall); + void __stopRecording(SensorProvider& provider, MethodCall& methodCall); + void __readRecords(SensorProvider& provider, MethodCall& methodCall); }; } diff --git a/src/server/SensorRecorderService.cpp b/src/server/SensorRecorderService.cpp index bc68956..b9ddf11 100644 --- a/src/server/SensorRecorderService.cpp +++ b/src/server/SensorRecorderService.cpp @@ -17,6 +17,10 @@ #include #include #include "SensorRecorderClient.h" +#include "SensorDatabase.h" +#include "SensorTimer.h" +#include "legacy/SensorProvider.h" +#include "legacy/RecorderClientInfo.h" using namespace ctx; @@ -36,15 +40,25 @@ bool SensorRecorderService::isUserService() bool SensorRecorderService::prepare() { - /* Service-specific initialization tasks */ + RecorderClientInfo::setHostService(this); + + if (!SensorDatabase::open(getActiveUser())) + return false; + + SensorTimer::init(this); + SensorProvider::init(); + return true; } void SensorRecorderService::cleanup() { + SensorProvider::release(); + SensorTimer::release(); + SensorDatabase::close(); } ClientBase* SensorRecorderService::createClient(const std::string& busName) { - return new(std::nothrow) SensorRecorderClient(this, busName); + return new SensorRecorderClient(this, busName); } diff --git a/src/server/SensorTimer.cpp b/src/server/SensorTimer.cpp new file mode 100644 index 0000000..62f7da9 --- /dev/null +++ b/src/server/SensorTimer.cpp @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "SensorTimer.h" + +using namespace ctx; + +Timer* SensorTimer::__timer = NULL; + +SensorTimer::SensorTimer() +{ +} + +void SensorTimer::init(ServiceBase* hostService) +{ + __timer = new Timer(hostService); +} + +void SensorTimer::release() +{ + delete __timer; +} + +unsigned int SensorTimer::addIdle(GSourceFunc callback, gpointer userData) +{ + return __timer->addIdle(callback, userData); +} + +unsigned int SensorTimer::addAlarm(unsigned int intervalMin, ITimerListener* listener) +{ + return __timer->addAlarm(intervalMin, listener, NULL); +} + +void SensorTimer::cancel(unsigned int timerId) +{ + __timer->cancel(timerId); +} diff --git a/src/server/SensorTimer.h b/src/server/SensorTimer.h new file mode 100644 index 0000000..ba79daa --- /dev/null +++ b/src/server/SensorTimer.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2017 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __SENSOR_RECORDER_TIMER_H__ +#define __SENSOR_RECORDER_TIMER_H__ + +namespace ctx { + + class ServiceBase; + class Timer; + class ITimerListener; + + class SensorTimer { + public: + static void init(ServiceBase* hostService); + static void release(); + + static unsigned int addIdle(GSourceFunc callback, gpointer userData); + static unsigned int addAlarm(unsigned int intervalMin, ITimerListener* listener); + static void cancel(unsigned int timerId); + + private: + SensorTimer(); + + static Timer* __timer; + }; + +} + +#endif /* __SENSOR_RECORDER_TIMER_H__ */ diff --git a/src/server/legacy/CreateProvider.cpp b/src/server/legacy/CreateProvider.cpp deleted file mode 100644 index 73e9f19..0000000 --- a/src/server/legacy/CreateProvider.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include "pedometer/Pedometer.h" -#include "pressure/Pressure.h" -#include "sleep/Sleep.h" -#include "heartrate/HeartRate.h" - -using namespace ctx; - -extern "C" SO_EXPORT ContextProvider* CreateProvider(const char *subject) -{ - ADD_PROVIDER(SUBJ_SENSOR_PEDOMETER, PedometerProvider); - ADD_PROVIDER(SUBJ_SENSOR_PRESSURE, PressureProvider); - ADD_PROVIDER(SUBJ_SENSOR_SLEEP_MONITOR, SleepProvider); - ADD_PROVIDER(SUBJ_SENSOR_HEART_RATE, HeartRateProvider); - - return NULL; -} diff --git a/src/server/legacy/Querier.cpp b/src/server/legacy/Querier.cpp index feec0b3..37f16e8 100644 --- a/src/server/legacy/Querier.cpp +++ b/src/server/legacy/Querier.cpp @@ -14,15 +14,13 @@ * limitations under the License. */ -#include -#include +#include +#include "../SensorDatabase.h" #include "Querier.h" using namespace ctx; -Querier::Querier(ContextProvider *provider, Json option) : - __provider(provider), - __option(option) +Querier::Querier() { } @@ -30,56 +28,29 @@ Querier::~Querier() { } -int Querier::query(const char *sql) +std::string Querier::getProjection() { - return __dbMgr.execute(0, sql, this) ? ERR_NONE : ERR_OPERATION_FAILED; + return ""; } -int Querier::queryRaw(int startTime, int endTime) +int Querier::query(const char *sql, std::vector>* tuples) { - return ERR_INVALID_PARAMETER; + bool ret = SensorDatabase::execute(sql, tuples); + return ret ? E_NONE : E_FAILED; } -int Querier::query(int startTime, int endTime) +int Querier::queryRaw(int startTime, int endTime, std::vector>* tuples) { - return ERR_INVALID_PARAMETER; + return E_PARAM; } -int Querier::query(int startTime, int endTime, int anchor, int interval) -{ - _D("Ignore anchor & interval"); - return query(startTime, endTime); -} - -void Querier::onTableCreated(unsigned int queryId, int error) -{ -} - -void Querier::onInserted(unsigned int queryId, int error, int64_t rowId) +int Querier::query(int startTime, int endTime, std::vector>* tuples) { + return E_PARAM; } -void Querier::onExecuted(unsigned int queryId, int error, std::vector& records) +int Querier::query(int startTime, int endTime, int anchor, int interval, std::vector>* tuples) { - Json response; - __convertToResponse(records, response); - __provider->replyToRead(__option, error, response); - delete this; -} - -void Querier::__convertToResponse(std::vector &sqlResult, Json &response) -{ - std::list keys; - std::string val; - - response.set(NULL, KEY_RESULT_SIZE, static_cast(sqlResult.size())); - - for (Json &tuple : sqlResult) { - tuple.getKeys(&keys); - for (std::string &key : keys) { - tuple.get(NULL, key.c_str(), &val); - response.append(NULL, key.c_str(), val); - } - keys.clear(); - } + _D("Ignore anchor & interval"); + return query(startTime, endTime, tuples); } diff --git a/src/server/legacy/Querier.h b/src/server/legacy/Querier.h index 0eed203..354681d 100644 --- a/src/server/legacy/Querier.h +++ b/src/server/legacy/Querier.h @@ -17,32 +17,24 @@ #ifndef __CONTEXT_QUERIER_H__ #define __CONTEXT_QUERIER_H__ -#include -#include +#include +#include namespace ctx { - class Querier : public IDatabaseListener { + class Querier { public: - Querier(ContextProvider *provider, Json option); + Querier(); virtual ~Querier(); - virtual int queryRaw(int startTime, int endTime); - virtual int query(int startTime, int endTime); - virtual int query(int startTime, int endTime, int anchor, int interval); + virtual std::string getProjection(); - protected: - int query(const char *sql); - void onTableCreated(unsigned int queryId, int error); - void onInserted(unsigned int queryId, int error, int64_t rowId); - void onExecuted(unsigned int queryId, int error, std::vector& records); - - private: - void __convertToResponse(std::vector &sqlResult, Json &response); + virtual int queryRaw(int startTime, int endTime, std::vector>* tuples); + virtual int query(int startTime, int endTime, std::vector>* tuples); + virtual int query(int startTime, int endTime, int anchor, int interval, std::vector>* tuples); - DatabaseManager __dbMgr; - ContextProvider *__provider; - Json __option; + protected: + int query(const char *sql, std::vector>* tuples); }; } diff --git a/src/server/legacy/ClientInfo.cpp b/src/server/legacy/RecorderClientInfo.cpp similarity index 54% rename from src/server/legacy/ClientInfo.cpp rename to src/server/legacy/RecorderClientInfo.cpp index 6c5955d..0ab8619 100644 --- a/src/server/legacy/ClientInfo.cpp +++ b/src/server/legacy/RecorderClientInfo.cpp @@ -15,30 +15,26 @@ */ #include -#include -#include +#include +#include "../SensorDatabase.h" #include "TypesInternal.h" #include "SensorProvider.h" -#include "ClientInfo.h" +#include "RecorderClientInfo.h" using namespace ctx; -unsigned int ClientInfo::__refCnt = 0; -DatabaseManager *ClientInfo::__dbMgr = NULL; -UninstallMonitor *ClientInfo::__uninstallMonitor = NULL; +unsigned int RecorderClientInfo::__refCnt = 0; +UninstallMonitor *RecorderClientInfo::__uninstallMonitor = NULL; +SensorRecorderService* RecorderClientInfo::__hostService = NULL; -ClientInfo::ClientInfo() +RecorderClientInfo::RecorderClientInfo() { if (++__refCnt != 1) return; - __uninstallMonitor = new(std::nothrow) UninstallMonitor(); - IF_FAIL_VOID_TAG(__uninstallMonitor, _E, "Memory allocation failed"); + __uninstallMonitor = new UninstallMonitor(__hostService); - __dbMgr = new(std::nothrow) DatabaseManager(); - IF_FAIL_VOID_TAG(__dbMgr, _E, "Memory allocation failed"); - - bool ret = __dbMgr->executeSync( + bool ret = SensorDatabase::execute( "CREATE TABLE IF NOT EXISTS " CLIENT_INFO " (" \ KEY_SUBJECT " TEXT NOT NULL," \ KEY_PKG_ID " TEXT NOT NULL," \ @@ -50,121 +46,110 @@ ClientInfo::ClientInfo() IF_FAIL_VOID_TAG(ret, _E, "Table creation failed"); } -ClientInfo::~ClientInfo() +RecorderClientInfo::~RecorderClientInfo() { if (--__refCnt != 0) return; - delete __dbMgr; - __dbMgr = NULL; - delete __uninstallMonitor; __uninstallMonitor = NULL; } -int ClientInfo::get(std::string subject, std::string pkgId, Json& option) +int RecorderClientInfo::get(std::string subject, std::string pkgId, Json& option) { - IF_FAIL_RETURN_TAG(__dbMgr, ERR_OPERATION_FAILED, _W, "DB not initialized"); - bool ret; std::string optStr; - std::vector records; + std::vector> tuples; + char *query = sqlite3_mprintf( "SELECT " KEY_OPTION " FROM " CLIENT_INFO " WHERE " \ KEY_SUBJECT "='%q' AND " KEY_PKG_ID "='%q'", subject.c_str(), pkgId.c_str()); - ret = __dbMgr->executeSync(query, &records); + ret = SensorDatabase::execute(query, &tuples); sqlite3_free(query); - IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); - IF_FAIL_RETURN(!records.empty(), ERR_NO_DATA); - IF_FAIL_RETURN(records[0].get(NULL, KEY_OPTION, &optStr), ERR_OPERATION_FAILED); + IF_FAIL_RETURN(ret, E_FAILED); + IF_FAIL_RETURN(!tuples.empty(), E_NO_DATA); + tuples[0]->getAt(0, &optStr); option = optStr; - return ERR_NONE; + return E_NONE; } -int ClientInfo::get(std::string subject, std::vector& options) +int RecorderClientInfo::get(std::string subject, std::vector& options) { - IF_FAIL_RETURN_TAG(__dbMgr, ERR_OPERATION_FAILED, _W, "DB not initialized"); - bool ret; std::string optStr; - std::vector records; + std::vector> tuples; + char *query = sqlite3_mprintf( "SELECT " KEY_OPTION " FROM " CLIENT_INFO " WHERE " \ KEY_SUBJECT "='%q'", subject.c_str()); - ret = __dbMgr->executeSync(query, &records); + ret = SensorDatabase::execute(query, &tuples); sqlite3_free(query); - IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); - IF_FAIL_RETURN(!records.empty(), ERR_NO_DATA); + IF_FAIL_RETURN(ret, E_FAILED); + IF_FAIL_RETURN(!tuples.empty(), E_NO_DATA); - for (Json& jObj : records) { - if (!jObj.get(NULL, KEY_OPTION, &optStr)) - continue; + for (auto& tuple : tuples) { + tuple->getAt(0, &optStr); options.push_back(Json(optStr)); } - return ERR_NONE; + return E_NONE; } -bool ClientInfo::exist(std::string subject) +bool RecorderClientInfo::exist(std::string subject) { - IF_FAIL_RETURN_TAG(__dbMgr, ERR_OPERATION_FAILED, _W, "DB not initialized"); - bool ret; - std::vector records; + std::vector> tuples; + char *query = sqlite3_mprintf( "SELECT " KEY_PKG_ID " FROM " CLIENT_INFO " WHERE " \ KEY_SUBJECT "='%q' LIMIT 1", subject.c_str()); - ret = __dbMgr->executeSync(query, &records); + ret = SensorDatabase::execute(query, &tuples); sqlite3_free(query); IF_FAIL_RETURN(ret, false); - IF_FAIL_RETURN(!records.empty(), false); + IF_FAIL_RETURN(!tuples.empty(), false); return true; } -bool ClientInfo::set(std::string subject, std::string pkgId, Json option, int retentionPeriod) +bool RecorderClientInfo::set(std::string subject, std::string pkgId, Json option, int retentionPeriod) { - IF_FAIL_RETURN_TAG(__dbMgr, false, _W, "DB not initialized"); - bool ret; char *query = sqlite3_mprintf( "INSERT INTO " CLIENT_INFO " VALUES ('%q', '%q', '%q', %d)", subject.c_str(), pkgId.c_str(), option.str().c_str(), retentionPeriod); - ret = __dbMgr->executeSync(query, NULL); + ret = SensorDatabase::execute(query, NULL); sqlite3_free(query); return ret; } -bool ClientInfo::remove(std::string subject, std::string pkgId) +bool RecorderClientInfo::remove(std::string subject, std::string pkgId) { - IF_FAIL_RETURN_TAG(__dbMgr, false, _W, "DB not initialized"); - bool ret; char *query = sqlite3_mprintf( "DELETE FROM " CLIENT_INFO " WHERE " \ KEY_SUBJECT "='%q' AND " KEY_PKG_ID "='%q'", subject.c_str(), pkgId.c_str()); - ret = __dbMgr->executeSync(query, NULL); + ret = SensorDatabase::execute(query, NULL); sqlite3_free(query); return ret; } -void ClientInfo::getParam(std::vector &options, const char *key, float *min, float *max) +void RecorderClientInfo::getParam(std::vector &options, const char *key, float *min, float *max) { double val; @@ -178,26 +163,28 @@ void ClientInfo::getParam(std::vector &options, const char *key, float *mi } } -void ClientInfo::purgeClient(std::string pkgId) +void RecorderClientInfo::purgeClient(std::string pkgId) { - IF_FAIL_VOID_TAG(__dbMgr, _W, "DB not initialized"); - bool ret; std::string subject; - std::vector records; + std::vector> tuples; char *query = sqlite3_mprintf( "SELECT " KEY_SUBJECT " FROM " CLIENT_INFO " WHERE " KEY_PKG_ID "='%q'", pkgId.c_str()); - ret = __dbMgr->executeSync(query, &records); + ret = SensorDatabase::execute(query, &tuples); sqlite3_free(query); IF_FAIL_VOID(ret); - for (Json& jObj : records) { - if (!jObj.get(NULL, KEY_SUBJECT, &subject)) - continue; + for (auto& tuple : tuples) { + tuple->getAt(0, &subject); _I("Stop recording '%s' for '%s'", subject.c_str(), pkgId.c_str()); SensorProvider::removeClient(subject, pkgId); } } + +void RecorderClientInfo::setHostService(SensorRecorderService* hostService) +{ + __hostService = hostService; +} diff --git a/src/server/legacy/ClientInfo.h b/src/server/legacy/RecorderClientInfo.h similarity index 78% rename from src/server/legacy/ClientInfo.h rename to src/server/legacy/RecorderClientInfo.h index e3ee643..9a8bbc9 100644 --- a/src/server/legacy/ClientInfo.h +++ b/src/server/legacy/RecorderClientInfo.h @@ -14,21 +14,23 @@ * limitations under the License. */ -#ifndef __CONTEXT_CLIENT_INFO_H__ -#define __CONTEXT_CLIENT_INFO_H__ +#ifndef __SENSOR_RECORDER_CLIENT_INFO_H__ +#define __SENSOR_RECORDER_CLIENT_INFO_H__ #include #include #include -#include +#include #include "UninstallMonitor.h" namespace ctx { - class ClientInfo { + class SensorRecorderService; + + class RecorderClientInfo { public: - ClientInfo(); - ~ClientInfo(); + RecorderClientInfo(); + ~RecorderClientInfo(); int get(std::string subject, std::string pkgId, Json& option); int get(std::string subject, std::vector& options); @@ -40,12 +42,13 @@ namespace ctx { void getParam(std::vector& options, const char *key, float *min, float *max); static void purgeClient(std::string pkgId); + static void setHostService(SensorRecorderService* hostService); private: static unsigned int __refCnt; - static DatabaseManager *__dbMgr; static UninstallMonitor *__uninstallMonitor; + static SensorRecorderService* __hostService; }; } -#endif /* _CONTEXT_CLIENT_INFO_H_ */ +#endif diff --git a/src/server/legacy/SensorLogger.cpp b/src/server/legacy/SensorLogger.cpp index 6bc92ea..c2d513d 100644 --- a/src/server/legacy/SensorLogger.cpp +++ b/src/server/legacy/SensorLogger.cpp @@ -15,7 +15,8 @@ */ #include -#include +#include +#include "../SensorDatabase.h" #include "TypesInternal.h" #include "TimeUtil.h" #include "SensorLogger.h" @@ -37,7 +38,7 @@ void SensorLogger::flushCache(bool force) bool SensorLogger::executeQuery(const char *query) { - return __dbMgr.execute(0, query, NULL); + return SensorDatabase::execute(query, NULL); } void SensorLogger::removeExpired(const char *subject, const char *tableName, const char *timeKey) @@ -53,7 +54,7 @@ void SensorLogger::removeExpired(const char *subject, const char *tableName, con " WHERE " KEY_SUBJECT "='%s')", tableName, timeKey, timestamp, subject); - __dbMgr.execute(0, query, NULL); + SensorDatabase::execute(query, NULL); sqlite3_free(query); __lastRemovalTime = timestamp; diff --git a/src/server/legacy/SensorLogger.h b/src/server/legacy/SensorLogger.h index 76d7ec6..879cd62 100644 --- a/src/server/legacy/SensorLogger.h +++ b/src/server/legacy/SensorLogger.h @@ -17,8 +17,6 @@ #ifndef __CONTEXT_SENSOR_LOGGER_H__ #define __CONTEXT_SENSOR_LOGGER_H__ -#include - namespace ctx { class SensorLogger { @@ -37,7 +35,6 @@ namespace ctx { private: uint64_t __lastRemovalTime; - DatabaseManager __dbMgr; }; } diff --git a/src/server/legacy/SensorProvider.cpp b/src/server/legacy/SensorProvider.cpp index 47d5269..2103376 100644 --- a/src/server/legacy/SensorProvider.cpp +++ b/src/server/legacy/SensorProvider.cpp @@ -16,38 +16,89 @@ #include #include -#include +#include +#include #include "TypesInternal.h" #include "SensorProvider.h" +#include "heartrate/HeartRate.h" +#include "pedometer/Pedometer.h" +#include "pressure/Pressure.h" +#include "sleep/Sleep.h" + +#define CREATE_PROVIDER(PROVIDERTYPE) \ + do { \ + SensorProvider* prvd = new PROVIDERTYPE(); \ + if (prvd->isSupported()) { \ + __providerMap[prvd->getSubject()] = prvd; \ + } else { \ + delete prvd; \ + } \ + } while (false) + using namespace ctx; std::map SensorProvider::__providerMap; SensorProvider::SensorProvider(const char *subject) : - ContextProvider(subject), - sensorLogger(NULL) + __subject(subject) { - __providerMap[subject] = this; } SensorProvider::~SensorProvider() { - __providerMap.erase(getSubject()); - delete sensorLogger; } -int SensorProvider::subscribe(Json option, Json *requestResult) +void SensorProvider::init() +{ + CREATE_PROVIDER(HeartRateProvider); + CREATE_PROVIDER(PedometerProvider); + CREATE_PROVIDER(PressureProvider); + CREATE_PROVIDER(SleepProvider); +} + +void SensorProvider::release() +{ + for (auto& prvd : __providerMap) { + delete prvd.second; + } + __providerMap.clear(); +} + +SensorProvider* SensorProvider::getInstance(const std::string& subject) { - return ERR_NONE; + auto it = __providerMap.find(subject); + + if (it == __providerMap.end()) + throw static_cast(E_SUPPORT); + + return it->second; } -int SensorProvider::unsubscribe(Json option) +const char* SensorProvider::getSubject() { - return ERR_NONE; + return __subject.c_str(); } -int SensorProvider::read(Json option, Json *requestResult) +bool SensorProvider::isSupported() +{ + return false; +} + +bool SensorProvider::getSystemInfo(const char* key) +{ + bool supported = false; + int ret = system_info_get_platform_bool(key, &supported); + IF_FAIL_RETURN_TAG(ret == SYSTEM_INFO_ERROR_NONE, false, _E, "system_info_get_platform_bool() failed"); + return supported; +} + +const char* SensorProvider::getPrivilege() +{ + return NULL; +} + +int SensorProvider::readRecords(Json option, std::string* projection, std::vector>* tuples) { int endTime = static_cast(time(NULL)) + 1; int startTime = endTime - DEFAULT_QUERY_PERIOD - 1; @@ -55,19 +106,19 @@ int SensorProvider::read(Json option, Json *requestResult) int interval = -1; if (option.get(NULL, KEY_START_TIME, &startTime)) - IF_FAIL_RETURN(startTime >= 0, ERR_INVALID_PARAMETER); + IF_FAIL_RETURN(startTime >= 0, E_PARAM); if (option.get(NULL, KEY_END_TIME, &endTime)) - IF_FAIL_RETURN(endTime >= 0, ERR_INVALID_PARAMETER); + IF_FAIL_RETURN(endTime >= 0, E_PARAM); if (option.get(NULL, KEY_ANCHOR, &anchor)) - IF_FAIL_RETURN(anchor >= 0, ERR_INVALID_PARAMETER); + IF_FAIL_RETURN(anchor >= 0, E_PARAM); if (option.get(NULL, KEY_INTERVAL, &interval)) - IF_FAIL_RETURN(interval >= 0, ERR_INVALID_PARAMETER); + IF_FAIL_RETURN(interval >= 0, E_PARAM); if (endTime >= 0 && startTime >= endTime) - return ERR_INVALID_PARAMETER; + return E_PARAM; if (interval > 0 && anchor < 0) anchor = endTime; @@ -75,54 +126,43 @@ int SensorProvider::read(Json option, Json *requestResult) if (anchor >= 0 && interval < 0) interval = static_cast(ceil(static_cast(endTime - startTime) / SECONDS_PER_MINUTE)); - int ret; - Querier *querier = getQuerier(option); - IF_FAIL_RETURN(querier, ERR_OPERATION_FAILED); + int ret = E_FAILED; - sensorLogger->flushCache(true); + getLogger()->flushCache(true); + *projection = getQuerier()->getProjection(); if (interval == 0) - ret = querier->queryRaw(startTime, endTime); + ret = getQuerier()->queryRaw(startTime, endTime, tuples); else if (interval > 0) - ret = querier->query(startTime, endTime, anchor, interval * SECONDS_PER_MINUTE); + ret = getQuerier()->query(startTime, endTime, anchor, interval * SECONDS_PER_MINUTE, tuples); else - ret = querier->query(startTime, endTime); - - if (ret != ERR_NONE) - delete querier; + ret = getQuerier()->query(startTime, endTime, tuples); return ret; } -int SensorProvider::write(Json data, Json *requestResult) +int SensorProvider::startRecording(const std::string& pkgId, Json option) { - IF_FAIL_RETURN(sensorLogger, ERR_OPERATION_FAILED); - - std::string operation; - std::string pkgId; - Json option; int retentionPeriod = DEFAULT_RETENTION; - _J("Data", data); - - IF_FAIL_RETURN(data.get(NULL, KEY_OPERATION, &operation), ERR_INVALID_PARAMETER); - IF_FAIL_RETURN(data.get(NULL, KEY_CLIENT_PKG_ID, &pkgId), ERR_INVALID_PARAMETER); - - data.get(NULL, KEY_OPTION, &option); + _D("PkgId: %s", pkgId.c_str()); + _J("Option", option); if (option.get(NULL, KEY_RETENTION, &retentionPeriod)) { retentionPeriod *= SECONDS_PER_HOUR; option.remove(NULL, KEY_RETENTION); } - IF_FAIL_RETURN(verifyOption(option), ERR_INVALID_PARAMETER); + IF_FAIL_RETURN(verifyOption(option), E_PARAM); - if (operation == VAL_START) - return __addClient(pkgId, retentionPeriod, option); - else if (operation == VAL_STOP) - return __removeClient(pkgId); + return __addClient(pkgId, retentionPeriod, option); +} + +int SensorProvider::stopRecording(const std::string& pkgId) +{ + _D("PkgId: %s", pkgId.c_str()); - return ERR_NOT_SUPPORTED; + return __removeClient(pkgId); } bool SensorProvider::verifyOption(Json option) @@ -138,21 +178,21 @@ int SensorProvider::__addClient(std::string pkgId, int retentionPeriod, Json opt int ret; /* Validate the retention period */ - IF_FAIL_RETURN(retentionPeriod > 0 && retentionPeriod <= MAX_RETENTION_PERIOD, ERR_INVALID_PARAMETER); + IF_FAIL_RETURN(retentionPeriod > 0 && retentionPeriod <= MAX_RETENTION_PERIOD, E_PARAM); /* Check if the app already started Sensor recording */ ret = __clientInfo.get(getSubject(), pkgId, tmp); - IF_FAIL_RETURN(ret != ERR_NONE, ERR_ALREADY_STARTED); - IF_FAIL_RETURN(ret == ERR_NO_DATA, ERR_OPERATION_FAILED); + IF_FAIL_RETURN(ret != E_NONE, E_STARTED); + IF_FAIL_RETURN(ret == E_NO_DATA, E_FAILED); /* Store the app's request */ if (!__clientInfo.set(getSubject(), pkgId, option, retentionPeriod)) - return ERR_OPERATION_FAILED; + return E_FAILED; /* If not listening the sensor yet, start */ - sensorLogger->start(); + getLogger()->start(); - return ERR_NONE; + return E_NONE; } int SensorProvider::__removeClient(std::string pkgId) @@ -161,24 +201,24 @@ int SensorProvider::__removeClient(std::string pkgId) int ret; /* Remove the app's request first */ - IF_FAIL_RETURN(__clientInfo.remove(getSubject(), pkgId), ERR_OPERATION_FAILED); + IF_FAIL_RETURN(__clientInfo.remove(getSubject(), pkgId), E_FAILED); /* Check if there is no client anymore */ ret = __clientInfo.get(getSubject(), options); - if (ret == ERR_NONE) { + if (ret == E_NONE) { /* Still, one or more clients exist */ /* If necessary, the logger restarts its logging logic with updated parameters */ - sensorLogger->start(); - return ERR_NONE; + getLogger()->start(); + return E_NONE; - } else if (ret == ERR_NO_DATA) { + } else if (ret == E_NO_DATA) { /* No client */ - sensorLogger->stop(); - return ERR_NONE; + getLogger()->stop(); + return E_NONE; } - return ERR_OPERATION_FAILED; + return E_FAILED; } void SensorProvider::removeClient(std::string subject, std::string pkgId) diff --git a/src/server/legacy/SensorProvider.h b/src/server/legacy/SensorProvider.h index 5b806a0..245ec31 100644 --- a/src/server/legacy/SensorProvider.h +++ b/src/server/legacy/SensorProvider.h @@ -17,37 +17,52 @@ #ifndef __CONTEXT_SENSOR_PROVIDER_H__ #define __CONTEXT_SENSOR_PROVIDER_H__ +#include #include -#include -#include "ClientInfo.h" +#include +#include +#include "RecorderClientInfo.h" #include "SensorLogger.h" #include "Querier.h" namespace ctx { - class SensorProvider : public ContextProvider { + class SensorRecorderService; + + class SensorProvider { public: - SensorProvider(const char *subject); virtual ~SensorProvider(); - virtual int subscribe(Json option, Json *requestResult); - virtual int unsubscribe(Json option); - virtual int read(Json option, Json *requestResult); - virtual int write(Json data, Json *requestResult); + const char* getSubject(); + + int readRecords(Json option, std::string* projection, std::vector>* tuples); + int startRecording(const std::string& pkgId, Json option); + int stopRecording(const std::string& pkgId); + + virtual bool isSupported(); + virtual const char* getPrivilege(); + + static void init(); + static void release(); + static SensorProvider* getInstance(const std::string& subject); static void removeClient(std::string subject, std::string pkgId); protected: - virtual Querier* getQuerier(Json option) = 0; - virtual bool verifyOption(Json option); + SensorProvider(const char *subject); - SensorLogger *sensorLogger; + bool getSystemInfo(const char* key); + + virtual SensorLogger* getLogger() = 0; + virtual Querier* getQuerier() = 0; + virtual bool verifyOption(Json option); private: int __addClient(std::string pkgId, int retentionPeriod, Json option); int __removeClient(std::string pkgId); - ClientInfo __clientInfo; + std::string __subject; + RecorderClientInfo __clientInfo; static std::map __providerMap; }; diff --git a/src/server/legacy/SensorProxy.cpp b/src/server/legacy/SensorProxy.cpp index 98dd0a6..53afe65 100644 --- a/src/server/legacy/SensorProxy.cpp +++ b/src/server/legacy/SensorProxy.cpp @@ -15,13 +15,19 @@ * */ -#include +#include +#include "../SensorTimer.h" #include "SensorProxy.h" #define SENSOR_EVENT(X) (((int)(X) << 16) | 0x01) using namespace ctx; +struct SensorEvent { + SensorProxy* listener; + sensor_data_t* data; +}; + SensorProxy::SensorProxy() : sensorHandle(-1), sensorType(UNKNOWN_SENSOR), @@ -119,6 +125,32 @@ bool SensorProxy::isSupported(sensor_type_t type) void SensorProxy::__eventCb(sensor_t sensor, unsigned int eventType, sensor_data_t *eventData, void *cbData) { - SensorProxy *instance = static_cast(cbData); - instance->onEvent(eventData); + SensorEvent* sensorEvent = new SensorEvent; + sensorEvent->listener = static_cast(cbData); + + if (sensorEvent->listener->sensorType == HUMAN_PEDOMETER_SENSOR) { + sensorEvent->data = static_cast(g_memdup(eventData, sizeof(sensor_pedometer_data_t))); + } else { + sensorEvent->data = static_cast(g_memdup(eventData, sizeof(sensor_data_t))); + } + + if (!sensorEvent->data) { + _E_ALLOC; + delete sensorEvent; + return; + } + + SensorTimer::addIdle(__threadSwitcher, sensorEvent); +} + +gboolean SensorProxy::__threadSwitcher(gpointer data) +{ + SensorEvent* sensorEvent = static_cast(data); + + sensorEvent->listener->onEvent(sensorEvent->data); + + g_free(sensorEvent->data); + delete sensorEvent; + + return G_SOURCE_REMOVE; } diff --git a/src/server/legacy/SensorProxy.h b/src/server/legacy/SensorProxy.h index 7ae1c87..e2e4af5 100644 --- a/src/server/legacy/SensorProxy.h +++ b/src/server/legacy/SensorProxy.h @@ -52,6 +52,7 @@ namespace ctx { private: static void __eventCb(sensor_t sensor, unsigned int eventType, sensor_data_t *eventData, void *cbData); + static gboolean __threadSwitcher(gpointer data); }; } diff --git a/src/server/legacy/TypesInternal.h b/src/server/legacy/TypesInternal.h index 0bd3cb5..5a8cbaf 100644 --- a/src/server/legacy/TypesInternal.h +++ b/src/server/legacy/TypesInternal.h @@ -26,7 +26,7 @@ #define HEART_RATE_RECORD "SensorHeartRateRecord" /* Privileges */ -#define PRIV_HEALTHINFO "healthinfo" +#define PRIV_HEALTHINFO "http://tizen.org/privilege/healthinfo" /* Constants */ #define SECONDS_PER_MINUTE 60 @@ -43,4 +43,45 @@ /* SQL Helper */ #define TIME_QUANTIZER(key) "ROUND((CAST(" key " AS REAL) - %llu)/CAST(%llu AS REAL) + 0.5)" +/* Sensor Subjects */ +#define SUBJ_SENSOR "sensor/" +#define SUBJ_SENSOR_HEART_RATE SUBJ_SENSOR "heart_rate" +#define SUBJ_SENSOR_PEDOMETER SUBJ_SENSOR "pedometer" +#define SUBJ_SENSOR_SLEEP_MONITOR SUBJ_SENSOR "sleep_monitor" +#define SUBJ_SENSOR_PRESSURE SUBJ_SENSOR "pressure" +#define SUBJ_SENSOR_EXERCISE SUBJ_SENSOR "exercise" + +/* Keys */ +#define KEY_SUBJECT "Subject" +#define KEY_OPERATION "Operation" +#define KEY_OPTION "Option" + +#define KEY_CLIENT_PKG_ID "_ClientPkgId_" /* Special key for internal use */ +#define KEY_PKG_ID "PkgId" +#define KEY_START_TIME "StartTime" +#define KEY_END_TIME "EndTime" +#define KEY_UNIV_TIME "UTC" +#define KEY_LOCAL_TIME "LocalTime" +#define KEY_STATE "State" + +#define KEY_RETENTION "Retention" +#define KEY_INTERVAL "Interval" +#define KEY_ANCHOR "Anchor" + +#define KEY_STEPS "Steps" +#define KEY_WALK_STEPS "WalkSteps" +#define KEY_RUN_STEPS "RunSteps" +#define KEY_DISTANCE "Dist" +#define KEY_CALORIES "Cal" +#define KEY_PRESSURE "Pressure" +#define KEY_AVG_PRESSURE "AvgPressure" +#define KEY_MIN_PRESSURE "MinPressure" +#define KEY_MAX_PRESSURE "MaxPressure" +#define KEY_SLEEP_STATE KEY_STATE +#define KEY_HEART_RATE "HeartRate" + +/* Values */ +#define VAL_START "Start" +#define VAL_STOP "Stop" + #endif /* __CONTEXT_SENSOR_RECORDER_TYPES_INTERNAL_H__ */ diff --git a/src/server/legacy/UninstallMonitor.cpp b/src/server/legacy/UninstallMonitor.cpp index 026ea10..6b359ed 100644 --- a/src/server/legacy/UninstallMonitor.cpp +++ b/src/server/legacy/UninstallMonitor.cpp @@ -14,26 +14,25 @@ * limitations under the License. */ -#include "ClientInfo.h" +#include +#include "RecorderClientInfo.h" #include "UninstallMonitor.h" using namespace ctx; -UninstallMonitor::UninstallMonitor() : - __dbusSignalId(-1), - __dbusWatcher(DBusType::SYSTEM) +UninstallMonitor::UninstallMonitor(SensorRecorderService* hostService) : + __dbusMonitor(hostService->getConnection()) { - __dbusSignalId = __dbusWatcher.watch(NULL, + __dbusMonitor.subscribe(NULL, "/org/tizen/pkgmgr/signal", "org.tizen.pkgmgr.signal", "uninstall", this); } UninstallMonitor::~UninstallMonitor() { - if (__dbusSignalId > 0) - __dbusWatcher.unwatch(__dbusSignalId); } -void UninstallMonitor::onSignal(const char *sender, const char *path, const char *iface, const char *name, GVariant *param) +void UninstallMonitor::onSignal(const std::string& sender, const std::string& objPath, + const std::string& interface, const std::string& signalName, GVariant *param) { const gchar *pkgId = NULL; const gchar *key = NULL; @@ -45,5 +44,5 @@ void UninstallMonitor::onSignal(const char *sender, const char *path, const char IF_FAIL_VOID(pkgId && STR_EQ(key, "end") && STR_EQ(val, "ok")); _I("'%s' has been removed", pkgId); - ClientInfo::purgeClient(pkgId); + RecorderClientInfo::purgeClient(pkgId); } diff --git a/src/server/legacy/UninstallMonitor.h b/src/server/legacy/UninstallMonitor.h index baa3659..f014fa3 100644 --- a/src/server/legacy/UninstallMonitor.h +++ b/src/server/legacy/UninstallMonitor.h @@ -17,20 +17,23 @@ #ifndef __CONTEXT_UNINSTALL_MONITOR_H__ #define __CONTEXT_UNINSTALL_MONITOR_H__ -#include +#include +#include namespace ctx { + class SensorRecorderService; + class UninstallMonitor : public IDBusSignalListener { public: - UninstallMonitor(); + UninstallMonitor(SensorRecorderService* hostService); ~UninstallMonitor(); - void onSignal(const char *sender, const char *path, const char *iface, const char *name, GVariant *param); + void onSignal(const std::string& sender, const std::string& objPath, + const std::string& interface, const std::string& signalName, GVariant *param); private: - int64_t __dbusSignalId; - DBusSignalWatcher __dbusWatcher; + DBusMonitor __dbusMonitor; }; } diff --git a/src/server/legacy/heartrate/HeartRate.cpp b/src/server/legacy/heartrate/HeartRate.cpp index 3afa98e..c13b63f 100644 --- a/src/server/legacy/heartrate/HeartRate.cpp +++ b/src/server/legacy/heartrate/HeartRate.cpp @@ -14,11 +14,8 @@ * limitations under the License. */ -#include -#include +#include #include "../TypesInternal.h" -#include "HeartRateLogger.h" -#include "HeartRateQuerier.h" #include "HeartRate.h" using namespace ctx; @@ -26,31 +23,30 @@ using namespace ctx; HeartRateProvider::HeartRateProvider() : SensorProvider(SUBJ_SENSOR_HEART_RATE) { - IF_FAIL_VOID(isSupported()); - - sensorLogger = new(std::nothrow) HeartRateLogger(); - IF_FAIL_VOID_TAG(sensorLogger, _E, "Memory allocation failed"); } HeartRateProvider::~HeartRateProvider() { } -void HeartRateProvider::getPrivilege(std::vector &privilege) +const char* HeartRateProvider::getPrivilege() { - privilege.push_back(PRIV_HEALTHINFO); + return PRIV_HEALTHINFO; } bool HeartRateProvider::isSupported() { - return util::getSystemInfoBool("tizen.org/feature/sensor.heart_rate_monitor"); + return getSystemInfo("tizen.org/feature/sensor.heart_rate_monitor"); +} + +SensorLogger* HeartRateProvider::getLogger() +{ + return &__logger; } -Querier* HeartRateProvider::getQuerier(Json option) +Querier* HeartRateProvider::getQuerier() { - HeartRateQuerier *querier = new(std::nothrow) HeartRateQuerier(this, option); - IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); - return querier; + return &__querier; } bool HeartRateProvider::verifyOption(Json option) diff --git a/src/server/legacy/heartrate/HeartRate.h b/src/server/legacy/heartrate/HeartRate.h index 71f0812..03d1fb6 100644 --- a/src/server/legacy/heartrate/HeartRate.h +++ b/src/server/legacy/heartrate/HeartRate.h @@ -18,6 +18,8 @@ #define __CONTEXT_HEARTRATE_PROVIDER_H__ #include "../SensorProvider.h" +#include "HeartRateLogger.h" +#include "HeartRateQuerier.h" namespace ctx { @@ -27,11 +29,16 @@ namespace ctx { ~HeartRateProvider(); bool isSupported(); - void getPrivilege(std::vector &privilege); + const char* getPrivilege(); protected: - Querier* getQuerier(Json option); + SensorLogger* getLogger(); + Querier* getQuerier(); bool verifyOption(Json option); + + private: + HeartRateLogger __logger; + HeartRateQuerier __querier; }; } diff --git a/src/server/legacy/heartrate/HeartRateLogger.cpp b/src/server/legacy/heartrate/HeartRateLogger.cpp index 8ef6895..c9bdc6e 100644 --- a/src/server/legacy/heartrate/HeartRateLogger.cpp +++ b/src/server/legacy/heartrate/HeartRateLogger.cpp @@ -16,9 +16,10 @@ #include #include -#include +#include +#include "../../SensorTimer.h" #include "../TypesInternal.h" -#include "../ClientInfo.h" +#include "../RecorderClientInfo.h" #include "../TimeUtil.h" #include "HeartRateLogger.h" @@ -30,8 +31,7 @@ using namespace ctx; HeartRateLogger::HeartRateLogger() : - __timerMgr(NULL), - __timerId(-1), + __timerId(0), __timerInterval(INT_MAX), __expiredTime(0) { @@ -46,7 +46,7 @@ HeartRateLogger::HeartRateLogger() : KEY_HEART_RATE " REAL NOT NULL" \ ")"); - ClientInfo clientInfo; + RecorderClientInfo clientInfo; if (clientInfo.exist(SUBJ_SENSOR_HEART_RATE)) start(); } @@ -59,32 +59,27 @@ HeartRateLogger::~HeartRateLogger() bool HeartRateLogger::start() { std::vector options; - ClientInfo clientInfo; + RecorderClientInfo clientInfo; float interval = MAX_MEASURING_INTERVAL; - if (clientInfo.get(SUBJ_SENSOR_HEART_RATE, options) != ERR_NONE) + if (clientInfo.get(SUBJ_SENSOR_HEART_RATE, options) != E_NONE) return false; clientInfo.getParam(options, KEY_INTERVAL, &interval, NULL); - if (!__timerMgr) { - __timerMgr = new(std::nothrow) TimerManager; - IF_FAIL_RETURN_TAG(__timerMgr, false, _E, "Memory allocation failed"); - } - - if (interval == __timerInterval) + if (interval == static_cast(__timerInterval)) return true; - __timerInterval = interval; + __timerInterval = static_cast(interval); - _I(GREEN("Start to record (at every %d minutes)"), __timerInterval); + _I(GREEN("Start to record (at every %u minutes)"), __timerInterval); - if (__timerId > 0) - __timerMgr->remove(__timerId); + if (__timerId != 0) + SensorTimer::cancel(__timerId); - __timerId = __timerMgr->setFor(__timerInterval, this); + __timerId = SensorTimer::addAlarm(__timerInterval, this); - if (__timerId < 0) { + if (__timerId == 0) { _E("Setting timer failed"); __timerInterval = INT_MAX; return false; @@ -97,11 +92,7 @@ void HeartRateLogger::stop() { _I(GREEN("Stop recording")); - if (__timerMgr) - delete __timerMgr; - - __timerMgr = NULL; - __timerId = -1; + __timerId = 0; __timerInterval = INT_MAX; unlisten(); @@ -111,7 +102,7 @@ void HeartRateLogger::flushCache(bool force) { } -bool HeartRateLogger::onTimerExpired(int timerId) +bool HeartRateLogger::onTimerExpired(unsigned int timerId, unsigned int intervalMs, void* data) { IF_FAIL_RETURN(!isRunning(), true); diff --git a/src/server/legacy/heartrate/HeartRateLogger.h b/src/server/legacy/heartrate/HeartRateLogger.h index fa12aa6..c1b0fb7 100644 --- a/src/server/legacy/heartrate/HeartRateLogger.h +++ b/src/server/legacy/heartrate/HeartRateLogger.h @@ -17,7 +17,7 @@ #ifndef __CONTEXT_HEARTRATE_LOGGER_H__ #define __CONTEXT_HEARTRATE_LOGGER_H__ -#include +#include #include "../SensorLogger.h" #include "../SensorProxy.h" @@ -26,6 +26,8 @@ namespace ctx { + class SensorRecorderService; + class HeartRateLogger : public SensorLogger, public SensorProxy, public ITimerListener { public: HeartRateLogger(); @@ -36,15 +38,14 @@ namespace ctx { void flushCache(bool force = false); protected: - bool onTimerExpired(int timerId); + bool onTimerExpired(unsigned int timerId, unsigned int intervalMs, void* data); void onEvent(sensor_data_t *eventData); private: void __record(float heartrate, uint64_t eventTime); - TimerManager *__timerMgr; - int __timerId; - int __timerInterval; + unsigned int __timerId; + unsigned int __timerInterval; uint64_t __expiredTime; }; } diff --git a/src/server/legacy/heartrate/HeartRateQuerier.cpp b/src/server/legacy/heartrate/HeartRateQuerier.cpp index 1bae5a6..2bf1fba 100644 --- a/src/server/legacy/heartrate/HeartRateQuerier.cpp +++ b/src/server/legacy/heartrate/HeartRateQuerier.cpp @@ -15,7 +15,7 @@ */ #include -#include +#include #include "../TypesInternal.h" #include "HeartRateQuerier.h" @@ -26,8 +26,7 @@ using namespace ctx; -HeartRateQuerier::HeartRateQuerier(ContextProvider *provider, Json option) : - Querier(provider, option) +HeartRateQuerier::HeartRateQuerier() { } @@ -35,12 +34,17 @@ HeartRateQuerier::~HeartRateQuerier() { } -int HeartRateQuerier::queryRaw(int startTime, int endTime) +std::string HeartRateQuerier::getProjection() { - return query(startTime, endTime); + return KEY_HEART_RATE "," KEY_START_TIME "," KEY_END_TIME; } -int HeartRateQuerier::query(int startTime, int endTime) +int HeartRateQuerier::queryRaw(int startTime, int endTime, std::vector>* tuples) +{ + return query(startTime, endTime, tuples); +} + +int HeartRateQuerier::query(int startTime, int endTime, std::vector>* tuples) { char *sql = sqlite3_mprintf( "SELECT " PROJECTION \ @@ -48,7 +52,7 @@ int HeartRateQuerier::query(int startTime, int endTime) " WHERE " KEY_UNIV_TIME " > %llu AND " KEY_UNIV_TIME " <= %llu", SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); - int ret = Querier::query(sql); + int ret = Querier::query(sql, tuples); sqlite3_free(sql); return ret; diff --git a/src/server/legacy/heartrate/HeartRateQuerier.h b/src/server/legacy/heartrate/HeartRateQuerier.h index 335d902..9ca670e 100644 --- a/src/server/legacy/heartrate/HeartRateQuerier.h +++ b/src/server/legacy/heartrate/HeartRateQuerier.h @@ -23,11 +23,13 @@ namespace ctx { class HeartRateQuerier : public Querier { public: - HeartRateQuerier(ContextProvider *provider, Json option); + HeartRateQuerier(); ~HeartRateQuerier(); - int queryRaw(int startTime, int endTime); - int query(int startTime, int endTime); + std::string getProjection(); + + int queryRaw(int startTime, int endTime, std::vector>* tuples); + int query(int startTime, int endTime, std::vector>* tuples); }; } diff --git a/src/server/legacy/pedometer/Pedometer.cpp b/src/server/legacy/pedometer/Pedometer.cpp index 8752754..7c45c07 100644 --- a/src/server/legacy/pedometer/Pedometer.cpp +++ b/src/server/legacy/pedometer/Pedometer.cpp @@ -14,11 +14,8 @@ * limitations under the License. */ -#include -#include +#include #include "../TypesInternal.h" -#include "PedometerLogger.h" -#include "PedometerQuerier.h" #include "Pedometer.h" using namespace ctx; @@ -26,29 +23,28 @@ using namespace ctx; PedometerProvider::PedometerProvider() : SensorProvider(SUBJ_SENSOR_PEDOMETER) { - IF_FAIL_VOID(isSupported()); - - sensorLogger = new(std::nothrow) PedometerLogger(); - IF_FAIL_VOID_TAG(sensorLogger, _E, "Memory allocation failed"); } PedometerProvider::~PedometerProvider() { } -void PedometerProvider::getPrivilege(std::vector &privilege) +const char* PedometerProvider::getPrivilege() { - privilege.push_back(PRIV_HEALTHINFO); + return PRIV_HEALTHINFO; } bool PedometerProvider::isSupported() { - return util::getSystemInfoBool("tizen.org/feature/sensor.pedometer"); + return getSystemInfo("tizen.org/feature/sensor.pedometer"); +} + +SensorLogger* PedometerProvider::getLogger() +{ + return &__logger; } -Querier* PedometerProvider::getQuerier(Json option) +Querier* PedometerProvider::getQuerier() { - PedometerQuerier *querier = new(std::nothrow) PedometerQuerier(this, option); - IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); - return querier; + return &__querier; } diff --git a/src/server/legacy/pedometer/Pedometer.h b/src/server/legacy/pedometer/Pedometer.h index 7fee01f..6df0f2a 100644 --- a/src/server/legacy/pedometer/Pedometer.h +++ b/src/server/legacy/pedometer/Pedometer.h @@ -18,6 +18,8 @@ #define __CONTEXT_PEDOMETER_PROVIDER_H__ #include "../SensorProvider.h" +#include "PedometerLogger.h" +#include "PedometerQuerier.h" namespace ctx { @@ -27,10 +29,15 @@ namespace ctx { ~PedometerProvider(); bool isSupported(); - void getPrivilege(std::vector &privilege); + const char* getPrivilege(); protected: - Querier* getQuerier(Json option); + SensorLogger* getLogger(); + Querier* getQuerier(); + + private: + PedometerLogger __logger; + PedometerQuerier __querier; }; } diff --git a/src/server/legacy/pedometer/PedometerLogger.cpp b/src/server/legacy/pedometer/PedometerLogger.cpp index cc44856..90918c7 100644 --- a/src/server/legacy/pedometer/PedometerLogger.cpp +++ b/src/server/legacy/pedometer/PedometerLogger.cpp @@ -16,9 +16,9 @@ #include #include -#include +#include #include "../TypesInternal.h" -#include "../ClientInfo.h" +#include "../RecorderClientInfo.h" #include "../TimeUtil.h" #include "PedometerLogger.h" @@ -43,7 +43,7 @@ PedometerLogger::PedometerLogger() : KEY_CALORIES " REAL NOT NULL" \ ")"); - ClientInfo clientInfo; + RecorderClientInfo clientInfo; if (clientInfo.exist(SUBJ_SENSOR_PEDOMETER)) start(); } diff --git a/src/server/legacy/pedometer/PedometerLogger.h b/src/server/legacy/pedometer/PedometerLogger.h index f4b32f9..b7d118e 100644 --- a/src/server/legacy/pedometer/PedometerLogger.h +++ b/src/server/legacy/pedometer/PedometerLogger.h @@ -41,6 +41,7 @@ namespace ctx { unsigned int runSteps; float distance; float calories; + DataRecord() : timestamp(0), walkSteps(0), runSteps(0), distance(0), calories(0) {} }; void __recordSingle(sensor_pedometer_data_t *eventData, uint64_t timestamp); diff --git a/src/server/legacy/pedometer/PedometerQuerier.cpp b/src/server/legacy/pedometer/PedometerQuerier.cpp index 3abf121..648c5d0 100644 --- a/src/server/legacy/pedometer/PedometerQuerier.cpp +++ b/src/server/legacy/pedometer/PedometerQuerier.cpp @@ -15,7 +15,7 @@ */ #include -#include +#include #include "../TypesInternal.h" #include "PedometerQuerier.h" @@ -39,8 +39,7 @@ using namespace ctx; -PedometerQuerier::PedometerQuerier(ContextProvider *provider, Json option) : - Querier(provider, option) +PedometerQuerier::PedometerQuerier() { } @@ -48,7 +47,19 @@ PedometerQuerier::~PedometerQuerier() { } -int PedometerQuerier::queryRaw(int startTime, int endTime) +std::string PedometerQuerier::getProjection() +{ + return \ + KEY_STEPS "," \ + KEY_WALK_STEPS "," \ + KEY_RUN_STEPS "," \ + KEY_DISTANCE "," \ + KEY_CALORIES "," \ + KEY_START_TIME "," \ + KEY_END_TIME; +} + +int PedometerQuerier::queryRaw(int startTime, int endTime, std::vector>* tuples) { char *sql = sqlite3_mprintf( "SELECT " PROJECTION_RAW \ @@ -57,13 +68,13 @@ int PedometerQuerier::queryRaw(int startTime, int endTime) " ORDER BY " KEY_END_TIME " ASC", SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); - int ret = Querier::query(sql); + int ret = Querier::query(sql, tuples); sqlite3_free(sql); return ret; } -int PedometerQuerier::query(int startTime, int endTime) +int PedometerQuerier::query(int startTime, int endTime, std::vector>* tuples) { char *sql = sqlite3_mprintf( "SELECT " PROJECTION \ @@ -71,13 +82,13 @@ int PedometerQuerier::query(int startTime, int endTime) " WHERE " KEY_END_TIME " > %llu AND " KEY_END_TIME " <= %llu", SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); - int ret = Querier::query(sql); + int ret = Querier::query(sql, tuples); sqlite3_free(sql); return ret; } -int PedometerQuerier::query(int startTime, int endTime, int anchor, int interval) +int PedometerQuerier::query(int startTime, int endTime, int anchor, int interval, std::vector>* tuples) { char *sql = sqlite3_mprintf( "SELECT " PROJECTION \ @@ -88,7 +99,7 @@ int PedometerQuerier::query(int startTime, int endTime, int anchor, int interval SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime)), SEC_TO_MS(static_cast(anchor)), SEC_TO_MS(static_cast(interval))); - int ret = Querier::query(sql); + int ret = Querier::query(sql, tuples); sqlite3_free(sql); return ret; diff --git a/src/server/legacy/pedometer/PedometerQuerier.h b/src/server/legacy/pedometer/PedometerQuerier.h index 21af1e1..057d0d4 100644 --- a/src/server/legacy/pedometer/PedometerQuerier.h +++ b/src/server/legacy/pedometer/PedometerQuerier.h @@ -23,12 +23,14 @@ namespace ctx { class PedometerQuerier : public Querier { public: - PedometerQuerier(ContextProvider *provider, Json option); + PedometerQuerier(); ~PedometerQuerier(); - int queryRaw(int startTime, int endTime); - int query(int startTime, int endTime); - int query(int startTime, int endTime, int anchor, int interval); + std::string getProjection(); + + int queryRaw(int startTime, int endTime, std::vector>* tuples); + int query(int startTime, int endTime, std::vector>* tuples); + int query(int startTime, int endTime, int anchor, int interval, std::vector>* tuples); }; } diff --git a/src/server/legacy/pressure/Pressure.cpp b/src/server/legacy/pressure/Pressure.cpp index 76b60f4..96fcc41 100644 --- a/src/server/legacy/pressure/Pressure.cpp +++ b/src/server/legacy/pressure/Pressure.cpp @@ -14,11 +14,8 @@ * limitations under the License. */ -#include -#include +#include #include "../TypesInternal.h" -#include "PressureLogger.h" -#include "PressureQuerier.h" #include "Pressure.h" using namespace ctx; @@ -26,10 +23,6 @@ using namespace ctx; PressureProvider::PressureProvider() : SensorProvider(SUBJ_SENSOR_PRESSURE) { - IF_FAIL_VOID(isSupported()); - - sensorLogger = new(std::nothrow) PressureLogger(); - IF_FAIL_VOID_TAG(sensorLogger, _E, "Memory allocation failed"); } PressureProvider::~PressureProvider() @@ -38,12 +31,15 @@ PressureProvider::~PressureProvider() bool PressureProvider::isSupported() { - return util::getSystemInfoBool("tizen.org/feature/sensor.barometer"); + return getSystemInfo("tizen.org/feature/sensor.barometer"); +} + +SensorLogger* PressureProvider::getLogger() +{ + return &__logger; } -Querier* PressureProvider::getQuerier(Json option) +Querier* PressureProvider::getQuerier() { - PressureQuerier *querier = new(std::nothrow) PressureQuerier(this, option); - IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); - return querier; + return &__querier; } diff --git a/src/server/legacy/pressure/Pressure.h b/src/server/legacy/pressure/Pressure.h index 419cfba..767bff7 100644 --- a/src/server/legacy/pressure/Pressure.h +++ b/src/server/legacy/pressure/Pressure.h @@ -18,6 +18,8 @@ #define __CONTEXT_PRESSURE_PROVIDER_H__ #include "../SensorProvider.h" +#include "PressureLogger.h" +#include "PressureQuerier.h" namespace ctx { @@ -29,7 +31,12 @@ namespace ctx { bool isSupported(); protected: - Querier* getQuerier(Json option); + SensorLogger* getLogger(); + Querier* getQuerier(); + + private: + PressureLogger __logger; + PressureQuerier __querier; }; } diff --git a/src/server/legacy/pressure/PressureLogger.cpp b/src/server/legacy/pressure/PressureLogger.cpp index 0bb1fe4..14d5b53 100644 --- a/src/server/legacy/pressure/PressureLogger.cpp +++ b/src/server/legacy/pressure/PressureLogger.cpp @@ -16,9 +16,9 @@ #include #include -#include +#include #include "../TypesInternal.h" -#include "../ClientInfo.h" +#include "../RecorderClientInfo.h" #include "../TimeUtil.h" #include "PressureLogger.h" @@ -30,7 +30,9 @@ using namespace ctx; -PressureLogger::PressureLogger() +PressureLogger::PressureLogger() : + __lastEventTime(0), + __cacheCount(0) { setSensor(PRESSURE_SENSOR); setPowerSave(false); @@ -44,7 +46,7 @@ PressureLogger::PressureLogger() KEY_PRESSURE " REAL NOT NULL" \ ")"); - ClientInfo clientInfo; + RecorderClientInfo clientInfo; if (clientInfo.exist(SUBJ_SENSOR_PRESSURE)) start(); } @@ -77,7 +79,7 @@ void PressureLogger::stop() void PressureLogger::flushCache(bool force) { - IF_FAIL_VOID(force || __cacheCount > CACHE_LIMIT); + IF_FAIL_VOID((force && __cacheCount > 0) || __cacheCount > CACHE_LIMIT); __insertionQuery.resize(__insertionQuery.size() - 1); if (__insertionQuery.at(__insertionQuery.size() - 1) == ')') diff --git a/src/server/legacy/pressure/PressureQuerier.cpp b/src/server/legacy/pressure/PressureQuerier.cpp index 8d19638..00f67bb 100644 --- a/src/server/legacy/pressure/PressureQuerier.cpp +++ b/src/server/legacy/pressure/PressureQuerier.cpp @@ -15,7 +15,8 @@ */ #include -#include +#include +#include #include "../TypesInternal.h" #include "PressureQuerier.h" @@ -37,8 +38,7 @@ using namespace ctx; -PressureQuerier::PressureQuerier(ContextProvider *provider, Json option) : - Querier(provider, option) +PressureQuerier::PressureQuerier() { } @@ -46,7 +46,18 @@ PressureQuerier::~PressureQuerier() { } -int PressureQuerier::queryRaw(int startTime, int endTime) +std::string PressureQuerier::getProjection() +{ + return \ + KEY_PRESSURE "," \ + KEY_MIN_PRESSURE "," \ + KEY_MAX_PRESSURE "," \ + KEY_AVG_PRESSURE "," \ + KEY_START_TIME "," \ + KEY_END_TIME; +} + +int PressureQuerier::queryRaw(int startTime, int endTime, std::vector>* tuples) { char *sql = sqlite3_mprintf( "SELECT " PROJECTION_RAW \ @@ -54,13 +65,13 @@ int PressureQuerier::queryRaw(int startTime, int endTime) " WHERE " KEY_UNIV_TIME " > %llu AND " KEY_UNIV_TIME " <= %llu", SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); - int ret = Querier::query(sql); + int ret = Querier::query(sql, tuples); sqlite3_free(sql); return ret; } -int PressureQuerier::query(int startTime, int endTime) +int PressureQuerier::query(int startTime, int endTime, std::vector>* tuples) { char *sql = sqlite3_mprintf( "SELECT " PROJECTION \ @@ -68,13 +79,13 @@ int PressureQuerier::query(int startTime, int endTime) " WHERE " KEY_UNIV_TIME " > %llu AND " KEY_UNIV_TIME " <= %llu", SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); - int ret = Querier::query(sql); + int ret = Querier::query(sql, tuples); sqlite3_free(sql); return ret; } -int PressureQuerier::query(int startTime, int endTime, int anchor, int interval) +int PressureQuerier::query(int startTime, int endTime, int anchor, int interval, std::vector>* tuples) { char *sql = sqlite3_mprintf( "SELECT " PROJECTION \ @@ -85,7 +96,7 @@ int PressureQuerier::query(int startTime, int endTime, int anchor, int interval) SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime)), SEC_TO_MS(static_cast(anchor)), SEC_TO_MS(static_cast(interval))); - int ret = Querier::query(sql); + int ret = Querier::query(sql, tuples); sqlite3_free(sql); return ret; diff --git a/src/server/legacy/pressure/PressureQuerier.h b/src/server/legacy/pressure/PressureQuerier.h index 1bd9aa6..f6380e6 100644 --- a/src/server/legacy/pressure/PressureQuerier.h +++ b/src/server/legacy/pressure/PressureQuerier.h @@ -23,12 +23,14 @@ namespace ctx { class PressureQuerier : public Querier { public: - PressureQuerier(ContextProvider *provider, Json option); + PressureQuerier(); ~PressureQuerier(); - int queryRaw(int startTime, int endTime); - int query(int startTime, int endTime); - int query(int startTime, int endTime, int anchor, int interval); + std::string getProjection(); + + int queryRaw(int startTime, int endTime, std::vector>* tuples); + int query(int startTime, int endTime, std::vector>* tuples); + int query(int startTime, int endTime, int anchor, int interval, std::vector>* tuples); }; } diff --git a/src/server/legacy/sleep/Sleep.cpp b/src/server/legacy/sleep/Sleep.cpp index 3ae40c9..25ec3f1 100644 --- a/src/server/legacy/sleep/Sleep.cpp +++ b/src/server/legacy/sleep/Sleep.cpp @@ -14,11 +14,8 @@ * limitations under the License. */ -#include -#include +#include #include "../TypesInternal.h" -#include "SleepLogger.h" -#include "SleepQuerier.h" #include "Sleep.h" using namespace ctx; @@ -26,29 +23,29 @@ using namespace ctx; SleepProvider::SleepProvider() : SensorProvider(SUBJ_SENSOR_SLEEP_MONITOR) { - IF_FAIL_VOID(isSupported()); - - sensorLogger = new(std::nothrow) SleepLogger(); - IF_FAIL_VOID_TAG(sensorLogger, _E, "Memory allocation failed"); } SleepProvider::~SleepProvider() { } -void SleepProvider::getPrivilege(std::vector &privilege) +const char* SleepProvider::getPrivilege() { - privilege.push_back(PRIV_HEALTHINFO); + return PRIV_HEALTHINFO; } bool SleepProvider::isSupported() { - return util::getSystemInfoBool("tizen.org/feature/sensor.sleep_monitor"); + return (getSystemInfo("tizen.org/feature/sensor.sleep_monitor") + && getSystemInfo("tizen.org/feature/sensor.sleep_detector")); +} + +SensorLogger* SleepProvider::getLogger() +{ + return &__logger; } -Querier* SleepProvider::getQuerier(Json option) +Querier* SleepProvider::getQuerier() { - SleepQuerier *querier = new(std::nothrow) SleepQuerier(this, option); - IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); - return querier; + return &__querier; } diff --git a/src/server/legacy/sleep/Sleep.h b/src/server/legacy/sleep/Sleep.h index c93310e..bf90e59 100644 --- a/src/server/legacy/sleep/Sleep.h +++ b/src/server/legacy/sleep/Sleep.h @@ -18,6 +18,8 @@ #define __CONTEXT_SLEEP_PROVIDER_H__ #include "../SensorProvider.h" +#include "SleepLogger.h" +#include "SleepQuerier.h" namespace ctx { @@ -26,11 +28,16 @@ namespace ctx { SleepProvider(); ~SleepProvider(); - void getPrivilege(std::vector &privilege); + const char* getPrivilege(); bool isSupported(); protected: - Querier* getQuerier(Json option); + SensorLogger* getLogger(); + Querier* getQuerier(); + + private: + SleepLogger __logger; + SleepQuerier __querier; }; } diff --git a/src/server/legacy/sleep/SleepDetector.cpp b/src/server/legacy/sleep/SleepDetector.cpp index 5367dac..7d433a9 100644 --- a/src/server/legacy/sleep/SleepDetector.cpp +++ b/src/server/legacy/sleep/SleepDetector.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "../TimeUtil.h" #include "SleepDetector.h" diff --git a/src/server/legacy/sleep/SleepLogger.cpp b/src/server/legacy/sleep/SleepLogger.cpp index 171df5b..b9e5723 100644 --- a/src/server/legacy/sleep/SleepLogger.cpp +++ b/src/server/legacy/sleep/SleepLogger.cpp @@ -16,9 +16,9 @@ #include #include -#include +#include #include "../TypesInternal.h" -#include "../ClientInfo.h" +#include "../RecorderClientInfo.h" #include "../TimeUtil.h" #include "SleepDetector.h" #include "SleepMonitor.h" @@ -38,6 +38,8 @@ SleepLogger::SleepLogger() : __sleepDetector = NULL; __sleepMonitor = NULL; + __resetInsertionQuery(); + /* Create the log table */ executeQuery( "CREATE TABLE IF NOT EXISTS " SLEEP_MONITOR_RECORD " (" \ @@ -46,7 +48,7 @@ SleepLogger::SleepLogger() : KEY_STATE " INTEGER NOT NULL DEFAULT 1" \ ")"); - ClientInfo clientInfo; + RecorderClientInfo clientInfo; if (clientInfo.exist(SUBJ_SENSOR_SLEEP_MONITOR)) start(); } diff --git a/src/server/legacy/sleep/SleepLogger.h b/src/server/legacy/sleep/SleepLogger.h index 5bf25d1..d0e1926 100644 --- a/src/server/legacy/sleep/SleepLogger.h +++ b/src/server/legacy/sleep/SleepLogger.h @@ -17,6 +17,7 @@ #ifndef __CONTEXT_SLEEP_LOGGER_H__ #define __CONTEXT_SLEEP_LOGGER_H__ +#include #include "../SensorLogger.h" #define STATE_SLEEP 1 diff --git a/src/server/legacy/sleep/SleepMonitor.cpp b/src/server/legacy/sleep/SleepMonitor.cpp index 9b0b227..040e8ee 100644 --- a/src/server/legacy/sleep/SleepMonitor.cpp +++ b/src/server/legacy/sleep/SleepMonitor.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "../TypesInternal.h" #include "../TimeUtil.h" #include "SleepMonitor.h" diff --git a/src/server/legacy/sleep/SleepQuerier.cpp b/src/server/legacy/sleep/SleepQuerier.cpp index 1a8f8dc..1e3e344 100644 --- a/src/server/legacy/sleep/SleepQuerier.cpp +++ b/src/server/legacy/sleep/SleepQuerier.cpp @@ -15,7 +15,8 @@ */ #include -#include +#include +#include #include "../TypesInternal.h" #include "SleepQuerier.h" @@ -26,8 +27,7 @@ using namespace ctx; -SleepQuerier::SleepQuerier(ContextProvider *provider, Json option) : - Querier(provider, option) +SleepQuerier::SleepQuerier() { } @@ -35,12 +35,17 @@ SleepQuerier::~SleepQuerier() { } -int SleepQuerier::queryRaw(int startTime, int endTime) +std::string SleepQuerier::getProjection() { - return query(startTime, endTime); + return KEY_STATE "," KEY_START_TIME "," KEY_END_TIME; } -int SleepQuerier::query(int startTime, int endTime) +int SleepQuerier::queryRaw(int startTime, int endTime, std::vector>* tuples) +{ + return query(startTime, endTime, tuples); +} + +int SleepQuerier::query(int startTime, int endTime, std::vector>* tuples) { char *sql = sqlite3_mprintf( "SELECT " PROJECTION \ @@ -48,7 +53,7 @@ int SleepQuerier::query(int startTime, int endTime) " WHERE " KEY_END_TIME " > %llu AND " KEY_START_TIME " <= %llu", SEC_TO_MS(static_cast(startTime)), SEC_TO_MS(static_cast(endTime))); - int ret = Querier::query(sql); + int ret = Querier::query(sql, tuples); sqlite3_free(sql); return ret; diff --git a/src/server/legacy/sleep/SleepQuerier.h b/src/server/legacy/sleep/SleepQuerier.h index 7ba674f..e76fc10 100644 --- a/src/server/legacy/sleep/SleepQuerier.h +++ b/src/server/legacy/sleep/SleepQuerier.h @@ -23,11 +23,13 @@ namespace ctx { class SleepQuerier : public Querier { public: - SleepQuerier(ContextProvider *provider, Json option); + SleepQuerier(); ~SleepQuerier(); - int queryRaw(int startTime, int endTime); - int query(int startTime, int endTime); + std::string getProjection(); + + int queryRaw(int startTime, int endTime, std::vector>* tuples); + int query(int startTime, int endTime, std::vector>* tuples); }; } diff --git a/src/shared/SensorRecorderTypesPrivate.h b/src/shared/SensorRecorderTypesPrivate.h index 77dcd10..11aec63 100644 --- a/src/shared/SensorRecorderTypesPrivate.h +++ b/src/shared/SensorRecorderTypesPrivate.h @@ -22,13 +22,28 @@ #define CTX_SENSOR_RECORDER "SensorRecorder" #define CTX_SENSOR_RECORDER_SPEC \ - "" \ - " " \ - " " \ + "" \ + " " \ + "" \ + "" \ + " " \ + " " \ + "" \ + "" \ + " " \ + "" \ + "" \ + " " \ + " " \ + " " \ + " " \ "" -#ifndef STR_EQ -#define STR_EQ(X, Y) (g_strcmp0((X), (Y)) == 0) -#endif +#define METHOD_IS_SUPPORTED "IsSupported" +#define METHOD_START_REC "StartRecording" +#define METHOD_STOP_REC "StopRecording" +#define METHOD_READ_REC "ReadRecords" + +#define BASE_PATH "sensor-recorder" #endif -- 2.7.4 From 55b10ea705fe645dbb96ff514d3266fecfe2bbb5 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 19 May 2017 22:48:22 +0900 Subject: [PATCH 09/16] Version 1.0.0 Change-Id: I17b5e42a9bdc76dae6c602a4db6f1c0c4594b720 Signed-off-by: Mu-Woong Lee --- packaging/context-sensor-recorder.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/context-sensor-recorder.spec b/packaging/context-sensor-recorder.spec index 3babfc1..21760ef 100644 --- a/packaging/context-sensor-recorder.spec +++ b/packaging/context-sensor-recorder.spec @@ -1,6 +1,6 @@ Name: context-sensor-recorder Summary: Sensor recorder service server and client libraries -Version: 0.0.1 +Version: 1.0.0 Release: 1 Group: Service Framework/Context License: Apache-2.0 -- 2.7.4 From b74875f7a9ff7637aa1663cd79610bb4667f403f Mon Sep 17 00:00:00 2001 From: "kibak.yoon" Date: Sun, 21 May 2017 16:06:23 +0900 Subject: [PATCH 10/16] sensor: rec: allow option parameter that can be NULL Change-Id: I037246fc8f4d924b9af131d523c40f36557d1cd0 Signed-off-by: kibak.yoon --- src/client/sensor_recorder.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/client/sensor_recorder.cpp b/src/client/sensor_recorder.cpp index f57fae3..e599b34 100644 --- a/src/client/sensor_recorder.cpp +++ b/src/client/sensor_recorder.cpp @@ -66,9 +66,12 @@ EXPORT_API int ctx_sensor_rec_is_supported(const char* subject, bool *supported) EXPORT_API int ctx_sensor_rec_start(const char* subject, ctx_sensor_rec_option_h option) { - IF_FAIL_RETURN(subject && option, E_PARAM); + IF_FAIL_RETURN(subject, E_PARAM); + + std::string optionStr(""); - std::string optionStr = __mapToJson(*static_cast(option)); + if (option) + optionStr = __mapToJson(*static_cast(option)); GVariant* param = g_variant_new("(ss)", subject, optionStr.c_str()); return __getServiceProxy()->call(METHOD_START_REC, param); -- 2.7.4 From 1ed432d120b8859f43373707f2bd4d39721bfab9 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Mon, 29 May 2017 14:42:08 +0900 Subject: [PATCH 11/16] Add dependency to sensord sensor-recorder requires sensord, as it collects sensory data from sensord. Change-Id: Id4eff150ca9882dc1fbb8a33cd62dc693270bef1 Signed-off-by: Mu-Woong Lee --- packaging/context-sensor-recorder.spec | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packaging/context-sensor-recorder.spec b/packaging/context-sensor-recorder.spec index 21760ef..a09e3a2 100644 --- a/packaging/context-sensor-recorder.spec +++ b/packaging/context-sensor-recorder.spec @@ -18,8 +18,11 @@ BuildRequires: pkgconfig(context-common-client) Requires: %{name}-dummy = %{version}-%{release} Requires: context-service +Requires: sensord + Provides: %{name}-profile_mobile = %{version}-%{release} Provides: %{name}-profile_wearable = %{version}-%{release} + %global __provides_exclude ^.*-genuine\\.so.*$ %description -- 2.7.4 From eba46fff255466754e3db98e0444499ced19f7ec Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Thu, 8 Jun 2017 21:27:46 +0900 Subject: [PATCH 12/16] Rename the class Json to avoid symbol conflicts with Jsoncpp Change-Id: Iaa1159d13e1f60808fdd540f27cc9c5a0681a1c7 Signed-off-by: Mu-Woong Lee --- src/server/legacy/RecorderClientInfo.cpp | 12 ++++++------ src/server/legacy/RecorderClientInfo.h | 10 +++++----- src/server/legacy/SensorProvider.cpp | 12 ++++++------ src/server/legacy/SensorProvider.h | 8 ++++---- src/server/legacy/heartrate/HeartRate.cpp | 2 +- src/server/legacy/heartrate/HeartRate.h | 2 +- src/server/legacy/heartrate/HeartRateLogger.cpp | 2 +- 7 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/server/legacy/RecorderClientInfo.cpp b/src/server/legacy/RecorderClientInfo.cpp index 0ab8619..2bf99d8 100644 --- a/src/server/legacy/RecorderClientInfo.cpp +++ b/src/server/legacy/RecorderClientInfo.cpp @@ -55,7 +55,7 @@ RecorderClientInfo::~RecorderClientInfo() __uninstallMonitor = NULL; } -int RecorderClientInfo::get(std::string subject, std::string pkgId, Json& option) +int RecorderClientInfo::get(std::string subject, std::string pkgId, CtxJson& option) { bool ret; std::string optStr; @@ -78,7 +78,7 @@ int RecorderClientInfo::get(std::string subject, std::string pkgId, Json& option return E_NONE; } -int RecorderClientInfo::get(std::string subject, std::vector& options) +int RecorderClientInfo::get(std::string subject, std::vector& options) { bool ret; std::string optStr; @@ -97,7 +97,7 @@ int RecorderClientInfo::get(std::string subject, std::vector& options) for (auto& tuple : tuples) { tuple->getAt(0, &optStr); - options.push_back(Json(optStr)); + options.push_back(CtxJson(optStr)); } return E_NONE; @@ -122,7 +122,7 @@ bool RecorderClientInfo::exist(std::string subject) return true; } -bool RecorderClientInfo::set(std::string subject, std::string pkgId, Json option, int retentionPeriod) +bool RecorderClientInfo::set(std::string subject, std::string pkgId, CtxJson option, int retentionPeriod) { bool ret; char *query = sqlite3_mprintf( @@ -149,11 +149,11 @@ bool RecorderClientInfo::remove(std::string subject, std::string pkgId) return ret; } -void RecorderClientInfo::getParam(std::vector &options, const char *key, float *min, float *max) +void RecorderClientInfo::getParam(std::vector &options, const char *key, float *min, float *max) { double val; - for (Json& opt : options) { + for (CtxJson& opt : options) { if (!opt.get(NULL, key, &val)) continue; if (min) diff --git a/src/server/legacy/RecorderClientInfo.h b/src/server/legacy/RecorderClientInfo.h index 9a8bbc9..0c85919 100644 --- a/src/server/legacy/RecorderClientInfo.h +++ b/src/server/legacy/RecorderClientInfo.h @@ -19,7 +19,7 @@ #include #include -#include +#include #include #include "UninstallMonitor.h" @@ -32,14 +32,14 @@ namespace ctx { RecorderClientInfo(); ~RecorderClientInfo(); - int get(std::string subject, std::string pkgId, Json& option); - int get(std::string subject, std::vector& options); + int get(std::string subject, std::string pkgId, CtxJson& option); + int get(std::string subject, std::vector& options); bool exist(std::string subject); - bool set(std::string subject, std::string pkgId, Json option, int retentionPeriod); + bool set(std::string subject, std::string pkgId, CtxJson option, int retentionPeriod); bool remove(std::string subject, std::string pkgId); - void getParam(std::vector& options, const char *key, float *min, float *max); + void getParam(std::vector& options, const char *key, float *min, float *max); static void purgeClient(std::string pkgId); static void setHostService(SensorRecorderService* hostService); diff --git a/src/server/legacy/SensorProvider.cpp b/src/server/legacy/SensorProvider.cpp index 2103376..a31a050 100644 --- a/src/server/legacy/SensorProvider.cpp +++ b/src/server/legacy/SensorProvider.cpp @@ -98,7 +98,7 @@ const char* SensorProvider::getPrivilege() return NULL; } -int SensorProvider::readRecords(Json option, std::string* projection, std::vector>* tuples) +int SensorProvider::readRecords(CtxJson option, std::string* projection, std::vector>* tuples) { int endTime = static_cast(time(NULL)) + 1; int startTime = endTime - DEFAULT_QUERY_PERIOD - 1; @@ -141,7 +141,7 @@ int SensorProvider::readRecords(Json option, std::string* projection, std::vecto return ret; } -int SensorProvider::startRecording(const std::string& pkgId, Json option) +int SensorProvider::startRecording(const std::string& pkgId, CtxJson option) { int retentionPeriod = DEFAULT_RETENTION; @@ -165,16 +165,16 @@ int SensorProvider::stopRecording(const std::string& pkgId) return __removeClient(pkgId); } -bool SensorProvider::verifyOption(Json option) +bool SensorProvider::verifyOption(CtxJson option) { std::list keys; option.getKeys(&keys); return keys.size() == 0; } -int SensorProvider::__addClient(std::string pkgId, int retentionPeriod, Json option) +int SensorProvider::__addClient(std::string pkgId, int retentionPeriod, CtxJson option) { - Json tmp; + CtxJson tmp; int ret; /* Validate the retention period */ @@ -197,7 +197,7 @@ int SensorProvider::__addClient(std::string pkgId, int retentionPeriod, Json opt int SensorProvider::__removeClient(std::string pkgId) { - std::vector options; + std::vector options; int ret; /* Remove the app's request first */ diff --git a/src/server/legacy/SensorProvider.h b/src/server/legacy/SensorProvider.h index 245ec31..0e17775 100644 --- a/src/server/legacy/SensorProvider.h +++ b/src/server/legacy/SensorProvider.h @@ -35,8 +35,8 @@ namespace ctx { const char* getSubject(); - int readRecords(Json option, std::string* projection, std::vector>* tuples); - int startRecording(const std::string& pkgId, Json option); + int readRecords(CtxJson option, std::string* projection, std::vector>* tuples); + int startRecording(const std::string& pkgId, CtxJson option); int stopRecording(const std::string& pkgId); virtual bool isSupported(); @@ -55,10 +55,10 @@ namespace ctx { virtual SensorLogger* getLogger() = 0; virtual Querier* getQuerier() = 0; - virtual bool verifyOption(Json option); + virtual bool verifyOption(CtxJson option); private: - int __addClient(std::string pkgId, int retentionPeriod, Json option); + int __addClient(std::string pkgId, int retentionPeriod, CtxJson option); int __removeClient(std::string pkgId); std::string __subject; diff --git a/src/server/legacy/heartrate/HeartRate.cpp b/src/server/legacy/heartrate/HeartRate.cpp index c13b63f..55dadf2 100644 --- a/src/server/legacy/heartrate/HeartRate.cpp +++ b/src/server/legacy/heartrate/HeartRate.cpp @@ -49,7 +49,7 @@ Querier* HeartRateProvider::getQuerier() return &__querier; } -bool HeartRateProvider::verifyOption(Json option) +bool HeartRateProvider::verifyOption(CtxJson option) { std::list keys; option.getKeys(&keys); diff --git a/src/server/legacy/heartrate/HeartRate.h b/src/server/legacy/heartrate/HeartRate.h index 03d1fb6..05b1e60 100644 --- a/src/server/legacy/heartrate/HeartRate.h +++ b/src/server/legacy/heartrate/HeartRate.h @@ -34,7 +34,7 @@ namespace ctx { protected: SensorLogger* getLogger(); Querier* getQuerier(); - bool verifyOption(Json option); + bool verifyOption(CtxJson option); private: HeartRateLogger __logger; diff --git a/src/server/legacy/heartrate/HeartRateLogger.cpp b/src/server/legacy/heartrate/HeartRateLogger.cpp index c9bdc6e..427fcf1 100644 --- a/src/server/legacy/heartrate/HeartRateLogger.cpp +++ b/src/server/legacy/heartrate/HeartRateLogger.cpp @@ -58,7 +58,7 @@ HeartRateLogger::~HeartRateLogger() bool HeartRateLogger::start() { - std::vector options; + std::vector options; RecorderClientInfo clientInfo; float interval = MAX_MEASURING_INTERVAL; -- 2.7.4 From d91f4a83e60ae3692b7e4a265fa6156369c58e62 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 9 Jun 2017 19:45:42 +0900 Subject: [PATCH 13/16] Dependency cleanup: apply the modified service & client interfaces Change-Id: I9eda5fa56e03338e5acd8768976714f5bf007d5f Signed-off-by: Mu-Woong Lee --- include/private/SensorRecorderService.h | 24 +++++++++--- packaging/context-sensor-recorder.spec | 2 +- src/server-dummy/SensorRecorderService.cpp | 29 ++++++++++++-- ...sorRecorderClient.cpp => MethodCallHandler.cpp} | 44 ++++++++++++---------- ...{SensorRecorderClient.h => MethodCallHandler.h} | 27 +++++++------ src/server/SensorRecorderService.cpp | 43 +++++++++++++++++---- src/server/SensorTimer.cpp | 5 +-- src/server/SensorTimer.h | 5 ++- 8 files changed, 127 insertions(+), 52 deletions(-) rename src/server/{SensorRecorderClient.cpp => MethodCallHandler.cpp} (70%) rename src/server/{SensorRecorderClient.h => MethodCallHandler.h} (55%) diff --git a/include/private/SensorRecorderService.h b/include/private/SensorRecorderService.h index 50f9a8b..90520f4 100644 --- a/include/private/SensorRecorderService.h +++ b/include/private/SensorRecorderService.h @@ -19,22 +19,36 @@ /* This header SHOULD NOT be included by other headers in this directory. */ -#include +#include +#include +#include namespace ctx { - class EXPORT_API SensorRecorderService : public ServiceBase { + class EXPORT_API SensorRecorderService : public IService { public: - SensorRecorderService(GDBusConnection* conn); + SensorRecorderService(); ~SensorRecorderService(); + void setServiceRunner(IServiceRunner* runner); + bool isUserService(); - protected: + const char* getServiceName(); + const char* getMethodSpecs(); + bool prepare(); void cleanup(); - ClientBase* createClient(const std::string& busName); + void onUserActivated(); + void onUserDeactivated(); + + IMethodCallHandler* createMethodCallHandler(); + + GDBusConnection* getConnection(); + + private: + IServiceRunner* __serviceRunner; }; } diff --git a/packaging/context-sensor-recorder.spec b/packaging/context-sensor-recorder.spec index a09e3a2..83efa7b 100644 --- a/packaging/context-sensor-recorder.spec +++ b/packaging/context-sensor-recorder.spec @@ -1,6 +1,6 @@ Name: context-sensor-recorder Summary: Sensor recorder service server and client libraries -Version: 1.0.0 +Version: 1.0.1 Release: 1 Group: Service Framework/Context License: Apache-2.0 diff --git a/src/server-dummy/SensorRecorderService.cpp b/src/server-dummy/SensorRecorderService.cpp index 2501a40..06cf899 100644 --- a/src/server-dummy/SensorRecorderService.cpp +++ b/src/server-dummy/SensorRecorderService.cpp @@ -14,13 +14,14 @@ * limitations under the License. */ +#include #include #include using namespace ctx; -SensorRecorderService::SensorRecorderService(GDBusConnection* conn) : - ServiceBase(conn, CTX_SENSOR_RECORDER, CTX_SENSOR_RECORDER_SPEC) +SensorRecorderService::SensorRecorderService() : + __serviceRunner(NULL) { throw std::runtime_error("Sensor Recorder is not supported"); } @@ -29,11 +30,25 @@ SensorRecorderService::~SensorRecorderService() { } +void SensorRecorderService::setServiceRunner(IServiceRunner* runner) +{ +} + bool SensorRecorderService::isUserService() { return true; } +const char* SensorRecorderService::getServiceName() +{ + return NULL; +} + +const char* SensorRecorderService::getMethodSpecs() +{ + return NULL; +} + bool SensorRecorderService::prepare() { return false; @@ -43,7 +58,15 @@ void SensorRecorderService::cleanup() { } -ClientBase* SensorRecorderService::createClient(const std::string& busName) +void SensorRecorderService::onUserActivated() +{ +} + +void SensorRecorderService::onUserDeactivated() +{ +} + +IMethodCallHandler* SensorRecorderService::createMethodCallHandler() { return NULL; } diff --git a/src/server/SensorRecorderClient.cpp b/src/server/MethodCallHandler.cpp similarity index 70% rename from src/server/SensorRecorderClient.cpp rename to src/server/MethodCallHandler.cpp index 87eed76..8a20944 100644 --- a/src/server/SensorRecorderClient.cpp +++ b/src/server/MethodCallHandler.cpp @@ -14,10 +14,9 @@ * limitations under the License. */ -#include -#include +#include #include -#include "SensorRecorderClient.h" +#include "MethodCallHandler.h" #include "legacy/SensorProvider.h" #define IDX_SUBJECT 0 @@ -25,16 +24,21 @@ using namespace ctx; -SensorRecorderClient::SensorRecorderClient(ServiceBase* hostService, const std::string& busName) : - ClientBase(hostService, busName) +MethodCallHandler::MethodCallHandler() : + __caller(NULL) { } -SensorRecorderClient::~SensorRecorderClient() +MethodCallHandler::~MethodCallHandler() { } -void SensorRecorderClient::onMethodCalled(MethodCall* methodCall) +void MethodCallHandler::setCaller(IClient* client) +{ + __caller = client; +} + +void MethodCallHandler::onMethodCalled(IMethodCall* methodCall) { try { __verifyUid(methodCall->getUid()); @@ -64,19 +68,19 @@ void SensorRecorderClient::onMethodCalled(MethodCall* methodCall) delete methodCall; } -void SensorRecorderClient::onDisconnected() +void MethodCallHandler::onDisconnected() { } -void SensorRecorderClient::__verifyUid(uid_t uid) +void MethodCallHandler::__verifyUid(uid_t uid) { - if (!isSystemUid(uid) && uid != ServiceBase::getActiveUser()) { - _E("Invalid Uid: %u != %u (ActiveUser)", uid, ServiceBase::getActiveUser()); + if (!util::isSystemUid(uid) && uid != util::getActiveUid()) { + _E("Invalid Uid: %u != %u (ActiveUser)", uid, util::getActiveUid()); throw static_cast(E_ACCESS); } } -std::string SensorRecorderClient::__extractParameter(GVariant* param, unsigned int idx) +std::string MethodCallHandler::__extractParameter(GVariant* param, unsigned int idx) { const char* val = NULL; g_variant_get_child(param, idx, "&s", &val); @@ -87,13 +91,13 @@ std::string SensorRecorderClient::__extractParameter(GVariant* param, unsigned i return val; } -void SensorRecorderClient::__startRecording(SensorProvider& provider, MethodCall& methodCall) +void MethodCallHandler::__startRecording(SensorProvider& provider, IMethodCall& methodCall) { - if (!hasPrivilege(provider.getPrivilege())) + if (!methodCall.hasPrivilege(provider.getPrivilege())) throw static_cast(E_ACCESS); // TODO: use the 'real' package id, instead of the smack label - std::string pkgId = getClientId(); + std::string pkgId = methodCall.getCallerId(); std::string option = __extractParameter(methodCall.getParam(), IDX_OPTION); _D("Option: %s", option.c_str()); @@ -101,22 +105,22 @@ void SensorRecorderClient::__startRecording(SensorProvider& provider, MethodCall methodCall.reply(error); } -void SensorRecorderClient::__stopRecording(SensorProvider& provider, MethodCall& methodCall) +void MethodCallHandler::__stopRecording(SensorProvider& provider, IMethodCall& methodCall) { // TODO: use the 'real' package id, instead of the smack label - std::string pkgId = getClientId(); + std::string pkgId = methodCall.getCallerId(); int error = provider.stopRecording(pkgId); methodCall.reply(error); } -void SensorRecorderClient::__readRecords(SensorProvider& provider, MethodCall& methodCall) +void MethodCallHandler::__readRecords(SensorProvider& provider, IMethodCall& methodCall) { - if (!hasPrivilege(provider.getPrivilege())) + if (!methodCall.hasPrivilege(provider.getPrivilege())) throw static_cast(E_ACCESS); // TODO: use the 'real' package id, instead of the smack label - std::string pkgId = getClientId(); + std::string pkgId = methodCall.getCallerId(); std::string option = __extractParameter(methodCall.getParam(), IDX_OPTION); _D("Option: %s", option.c_str()); diff --git a/src/server/SensorRecorderClient.h b/src/server/MethodCallHandler.h similarity index 55% rename from src/server/SensorRecorderClient.h rename to src/server/MethodCallHandler.h index 45cc9fe..cde2a2b 100644 --- a/src/server/SensorRecorderClient.h +++ b/src/server/MethodCallHandler.h @@ -14,31 +14,36 @@ * limitations under the License. */ -#ifndef __SENSOR_RECORDER_CLIENT_H__ -#define __SENSOR_RECORDER_CLIENT_H__ +#ifndef __SENSOR_RECORDER_METHOD_CALL_HANDLER_H__ +#define __SENSOR_RECORDER_METHOD_CALL_HANDLER_H__ -#include +#include +#include +#include namespace ctx { class SensorProvider; - class SensorRecorderClient : public ClientBase { + class MethodCallHandler : public IMethodCallHandler { public: - SensorRecorderClient(ServiceBase* hostService, const std::string& busName); - ~SensorRecorderClient(); + MethodCallHandler(); + ~MethodCallHandler(); - void onMethodCalled(MethodCall* methodCall); + void setCaller(IClient* client); + void onMethodCalled(IMethodCall* methodCall); void onDisconnected(); private: void __verifyUid(uid_t uid); std::string __extractParameter(GVariant* param, unsigned int idx); - void __startRecording(SensorProvider& provider, MethodCall& methodCall); - void __stopRecording(SensorProvider& provider, MethodCall& methodCall); - void __readRecords(SensorProvider& provider, MethodCall& methodCall); + void __startRecording(SensorProvider& provider, IMethodCall& methodCall); + void __stopRecording(SensorProvider& provider, IMethodCall& methodCall); + void __readRecords(SensorProvider& provider, IMethodCall& methodCall); + + IClient* __caller; }; } -#endif /* __SENSOR_RECORDER_CLIENT_H__ */ +#endif /* __SENSOR_RECORDER_METHOD_CALL_HANDLER_H__ */ diff --git a/src/server/SensorRecorderService.cpp b/src/server/SensorRecorderService.cpp index b9ddf11..bb1ae60 100644 --- a/src/server/SensorRecorderService.cpp +++ b/src/server/SensorRecorderService.cpp @@ -14,9 +14,10 @@ * limitations under the License. */ +#include #include #include -#include "SensorRecorderClient.h" +#include "MethodCallHandler.h" #include "SensorDatabase.h" #include "SensorTimer.h" #include "legacy/SensorProvider.h" @@ -24,8 +25,8 @@ using namespace ctx; -SensorRecorderService::SensorRecorderService(GDBusConnection* conn) : - ServiceBase(conn, CTX_SENSOR_RECORDER, CTX_SENSOR_RECORDER_SPEC) +SensorRecorderService::SensorRecorderService() : + __serviceRunner(NULL) { } @@ -33,19 +34,34 @@ SensorRecorderService::~SensorRecorderService() { } +void SensorRecorderService::setServiceRunner(IServiceRunner* runner) +{ + __serviceRunner = runner; +} + bool SensorRecorderService::isUserService() { return true; } +const char* SensorRecorderService::getServiceName() +{ + return CTX_SENSOR_RECORDER; +} + +const char* SensorRecorderService::getMethodSpecs() +{ + return CTX_SENSOR_RECORDER_SPEC; +} + bool SensorRecorderService::prepare() { RecorderClientInfo::setHostService(this); - if (!SensorDatabase::open(getActiveUser())) + if (!SensorDatabase::open(util::getActiveUid())) return false; - SensorTimer::init(this); + SensorTimer::init(__serviceRunner->getMainContext()); SensorProvider::init(); return true; @@ -58,7 +74,20 @@ void SensorRecorderService::cleanup() SensorDatabase::close(); } -ClientBase* SensorRecorderService::createClient(const std::string& busName) +void SensorRecorderService::onUserActivated() +{ +} + +void SensorRecorderService::onUserDeactivated() +{ +} + +IMethodCallHandler* SensorRecorderService::createMethodCallHandler() +{ + return new MethodCallHandler(); +} + +GDBusConnection* SensorRecorderService::getConnection() { - return new SensorRecorderClient(this, busName); + return __serviceRunner->getConnection(); } diff --git a/src/server/SensorTimer.cpp b/src/server/SensorTimer.cpp index 62f7da9..2e83968 100644 --- a/src/server/SensorTimer.cpp +++ b/src/server/SensorTimer.cpp @@ -16,7 +16,6 @@ #include #include -#include #include #include "SensorTimer.h" @@ -28,9 +27,9 @@ SensorTimer::SensorTimer() { } -void SensorTimer::init(ServiceBase* hostService) +void SensorTimer::init(GMainContext* mainContext) { - __timer = new Timer(hostService); + __timer = new Timer(mainContext); } void SensorTimer::release() diff --git a/src/server/SensorTimer.h b/src/server/SensorTimer.h index ba79daa..3f258a3 100644 --- a/src/server/SensorTimer.h +++ b/src/server/SensorTimer.h @@ -17,15 +17,16 @@ #ifndef __SENSOR_RECORDER_TIMER_H__ #define __SENSOR_RECORDER_TIMER_H__ +#include + namespace ctx { - class ServiceBase; class Timer; class ITimerListener; class SensorTimer { public: - static void init(ServiceBase* hostService); + static void init(GMainContext* mainContext); static void release(); static unsigned int addIdle(GSourceFunc callback, gpointer userData); -- 2.7.4 From 7a76a4340beef3af12fad21a6f2c0a0c17a168f1 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Tue, 13 Jun 2017 18:56:27 +0900 Subject: [PATCH 14/16] Remove run dependency to 'sensord' This dependency should be stated in the 'sensor recorder' block spec file. Change-Id: I77c09c9e5e78af51781195566c9dbd7743dc5182 Signed-off-by: Mu-Woong Lee --- packaging/context-sensor-recorder.spec | 1 - 1 file changed, 1 deletion(-) diff --git a/packaging/context-sensor-recorder.spec b/packaging/context-sensor-recorder.spec index 83efa7b..63c9fa9 100644 --- a/packaging/context-sensor-recorder.spec +++ b/packaging/context-sensor-recorder.spec @@ -18,7 +18,6 @@ BuildRequires: pkgconfig(context-common-client) Requires: %{name}-dummy = %{version}-%{release} Requires: context-service -Requires: sensord Provides: %{name}-profile_mobile = %{version}-%{release} Provides: %{name}-profile_wearable = %{version}-%{release} -- 2.7.4 From e26360b5a9b488683ac57c5dbd258650639ff416 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 16 Jun 2017 16:49:54 +0900 Subject: [PATCH 15/16] Rename the DB file to .context-sensor-recorder.db Change-Id: I2dd961d1766a35ea205a67c519e01653b40c8516 Signed-off-by: Mu-Woong Lee --- src/shared/SensorRecorderTypesPrivate.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/shared/SensorRecorderTypesPrivate.h b/src/shared/SensorRecorderTypesPrivate.h index 11aec63..d53c592 100644 --- a/src/shared/SensorRecorderTypesPrivate.h +++ b/src/shared/SensorRecorderTypesPrivate.h @@ -44,6 +44,6 @@ #define METHOD_STOP_REC "StopRecording" #define METHOD_READ_REC "ReadRecords" -#define BASE_PATH "sensor-recorder" +#define BASE_PATH "context-sensor-recorder" #endif -- 2.7.4 From c637f23868f4b3b29957e6d0e9d233bff3008d4c Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Mon, 26 Jun 2017 16:18:02 +0900 Subject: [PATCH 16/16] Remove thread switching of sensor events contextd is now single-threaded, thus sensor events don't need to be passed to the sensor-recorder's thread. Change-Id: I261f2487c76ea74634b7a502b3a12d5b419f395e Signed-off-by: Mu-Woong Lee --- src/server/SensorRecorderService.cpp | 2 +- src/server/SensorTimer.cpp | 9 ++------- src/server/SensorTimer.h | 3 +-- src/server/legacy/SensorProxy.cpp | 34 +--------------------------------- src/server/legacy/SensorProxy.h | 1 - 5 files changed, 5 insertions(+), 44 deletions(-) diff --git a/src/server/SensorRecorderService.cpp b/src/server/SensorRecorderService.cpp index bb1ae60..9846d00 100644 --- a/src/server/SensorRecorderService.cpp +++ b/src/server/SensorRecorderService.cpp @@ -61,7 +61,7 @@ bool SensorRecorderService::prepare() if (!SensorDatabase::open(util::getActiveUid())) return false; - SensorTimer::init(__serviceRunner->getMainContext()); + SensorTimer::init(); SensorProvider::init(); return true; diff --git a/src/server/SensorTimer.cpp b/src/server/SensorTimer.cpp index 2e83968..acf2bfa 100644 --- a/src/server/SensorTimer.cpp +++ b/src/server/SensorTimer.cpp @@ -27,9 +27,9 @@ SensorTimer::SensorTimer() { } -void SensorTimer::init(GMainContext* mainContext) +void SensorTimer::init() { - __timer = new Timer(mainContext); + __timer = new Timer(); } void SensorTimer::release() @@ -37,11 +37,6 @@ void SensorTimer::release() delete __timer; } -unsigned int SensorTimer::addIdle(GSourceFunc callback, gpointer userData) -{ - return __timer->addIdle(callback, userData); -} - unsigned int SensorTimer::addAlarm(unsigned int intervalMin, ITimerListener* listener) { return __timer->addAlarm(intervalMin, listener, NULL); diff --git a/src/server/SensorTimer.h b/src/server/SensorTimer.h index 3f258a3..752f86d 100644 --- a/src/server/SensorTimer.h +++ b/src/server/SensorTimer.h @@ -26,10 +26,9 @@ namespace ctx { class SensorTimer { public: - static void init(GMainContext* mainContext); + static void init(); static void release(); - static unsigned int addIdle(GSourceFunc callback, gpointer userData); static unsigned int addAlarm(unsigned int intervalMin, ITimerListener* listener); static void cancel(unsigned int timerId); diff --git a/src/server/legacy/SensorProxy.cpp b/src/server/legacy/SensorProxy.cpp index 53afe65..fb29fbd 100644 --- a/src/server/legacy/SensorProxy.cpp +++ b/src/server/legacy/SensorProxy.cpp @@ -23,11 +23,6 @@ using namespace ctx; -struct SensorEvent { - SensorProxy* listener; - sensor_data_t* data; -}; - SensorProxy::SensorProxy() : sensorHandle(-1), sensorType(UNKNOWN_SENSOR), @@ -125,32 +120,5 @@ bool SensorProxy::isSupported(sensor_type_t type) void SensorProxy::__eventCb(sensor_t sensor, unsigned int eventType, sensor_data_t *eventData, void *cbData) { - SensorEvent* sensorEvent = new SensorEvent; - sensorEvent->listener = static_cast(cbData); - - if (sensorEvent->listener->sensorType == HUMAN_PEDOMETER_SENSOR) { - sensorEvent->data = static_cast(g_memdup(eventData, sizeof(sensor_pedometer_data_t))); - } else { - sensorEvent->data = static_cast(g_memdup(eventData, sizeof(sensor_data_t))); - } - - if (!sensorEvent->data) { - _E_ALLOC; - delete sensorEvent; - return; - } - - SensorTimer::addIdle(__threadSwitcher, sensorEvent); -} - -gboolean SensorProxy::__threadSwitcher(gpointer data) -{ - SensorEvent* sensorEvent = static_cast(data); - - sensorEvent->listener->onEvent(sensorEvent->data); - - g_free(sensorEvent->data); - delete sensorEvent; - - return G_SOURCE_REMOVE; + static_cast(cbData)->onEvent(eventData); } diff --git a/src/server/legacy/SensorProxy.h b/src/server/legacy/SensorProxy.h index e2e4af5..7ae1c87 100644 --- a/src/server/legacy/SensorProxy.h +++ b/src/server/legacy/SensorProxy.h @@ -52,7 +52,6 @@ namespace ctx { private: static void __eventCb(sensor_t sensor, unsigned int eventType, sensor_data_t *eventData, void *cbData); - static gboolean __threadSwitcher(gpointer data); }; } -- 2.7.4