From da137414675f2ce5ae5336f517d4dfc248cfeb4f Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Fri, 10 Jun 2016 19:52:59 +0200 Subject: [PATCH 01/16] [my-place] Dynamic loading of PlacesDetector library. Change-Id: I7b007eef5e811a6c04d4f1b1aa120e94ae713657 Signed-off-by: Marcin Masternak --- src/my-place/CMakeLists.txt | 3 +- src/my-place/facade/UserPlaces.cpp | 52 ++++++++++++++++++++++------------- src/my-place/facade/UserPlaces.h | 8 ++++-- src/my-place/place/CMakeLists.txt | 7 +++++ src/my-place/place/PlacesDetector.cpp | 6 ++++ 5 files changed, 53 insertions(+), 23 deletions(-) create mode 100644 src/my-place/place/CMakeLists.txt diff --git a/src/my-place/CMakeLists.txt b/src/my-place/CMakeLists.txt index c336024..7ea03ee 100644 --- a/src/my-place/CMakeLists.txt +++ b/src/my-place/CMakeLists.txt @@ -6,7 +6,7 @@ SET(DEPS ${DEPS} capi-network-wifi ) -FILE(GLOB SRCS *.cpp facade/*.cpp place/*.cpp utils/*.cpp visit-detector/*.cpp) +FILE(GLOB SRCS *.cpp facade/*.cpp utils/*.cpp visit-detector/*.cpp) INCLUDE(FindPkgConfig) PKG_CHECK_MODULES(PKG_MYPLACE REQUIRED ${DEPS}) @@ -20,4 +20,5 @@ TARGET_LINK_LIBRARIES(${target} ${PKG_MYPLACE_LDFLAGS} ${target_shared}) INSTALL(TARGETS ${target} DESTINATION ${CMAKE_INSTALL_LIBDIR}/${target_dir}) +ADD_SUBDIRECTORY(place) ADD_SUBDIRECTORY(visit-categer) \ No newline at end of file diff --git a/src/my-place/facade/UserPlaces.cpp b/src/my-place/facade/UserPlaces.cpp index d0ae2fb..f29da9a 100755 --- a/src/my-place/facade/UserPlaces.cpp +++ b/src/my-place/facade/UserPlaces.cpp @@ -19,8 +19,12 @@ #include #include #include "UserPlaces.h" -#include "../place/PlacesDetector.h" #include +#include + +#define SO_PATH "/usr/lib/context-service/libctx-prvd-my-place-places-detector.so" + +typedef void (*places_detector_t)(); #define __GET_PLACES_QUERY "SELECT "\ PLACE_COLUMN_CATEG_ID ", "\ @@ -41,8 +45,7 @@ ctx::UserPlaces::UserPlaces(PlaceRecogMode energyMode): __visitDetector(nullptr), - __placesDetector(nullptr), - __placesDetectorTimerId(-1) + __timerId(-1) { time_t now = std::time(nullptr); __visitDetector = new(std::nothrow) VisitDetector(now, energyMode); @@ -51,35 +54,26 @@ ctx::UserPlaces::UserPlaces(PlaceRecogMode energyMode): return; } - __placesDetector = new(std::nothrow) PlacesDetector(); - if (__placesDetector == nullptr) { - _E("Cannot initialize __placesDetector"); - return; - } - - __placesDetectorTimerId = __timerManager.setAt( // execute once every night + __timerId = __timerManager.setAt( // execute once every night PLACES_DETECTOR_TASK_START_HOUR, PLACES_DETECTOR_TASK_START_MINUTE, DayOfWeek::EVERYDAY, - __placesDetector); - if (__placesDetectorTimerId < 0) { - _E("PlacesDetector timer set FAIL"); + this); + if (__timerId < 0) { + _E("timer set FAIL"); return; } else { - _D("PlacesDetector timer set SUCCESS"); + _D("timer set SUCCESS"); } } ctx::UserPlaces::~UserPlaces() { - if (__placesDetectorTimerId >= 0) { - __timerManager.remove(__placesDetectorTimerId); - _D("PlacesDetector timer removed"); + if (__timerId >= 0) { + __timerManager.remove(__timerId); } if (__visitDetector) delete __visitDetector; - if (__placesDetector) - delete __placesDetector; }; ctx::Json ctx::UserPlaces::getPlaces() @@ -127,6 +121,26 @@ void ctx::UserPlaces::setMode(PlaceRecogMode energyMode) __visitDetector->setMode(energyMode); } +bool ctx::UserPlaces::onTimerExpired(int timerId) +{ + _D("mmastern try to detect places from UserPlaces"); + GModule *soHandle = g_module_open(SO_PATH, G_MODULE_BIND_LAZY); + IF_FAIL_RETURN_TAG(soHandle, true, _E, "%s", g_module_error()); + + gpointer symbol; + if (!g_module_symbol(soHandle, "detectPlaces", &symbol) || symbol == NULL) { + _E("mmastern %s", g_module_error()); + g_module_close(soHandle); + return true; + } + + places_detector_t detectPlaces = reinterpret_cast(symbol); + + detectPlaces(); + g_module_close(soHandle); + return true; +} + std::vector ctx::UserPlaces::__dbGetPlaces() { std::vector records; diff --git a/src/my-place/facade/UserPlaces.h b/src/my-place/facade/UserPlaces.h index 2bcf56d..3ed19d3 100644 --- a/src/my-place/facade/UserPlaces.h +++ b/src/my-place/facade/UserPlaces.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include "../visit-detector/VisitDetector.h" #include "../place/PlacesDetector.h" @@ -29,13 +30,12 @@ namespace ctx { - class UserPlaces { + class UserPlaces : public ITimerListener { private: VisitDetector *__visitDetector; - PlacesDetector *__placesDetector; DatabaseManager *__dbManager; - int __placesDetectorTimerId; + int __timerId; TimerManager __timerManager; std::vector __dbGetPlaces(); std::map __dbGetWifiAPsMap(); @@ -52,6 +52,8 @@ namespace ctx { std::vector> __getPlaces(); static Json __composeJson(std::vector> places); + bool onTimerExpired(int timerId); + public: UserPlaces(PlaceRecogMode energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE); ~UserPlaces(); diff --git a/src/my-place/place/CMakeLists.txt b/src/my-place/place/CMakeLists.txt new file mode 100644 index 0000000..fc2c120 --- /dev/null +++ b/src/my-place/place/CMakeLists.txt @@ -0,0 +1,7 @@ +SET(target "${target_prefix}-my-place-places-detector") + +FILE(GLOB SRCS *.cpp) + +ADD_LIBRARY(${target} SHARED ${SRCS}) + +INSTALL(TARGETS ${target} DESTINATION ${CMAKE_INSTALL_LIBDIR}/${target_dir}) \ No newline at end of file diff --git a/src/my-place/place/PlacesDetector.cpp b/src/my-place/place/PlacesDetector.cpp index e452a13..d43b86e 100644 --- a/src/my-place/place/PlacesDetector.cpp +++ b/src/my-place/place/PlacesDetector.cpp @@ -376,3 +376,9 @@ void ctx::PlacesDetector::__dbInsertPlace(const Place &place) _D("insert place execute query result: %s", ret ? "SUCCESS" : "FAIL"); } +extern "C" SO_EXPORT void detectPlaces() +{ + _D(""); + ctx::PlacesDetector placesDetector; + placesDetector.detectPlaces(); +} -- 2.7.4 From 4becee54a1534349678a33e7632ecac27d8681b7 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Mon, 27 Jun 2016 13:01:23 +0900 Subject: [PATCH 02/16] Remove ProviderTypes.h Change-Id: I84850a5d6429fb1d9eb04e09908b30da0bc67c3b Signed-off-by: Mu-Woong Lee --- include/ProviderList.h | 1 + include/ProviderTypes.h | 187 -------------------------------- src/my-place/PlaceRecognitionProvider.h | 3 +- 3 files changed, 2 insertions(+), 189 deletions(-) delete mode 100644 include/ProviderTypes.h diff --git a/include/ProviderList.h b/include/ProviderList.h index f1dbe3b..7218956 100644 --- a/include/ProviderList.h +++ b/include/ProviderList.h @@ -19,6 +19,7 @@ #include #include +#include #define LIB_DIRECTORY "/usr/lib/context-service/" #define LIB_PREFIX "libctx-prvd-" diff --git a/include/ProviderTypes.h b/include/ProviderTypes.h deleted file mode 100644 index ed815e3..0000000 --- a/include/ProviderTypes.h +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2015 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_PROVIDER_TYPES_H_ -#define _CONTEXT_PROVIDER_TYPES_H_ - -#include "MyPlaceTypes.h" - -/* Privileges */ -#define PRIV_ALARM "alarm.set" -#define PRIV_NETWORK "network.get" -#define PRIV_TELEPHONY "telephony" -#define PRIV_MESSAGE "message.read" -#define PRIV_CONTACT "contact.read" -#define PRIV_LOCATION "location" -#define PRIV_APP_HISTORY "apphistory.read" -#define PRIV_MEDIA_HISTORY "mediahistory.read" -#define PRIV_CALL_HISTORY "callhistory.read" - - -/* FW-wide Data Logger Parameters */ -#define LOG_RETENTION_PERIOD 7776000 /* 90 days in secs */ - - -/* FW-wide Default Values */ -#define DEFAULT_TIMESPAN 30 -#define DEFAULT_LIMIT 10 - - -/* Subjects */ -/* TODO: Cleanup the below namings */ -#define SUBJ_STATE_BATTERY "system/battery" -#define SUBJ_STATE_CHARGER "system/charger" -#define SUBJ_STATE_HEADPHONE "system/headphone" -#define SUBJ_STATE_WIFI "system/wifi" -#define SUBJ_STATE_USB "system/usb" -#define SUBJ_STATE_GPS "system/gps" -#define SUBJ_STATE_PSMODE "system/psmode" -#define SUBJ_STATE_ALARM "device/alarm" -#define SUBJ_STATE_TIME "device/time" - -#define SUBJ_STATE_CALL "social/call" -#define SUBJ_STATE_EMAIL "social/email" -#define SUBJ_STATE_MESSAGE "social/message" -#define SUBJ_STATE_CONTACTS "social/contacts" - -#define SUBJ_ACTIVITY "activity/" -#define SUBJ_ACTIVITY_IN_VEHICLE SUBJ_ACTIVITY "in_vehicle" -#define SUBJ_ACTIVITY_RUNNING SUBJ_ACTIVITY "running" -#define SUBJ_ACTIVITY_STATIONARY SUBJ_ACTIVITY "stationary" -#define SUBJ_ACTIVITY_WALKING SUBJ_ACTIVITY "walking" - -#define SUBJ_APP_STATS "stats/app/" -#define SUBJ_APP_LOGGER SUBJ_APP_STATS "logger" -#define SUBJ_APP_RECENTLY_USED SUBJ_APP_STATS "recently" -#define SUBJ_APP_FREQUENTLY_USED SUBJ_APP_STATS "often" -#define SUBJ_APP_RARELY_USED SUBJ_APP_STATS "rarely" -#define SUBJ_APP_PEAK_TIME SUBJ_APP_STATS "peak_time" -#define SUBJ_APP_COMMON_SETTING SUBJ_APP_STATS "setting" -#define SUBJ_APP_FREQUENCY SUBJ_APP_STATS "frequency" - -#define SUBJ_MEDIA_LOGGER "stats/media/logger" -#define SUBJ_MUSIC_STATS "stats/music/" -#define SUBJ_MUSIC_PEAK_TIME SUBJ_MUSIC_STATS "peak_time" -#define SUBJ_MUSIC_COMMON_SETTING SUBJ_MUSIC_STATS "setting" -#define SUBJ_MUSIC_FREQUENCY SUBJ_MUSIC_STATS "frequency" -#define SUBJ_VIDEO_STATS "stats/video/" -#define SUBJ_VIDEO_PEAK_TIME SUBJ_VIDEO_STATS "peak_time" -#define SUBJ_VIDEO_COMMON_SETTING SUBJ_VIDEO_STATS "setting" -#define SUBJ_VIDEO_FREQUENCY SUBJ_VIDEO_STATS "frequency" - -#define SUBJ_SOCIAL_STATS "stats/contact/" -#define SUBJ_SOCIAL_FREQ_ADDRESS SUBJ_SOCIAL_STATS "often" -#define SUBJ_SOCIAL_FREQUENCY SUBJ_SOCIAL_STATS "frequency" - -#define SUBJ_PLACE_GEOFENCE "place/geofence" -#define SUBJ_PLACE_DETECTION PLACE_DETECTION_SUBJECT - -#define SUBJ_CUSTOM "custom" - -/* Data & Option Keys */ -#define KEY_QUERY_RESULT "QueryResult" -#define KEY_RESULT_SIZE "ResultSize" -#define KEY_COL_ROW_ID "rowId" -#define KEY_TIMESPAN "TimeSpan" -#define KEY_START_TIME "StartTime" -#define KEY_END_TIME "EndTime" -#define KEY_LAST_TIME "LastTime" -#define KEY_TOTAL_COUNT "TotalCount" -#define KEY_AVERAGE_COUNT "AvgCount" -#define KEY_DURATION "Duration" -#define KEY_TOTAL_DURATION "TotalDuration" -#define KEY_DAY_OF_WEEK "DayOfWeek" -#define KEY_HOUR_OF_DAY "HourOfDay" -#define KEY_TIME_OF_DAY "TimeOfDay" -#define KEY_TOTAL_COUNT "TotalCount" -#define KEY_APP_ID "AppId" -#define KEY_PKG_ID "PkgId" -#define KEY_AUDIO_JACK "AudioJack" -#define KEY_SYSTEM_VOLUME "SystemVolume" -#define KEY_MEDIA_VOLUME "MediaVolume" -#define KEY_BSSID "BSSID" -#define KEY_UNIV_TIME "UTC" -#define KEY_LOCAL_TIME "LocalTime" -#define KEY_RANK "Rank" - -#define KEY_EVENT "Event" -#define KEY_STATE "State" -#define KEY_TYPE "Type" -#define KEY_LEVEL "Level" -#define KEY_ACCURACY "Accuracy" -#define KEY_BSSID "BSSID" -#define KEY_MEDIUM "Medium" -#define KEY_ADDRESS "Address" -#define KEY_IS_CONNECTED "IsConnected" -#define KEY_IS_ENABLED "IsEnabled" -#define KEY_IS_CHARGING "IsCharging" -#define KEY_DETECTED "Detected" -#define KEY_TIME_OF_DAY "TimeOfDay" -#define KEY_DAY_OF_WEEK "DayOfWeek" -#define KEY_DAY_OF_MONTH "DayOfMonth" -#define KEY_PLACE_ID "PlaceId" - - -/* Data & Option Values */ -#define VAL_TRUE 1 -#define VAL_FALSE 0 -#define VAL_ENTER "Enter" -#define VAL_EXIT "Exit" -#define VAL_DISABLED "Disabled" -#define VAL_CONNECTED "Connected" -#define VAL_UNCONNECTED "Unconnected" -#define VAL_SEARCHING "Searching" -#define VAL_EMPTY "Empty" -#define VAL_CRITICAL "Critical" -#define VAL_LOW "Low" -#define VAL_NORMAL "Normal" -#define VAL_HIGH "High" -#define VAL_FULL "Full" -#define VAL_HEADSET "Headset" -#define VAL_BLUETOOTH "Bluetooth" -#define VAL_IDLE "Idle" -#define VAL_CONNECTING "Connecting" -#define VAL_CONNECTED "Connected" -#define VAL_HELD "Held" -#define VAL_DIALING "Dialing" -#define VAL_VOICE "Voice" -#define VAL_VIDEO "Video" -#define VAL_SENT "Sent" -#define VAL_RECEIVED "Received" -#define VAL_SMS "SMS" -#define VAL_MMS "MMS" -#define VAL_MY_PROFILE "MyProfile" -#define VAL_PERSON "Person" -#define VAL_CHANGED "Changed" -#define VAL_DETECTED "Detected" -#define VAL_UNCERTAIN "Uncertain" -#define VAL_IN "In" -#define VAL_OUT "Out" - -#define VAL_ACTIVE VAL_CONNECTED -#define VAL_ALERTING VAL_CONNECTING -#define VAL_INCOMING VAL_CONNECTING - - -/* Json Formats */ -#define TRIG_DEF_RANK "\"Rank\":{\"type\":\"integer\",\"min\":1}" -#define TRIG_DEF_TOTAL_COUNT "\"TotalCount\":{\"type\":\"integer\",\"min\":0}" -#define TRIG_DEF_TIME_OF_DAY "\"TimeOfDay\":{\"type\":\"string\"}" -#define TRIG_DEF_DAY_OF_WEEK "\"DayOfWeek\":{\"type\":\"string\",\"values\":[\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\",\"Weekday\",\"Weekend\"]}" -#define TRIG_BOOL_ITEM_DEF(sbj) "\"" sbj "\":{\"type\":\"integer\",\"min\":0,\"max\":1}" - - -#endif /* _CONTEXT_PROVIDER_TYPES_H_ */ diff --git a/src/my-place/PlaceRecognitionProvider.h b/src/my-place/PlaceRecognitionProvider.h index af1fba3..4a3a96c 100644 --- a/src/my-place/PlaceRecognitionProvider.h +++ b/src/my-place/PlaceRecognitionProvider.h @@ -18,9 +18,8 @@ #define _CONTEXT_PLACE_RECOGNITION_H_ #include -#include "MyPlaceTypes.h" +#include #include "facade/UserPlaces.h" -#include "ProviderTypes.h" namespace ctx { -- 2.7.4 From b988f7a78ace4696d92067bedae4a4b0cf8e5098 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Mon, 27 Jun 2016 13:33:19 +0900 Subject: [PATCH 03/16] Add sensor recorder provides (pedometer & pressure supported) Change-Id: Ib1177eb9b595b9b1bdc3b10f3b010b984c2cb6fc Signed-off-by: Mu-Woong Lee --- include/ProviderList.h | 2 + packaging/context-provider.spec | 3 +- src/CMakeLists.txt | 3 +- src/sensor/CMakeLists.txt | 19 +++++ src/sensor/ClientInfo.cpp | 159 ++++++++++++++++++++++++++++++++++++++++ src/sensor/ClientInfo.h | 45 ++++++++++++ src/sensor/CreateProvider.cpp | 30 ++++++++ src/sensor/Pedometer.cpp | 54 ++++++++++++++ src/sensor/Pedometer.h | 37 ++++++++++ src/sensor/PedometerLogger.cpp | 158 +++++++++++++++++++++++++++++++++++++++ src/sensor/PedometerLogger.h | 53 ++++++++++++++ src/sensor/PedometerQuerier.cpp | 71 ++++++++++++++++++ src/sensor/PedometerQuerier.h | 34 +++++++++ src/sensor/Pressure.cpp | 49 +++++++++++++ src/sensor/Pressure.h | 36 +++++++++ src/sensor/PressureLogger.cpp | 104 ++++++++++++++++++++++++++ src/sensor/PressureLogger.h | 45 ++++++++++++ src/sensor/PressureQuerier.cpp | 92 +++++++++++++++++++++++ src/sensor/PressureQuerier.h | 35 +++++++++ src/sensor/Querier.cpp | 84 +++++++++++++++++++++ src/sensor/Querier.h | 49 +++++++++++++ src/sensor/SensorLogger.cpp | 82 +++++++++++++++++++++ src/sensor/SensorLogger.h | 45 ++++++++++++ src/sensor/SensorProvider.cpp | 154 ++++++++++++++++++++++++++++++++++++++ src/sensor/SensorProvider.h | 50 +++++++++++++ src/sensor/SensorProxy.cpp | 124 +++++++++++++++++++++++++++++++ src/sensor/SensorProxy.h | 60 +++++++++++++++ src/sensor/TypesInternal.h | 40 ++++++++++ 28 files changed, 1715 insertions(+), 2 deletions(-) create mode 100644 src/sensor/CMakeLists.txt create mode 100644 src/sensor/ClientInfo.cpp create mode 100644 src/sensor/ClientInfo.h create mode 100644 src/sensor/CreateProvider.cpp create mode 100644 src/sensor/Pedometer.cpp create mode 100644 src/sensor/Pedometer.h create mode 100644 src/sensor/PedometerLogger.cpp create mode 100644 src/sensor/PedometerLogger.h create mode 100644 src/sensor/PedometerQuerier.cpp create mode 100644 src/sensor/PedometerQuerier.h create mode 100644 src/sensor/Pressure.cpp create mode 100644 src/sensor/Pressure.h create mode 100644 src/sensor/PressureLogger.cpp create mode 100644 src/sensor/PressureLogger.h create mode 100644 src/sensor/PressureQuerier.cpp create mode 100644 src/sensor/PressureQuerier.h create mode 100644 src/sensor/Querier.cpp create mode 100644 src/sensor/Querier.h create mode 100644 src/sensor/SensorLogger.cpp create mode 100644 src/sensor/SensorLogger.h create mode 100644 src/sensor/SensorProvider.cpp create mode 100644 src/sensor/SensorProvider.h create mode 100644 src/sensor/SensorProxy.cpp create mode 100644 src/sensor/SensorProxy.h create mode 100644 src/sensor/TypesInternal.h diff --git a/include/ProviderList.h b/include/ProviderList.h index 7218956..a159c44 100644 --- a/include/ProviderList.h +++ b/include/ProviderList.h @@ -20,6 +20,7 @@ #include #include #include +#include #define LIB_DIRECTORY "/usr/lib/context-service/" #define LIB_PREFIX "libctx-prvd-" @@ -42,6 +43,7 @@ const struct { {SUBJ_VIDEO_STATS, "media-stats"}, {SUBJ_STATE_MESSAGE, "message"}, {SUBJ_PLACE_DETECTION, "my-place"}, + {SUBJ_SENSOR, "sensor"}, {SUBJ_SOCIAL_STATS, "social-stats"}, {SUBJ_STATE_BATTERY, "system"}, {SUBJ_STATE_CHARGER, "system"}, diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index 4af42f5..36421d4 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -28,7 +28,8 @@ BuildRequires: pkgconfig(pkgmgr-info) BuildRequires: pkgconfig(capi-media-sound-manager) BuildRequires: pkgconfig(capi-network-bluetooth) BuildRequires: pkgconfig(capi-network-wifi) -BuildRequires: pkgconfig(libcore-context-manager) +BuildRequires: pkgconfig(sensor) +BuildRequires: pkgconfig(motion) %if "%{?BUILD_PROFILE}" == "mobile" BuildRequires: pkgconfig(msg-service) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 967c384..3dfad81 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -8,6 +8,7 @@ ADD_SUBDIRECTORY(activity) ADD_SUBDIRECTORY(app-stats) ADD_SUBDIRECTORY(custom) ADD_SUBDIRECTORY(headphone) +ADD_SUBDIRECTORY(sensor) ADD_SUBDIRECTORY(system) ADD_SUBDIRECTORY(time) ADD_SUBDIRECTORY(wifi) @@ -21,4 +22,4 @@ ADD_SUBDIRECTORY(media-stats) ADD_SUBDIRECTORY(message) #ADD_SUBDIRECTORY(my-place) ADD_SUBDIRECTORY(social-stats) -ENDIF("${PROFILE}" STREQUAL "mobile") +ENDIF("${PROFILE}" STREQUAL "mobile") \ No newline at end of file diff --git a/src/sensor/CMakeLists.txt b/src/sensor/CMakeLists.txt new file mode 100644 index 0000000..c00256a --- /dev/null +++ b/src/sensor/CMakeLists.txt @@ -0,0 +1,19 @@ +SET(target "${target_prefix}-sensor") + +SET(DEPS ${DEPS} + sensor +) + +FILE(GLOB SRCS *.cpp) + +INCLUDE(FindPkgConfig) +PKG_CHECK_MODULES(PKG_SENSOR REQUIRED ${DEPS}) + +FOREACH(flag ${PKG_SENSOR_CFLAGS}) + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}") +ENDFOREACH(flag) + +ADD_LIBRARY(${target} SHARED ${SRCS}) +TARGET_LINK_LIBRARIES(${target} ${PKG_SENSOR_LDFLAGS} ${target_shared}) + +INSTALL(TARGETS ${target} DESTINATION ${CMAKE_INSTALL_LIBDIR}/${target_dir}) diff --git a/src/sensor/ClientInfo.cpp b/src/sensor/ClientInfo.cpp new file mode 100644 index 0000000..6a94f01 --- /dev/null +++ b/src/sensor/ClientInfo.cpp @@ -0,0 +1,159 @@ +/* + * 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" + +using namespace ctx; + +unsigned int ClientInfo::__refCnt = 0; +DatabaseManager *ClientInfo::__dbMgr = NULL; + +ClientInfo::ClientInfo() +{ + ++__refCnt; + + if (__dbMgr) + return; + + __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; +} + +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 (auto 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; +} diff --git a/src/sensor/ClientInfo.h b/src/sensor/ClientInfo.h new file mode 100644 index 0000000..a52cd27 --- /dev/null +++ b/src/sensor/ClientInfo.h @@ -0,0 +1,45 @@ +/* + * 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 + +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); + + private: + static unsigned int __refCnt; + static DatabaseManager *__dbMgr; + }; +} + +#endif /* _CONTEXT_CLIENT_INFO_H_ */ diff --git a/src/sensor/CreateProvider.cpp b/src/sensor/CreateProvider.cpp new file mode 100644 index 0000000..47d5ee9 --- /dev/null +++ b/src/sensor/CreateProvider.cpp @@ -0,0 +1,30 @@ +/* + * 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.h" +#include "Pressure.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); + + return NULL; +} diff --git a/src/sensor/Pedometer.cpp b/src/sensor/Pedometer.cpp new file mode 100644 index 0000000..cac1e89 --- /dev/null +++ b/src/sensor/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/sensor/Pedometer.h b/src/sensor/Pedometer.h new file mode 100644 index 0000000..d4773fe --- /dev/null +++ b/src/sensor/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/sensor/PedometerLogger.cpp b/src/sensor/PedometerLogger.cpp new file mode 100644 index 0000000..b091e58 --- /dev/null +++ b/src/sensor/PedometerLogger.cpp @@ -0,0 +1,158 @@ +/* + * 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 "ClientInfo.h" +#include "PedometerLogger.h" + +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() +{ +} + +bool PedometerLogger::start() +{ + if (SensorProxy::isRunning()) + return true; + + _I(GREEN("Start to record")); + + if (SensorProxy::start()) { + flush(); + return true; + } + + return false; +} + +void PedometerLogger::stop() +{ + _I(GREEN("Stop recording")); + + SensorProxy::stop(); + __firstEvent = true; +} + +void PedometerLogger::onEvent(sensor_data_t *eventData) +{ + sensor_pedometer_data_t *pedometerData = reinterpret_cast(eventData); + uint64_t timestamp = getTime(); + + if (__firstEvent) { + _D("Baseline event"); + __firstEvent = false; + } else if (pedometerData->diffs_count == 0) { + _D("Single event"); + __recordSingle(pedometerData, timestamp); + } else { + _D("Batch event"); + __recordBatch(pedometerData, timestamp); + } + + __baseline.timestamp = timestamp; + __baseline.walkSteps = eventData->values[1]; + __baseline.runSteps = eventData->values[2]; + __baseline.distance = eventData->values[3]; + __baseline.calories = eventData->values[4]; + + _D("Baseline: %u, %u, %.3f, %.3f", + __baseline.walkSteps, __baseline.runSteps, __baseline.distance, __baseline.calories); + + removeExpired(SUBJ_SENSOR_PEDOMETER, PEDOMETER_RECORD, KEY_END_TIME); +} + +void PedometerLogger::__recordSingle(sensor_pedometer_data_t *eventData, uint64_t timestamp) +{ + DataRecord record; + record.walkSteps = static_cast(eventData->values[1]) - __baseline.walkSteps; + record.runSteps = static_cast(eventData->values[2]) - __baseline.runSteps; + record.distance = eventData->values[3] - __baseline.distance; + record.calories = eventData->values[4] - __baseline.calories; + + IF_FAIL_VOID_TAG(record.walkSteps + record.runSteps > 0, _D, "Skipping zero-count event"); + + 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, timestamp, record.walkSteps, record.runSteps, record.distance, record.calories); + executeQuery(query); + sqlite3_free(query); +} + +void PedometerLogger::__recordBatch(sensor_pedometer_data_t *eventData, uint64_t timestamp) +{ + 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), "(%llu, %llu, %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()); +} diff --git a/src/sensor/PedometerLogger.h b/src/sensor/PedometerLogger.h new file mode 100644 index 0000000..e1d021b --- /dev/null +++ b/src/sensor/PedometerLogger.h @@ -0,0 +1,53 @@ +/* + * 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(); + + 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); + + bool __firstEvent; + DataRecord __baseline; + }; +} + +#endif /* __CONTEXT_PEDOMETER_LOGGER_H__ */ diff --git a/src/sensor/PedometerQuerier.cpp b/src/sensor/PedometerQuerier.cpp new file mode 100644 index 0000000..37fa7de --- /dev/null +++ b/src/sensor/PedometerQuerier.cpp @@ -0,0 +1,71 @@ +/* + * 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 + +using namespace ctx; + +PedometerQuerier::PedometerQuerier(ContextProvider *provider, Json option) : + Querier(provider, option) +{ +} + +PedometerQuerier::~PedometerQuerier() +{ +} + +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 ROUND((" KEY_END_TIME " - %llu) / %llu + 0.5)" \ + " 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/sensor/PedometerQuerier.h b/src/sensor/PedometerQuerier.h new file mode 100644 index 0000000..5cdc506 --- /dev/null +++ b/src/sensor/PedometerQuerier.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_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 query(int startTime, int endTime); + int query(int startTime, int endTime, int anchor, int interval); + }; +} + +#endif /* __CONTEXT_PEDOMETER_QUERIER_H__ */ diff --git a/src/sensor/Pressure.cpp b/src/sensor/Pressure.cpp new file mode 100644 index 0000000..b50caa2 --- /dev/null +++ b/src/sensor/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/sensor/Pressure.h b/src/sensor/Pressure.h new file mode 100644 index 0000000..d12efac --- /dev/null +++ b/src/sensor/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/sensor/PressureLogger.cpp b/src/sensor/PressureLogger.cpp new file mode 100644 index 0000000..0dcaca9 --- /dev/null +++ b/src/sensor/PressureLogger.cpp @@ -0,0 +1,104 @@ +/* + * 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 "ClientInfo.h" +#include "PressureLogger.h" + +#define INSERTION_THRESHOLD 20000 +#define SAMPLING_INTERVAL 60000 +#define BATCH_LATENCY INT_MAX +#define MAX_QUERY_LENGTH 1000 + +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() +{ +} + +bool PressureLogger::start() +{ + if (SensorProxy::isRunning()) + return true; + + _I(GREEN("Start to record")); + + __lastInsertionTime = getTime(); + __resetInsertionQuery(); + + return SensorProxy::start(); +} + +void PressureLogger::stop() +{ + _I(GREEN("Stop recording")); + + SensorProxy::stop(); +} + +void PressureLogger::onEvent(sensor_data_t *eventData) +{ + uint64_t receivedTime = getTime(); + __record(eventData, receivedTime); + removeExpired(SUBJ_SENSOR_PRESSURE, PRESSURE_RECORD, KEY_UNIV_TIME); +} + +void PressureLogger::__record(sensor_data_t *eventData, uint64_t receivedTime) +{ + char buffer[64]; + g_snprintf(buffer, sizeof(buffer), "(%llu, %.5f),", + getTime(eventData->timestamp), eventData->values[0]); + + __insertionQuery += buffer; + + if (receivedTime - __lastInsertionTime < INSERTION_THRESHOLD && __insertionQuery.size() < MAX_QUERY_LENGTH) + return; + + __insertionQuery.resize(__insertionQuery.size() - 1); + if (__insertionQuery.at(__insertionQuery.size() - 1) == ')') + executeQuery(__insertionQuery.c_str()); + + __lastInsertionTime = receivedTime; + __resetInsertionQuery(); +} + +void PressureLogger::__resetInsertionQuery() +{ + __insertionQuery = + "INSERT INTO " PRESSURE_RECORD \ + " (" KEY_UNIV_TIME ", " KEY_PRESSURE ") VALUES "; +} diff --git a/src/sensor/PressureLogger.h b/src/sensor/PressureLogger.h new file mode 100644 index 0000000..45d0c68 --- /dev/null +++ b/src/sensor/PressureLogger.h @@ -0,0 +1,45 @@ +/* + * 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(); + + protected: + void onEvent(sensor_data_t *eventData); + + private: + void __record(sensor_data_t *eventData, uint64_t receivedTime); + void __resetInsertionQuery(); + + uint64_t __lastInsertionTime; + std::string __insertionQuery; + }; +} + +#endif /* __CONTEXT_PRESSURE_LOGGER_H__ */ diff --git a/src/sensor/PressureQuerier.cpp b/src/sensor/PressureQuerier.cpp new file mode 100644 index 0000000..5e01662 --- /dev/null +++ b/src/sensor/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 ROUND((" KEY_UNIV_TIME " - %llu) / %llu + 0.5)" \ + " 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/sensor/PressureQuerier.h b/src/sensor/PressureQuerier.h new file mode 100644 index 0000000..be1788c --- /dev/null +++ b/src/sensor/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/sensor/Querier.cpp b/src/sensor/Querier.cpp new file mode 100644 index 0000000..7cc0b9b --- /dev/null +++ b/src/sensor/Querier.cpp @@ -0,0 +1,84 @@ +/* + * 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) +{ + return ERR_INVALID_PARAMETER; +} + +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/sensor/Querier.h b/src/sensor/Querier.h new file mode 100644 index 0000000..0eed203 --- /dev/null +++ b/src/sensor/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/sensor/SensorLogger.cpp b/src/sensor/SensorLogger.cpp new file mode 100644 index 0000000..e2462ab --- /dev/null +++ b/src/sensor/SensorLogger.cpp @@ -0,0 +1,82 @@ +/* + * 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 +#include +#include "TypesInternal.h" +#include "SensorLogger.h" + +using namespace ctx; + +SensorLogger::SensorLogger() : + __lastRemovalTime(0) +{ +} + +SensorLogger::~SensorLogger() +{ +} + +uint64_t SensorLogger::getTime() +{ + struct timeval tv; + double timestamp; + + gettimeofday(&tv, NULL); + timestamp = tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0; + return static_cast(round(timestamp)); +} + +uint64_t SensorLogger::getTime(unsigned long long monotonic) +{ + struct timespec ts; + double timestamp; + uint64_t currentTime = getTime(); + + if (abs(currentTime / 1000 - monotonic / 1000000) < SECONDS_PER_DAY) + return static_cast(round(monotonic / 1000.0)); + + clock_gettime(CLOCK_MONOTONIC, &ts); + timestamp = static_cast(currentTime) - (ts.tv_sec * 1000000000.0 + ts.tv_nsec) / 1000000.0 + monotonic / 1000.0; + return static_cast(round(timestamp)); +} + +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 = 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/sensor/SensorLogger.h b/src/sensor/SensorLogger.h new file mode 100644 index 0000000..eef4df3 --- /dev/null +++ b/src/sensor/SensorLogger.h @@ -0,0 +1,45 @@ +/* + * 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; + + protected: + uint64_t getTime(); + uint64_t getTime(unsigned long long monotonic); + 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/sensor/SensorProvider.cpp b/src/sensor/SensorProvider.cpp new file mode 100644 index 0000000..e205246 --- /dev/null +++ b/src/sensor/SensorProvider.cpp @@ -0,0 +1,154 @@ +/* + * 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; + +SensorProvider::SensorProvider(const char *subject) : + ContextProvider(subject), + sensorLogger(NULL) +{ +} + +SensorProvider::~SensorProvider() +{ + 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); + + 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; + 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); + + if (data.get(NULL, KEY_RETENTION, &retentionPeriod)) + retentionPeriod *= SECONDS_PER_HOUR; + + /* TODO: remove the operation & pkg id from the json */ + + if (operation == VAL_START) + return __addClient(pkgId, retentionPeriod, data); + else if (operation == VAL_STOP) + return __removeClient(pkgId); + + return ERR_NOT_SUPPORTED; +} + +int SensorProvider::__addClient(std::string pkgId, int retentionPeriod, Json option) +{ + Json tmp; + int ret; + + /* 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_FAIL_RETURN(ret != ERR_NONE, ERR_NONE); + IF_FAIL_RETURN(ret == ERR_NO_DATA, ERR_OPERATION_FAILED); + + /* Stop listening */ + sensorLogger->stop(); + + return ERR_NONE; +} diff --git a/src/sensor/SensorProvider.h b/src/sensor/SensorProvider.h new file mode 100644 index 0000000..4a1cf5b --- /dev/null +++ b/src/sensor/SensorProvider.h @@ -0,0 +1,50 @@ +/* + * 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 "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); + + protected: + virtual Querier* getQuerier(Json option) = 0; + + SensorLogger *sensorLogger; + + private: + int __addClient(std::string pkgId, int retentionPeriod, Json option); + int __removeClient(std::string pkgId); + + ClientInfo __clientInfo; + }; +} + +#endif /* _CONTEXT_SENSOR_PROVIDER_H_ */ diff --git a/src/sensor/SensorProxy.cpp b/src/sensor/SensorProxy.cpp new file mode 100644 index 0000000..f927ec1 --- /dev/null +++ b/src/sensor/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() +{ + stop(); +} + +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::start() +{ + _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::stop() +{ + 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/sensor/SensorProxy.h b/src/sensor/SensorProxy.h new file mode 100644 index 0000000..d264668 --- /dev/null +++ b/src/sensor/SensorProxy.h @@ -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. + * + */ + +#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); + + virtual bool start(); + virtual void stop(); + 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); + + bool isRunning(); + + 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/sensor/TypesInternal.h b/src/sensor/TypesInternal.h new file mode 100644 index 0000000..a39a452 --- /dev/null +++ b/src/sensor/TypesInternal.h @@ -0,0 +1,40 @@ +/* + * 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 PEDOMETER_RECORD "SensorPedometerRecord" +#define PRESSURE_RECORD "SensorPressureRecord" +#define CLIENT_INFO "SensorClientInfo" + +/* Privileges */ +#define PRIV_HEALTHINFO "healthinfo" + +/* Constants */ +#define SECONDS_PER_MINUTE 60 +#define SECONDS_PER_HOUR 3600 +#define SECONDS_PER_DAY 86400 + +/* Default Parameters */ +#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) + +#endif /* __CONTEXT_SENSOR_RECORDER_TYPES_INTERNAL_H__ */ -- 2.7.4 From bc91cb664c708fa9e45ce3247a768607ab6a962b Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Mon, 27 Jun 2016 15:30:35 +0900 Subject: [PATCH 04/16] wifi: wifi monitoring is not initiated automatically Change-Id: I882ffdf3c1cb7a0281fa1909541e81952a068768 Signed-off-by: Mu-Woong Lee --- src/wifi/Wifi.cpp | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/src/wifi/Wifi.cpp b/src/wifi/Wifi.cpp index 9ebcdfe..ad5cc87 100644 --- a/src/wifi/Wifi.cpp +++ b/src/wifi/Wifi.cpp @@ -26,17 +26,10 @@ WifiStateProvider::WifiStateProvider() : __isActivated(false), __connState(WIFI_CONNECTION_STATE_FAILURE) { - IF_FAIL_VOID_TAG(__startMonitor(), _W, "WiFi monitor initialization failed"); - - if (!__getCurrentState()) { - __stopMonitor(); - _W("Getting current WiFi status failed"); - } } WifiStateProvider::~WifiStateProvider() { - __stopMonitor(); } void WifiStateProvider::getPrivilege(std::vector &privilege) @@ -163,22 +156,19 @@ void WifiStateProvider::__stopMonitor() int WifiStateProvider::subscribe() { -#if 0 IF_FAIL_RETURN(__startMonitor(), ERR_OPERATION_FAILED); if (!__getCurrentState()) { __stopMonitor(); return ERR_OPERATION_FAILED; } -#endif return ERR_NONE; } int WifiStateProvider::unsubscribe() { -#if 0 __stopMonitor(); -#endif + return ERR_NONE; } -- 2.7.4 From c1579c711c26cae3b219185937f3a300c097ea68 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Mon, 27 Jun 2016 15:31:02 +0900 Subject: [PATCH 05/16] custom: fix the package id json key Change-Id: I84f225136666b8c9faede8181c44623ea073dab0 Signed-off-by: Mu-Woong Lee --- src/custom/CustomManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/custom/CustomManager.cpp b/src/custom/CustomManager.cpp index 1f47c13..90dfb32 100644 --- a/src/custom/CustomManager.cpp +++ b/src/custom/CustomManager.cpp @@ -70,7 +70,7 @@ int CustomManager::write(Json data, Json *requestResult) std::string packageId; std::string name; - data.get(NULL, CUSTOM_KEY_PACKAGE_ID, &packageId); + data.get(NULL, KEY_CLIENT_PKG_ID, &packageId); data.get(NULL, CUSTOM_KEY_NAME, &name); std::string subj = std::string(SUBJ_CUSTOM) + CUSTOM_SEPERATOR + packageId + CUSTOM_SEPERATOR + name; -- 2.7.4 From 48361f3f3a2556b8f9af0f8c9af30bc04d298392 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Mon, 27 Jun 2016 15:31:35 +0900 Subject: [PATCH 06/16] Disable app usage logging on Wearable profile Change-Id: I883d8daa8cfb35daf77489a70e65d1b678871da9 Signed-off-by: Mu-Woong Lee --- packaging/context-provider.spec | 12 ++++++------ src/CMakeLists.txt | 4 ++-- src/activity/CMakeLists.txt | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index 36421d4..97e1b3b 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -1,6 +1,6 @@ Name: context-provider Summary: Context Provider -Version: 0.9.1 +Version: 0.9.2 Release: 1 Group: Service/Context License: Apache-2.0 @@ -20,11 +20,6 @@ BuildRequires: pkgconfig(vconf) BuildRequires: pkgconfig(capi-system-info) BuildRequires: pkgconfig(capi-system-device) BuildRequires: pkgconfig(capi-system-runtime-info) -BuildRequires: pkgconfig(capi-appfw-package-manager) -BuildRequires: pkgconfig(capi-appfw-application) -BuildRequires: pkgconfig(capi-appfw-app-manager) -BuildRequires: pkgconfig(pkgmgr) -BuildRequires: pkgconfig(pkgmgr-info) BuildRequires: pkgconfig(capi-media-sound-manager) BuildRequires: pkgconfig(capi-network-bluetooth) BuildRequires: pkgconfig(capi-network-wifi) @@ -32,6 +27,11 @@ BuildRequires: pkgconfig(sensor) BuildRequires: pkgconfig(motion) %if "%{?BUILD_PROFILE}" == "mobile" +BuildRequires: pkgconfig(capi-appfw-package-manager) +BuildRequires: pkgconfig(capi-appfw-application) +BuildRequires: pkgconfig(capi-appfw-app-manager) +BuildRequires: pkgconfig(pkgmgr) +BuildRequires: pkgconfig(pkgmgr-info) BuildRequires: pkgconfig(msg-service) BuildRequires: pkgconfig(contacts-service2) BuildRequires: pkgconfig(tapi) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3dfad81..bb6ed1d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -5,7 +5,6 @@ SET(DEPS ADD_SUBDIRECTORY(shared) ADD_SUBDIRECTORY(activity) -ADD_SUBDIRECTORY(app-stats) ADD_SUBDIRECTORY(custom) ADD_SUBDIRECTORY(headphone) ADD_SUBDIRECTORY(sensor) @@ -14,6 +13,7 @@ ADD_SUBDIRECTORY(time) ADD_SUBDIRECTORY(wifi) IF("${PROFILE}" STREQUAL "mobile") +ADD_SUBDIRECTORY(app-stats) ADD_SUBDIRECTORY(call) ADD_SUBDIRECTORY(contacts) ADD_SUBDIRECTORY(email) @@ -22,4 +22,4 @@ ADD_SUBDIRECTORY(media-stats) ADD_SUBDIRECTORY(message) #ADD_SUBDIRECTORY(my-place) ADD_SUBDIRECTORY(social-stats) -ENDIF("${PROFILE}" STREQUAL "mobile") \ No newline at end of file +ENDIF("${PROFILE}" STREQUAL "mobile") diff --git a/src/activity/CMakeLists.txt b/src/activity/CMakeLists.txt index 48192c3..7ce6d10 100644 --- a/src/activity/CMakeLists.txt +++ b/src/activity/CMakeLists.txt @@ -1,7 +1,7 @@ SET(target "${target_prefix}-activity") SET(DEPS ${DEPS} - libcore-context-manager + motion ) FILE(GLOB SRCS *.cpp) -- 2.7.4 From 909148fda924fa608c8f5b154c483a447b484492 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Thu, 30 Jun 2016 10:18:02 +0900 Subject: [PATCH 07/16] sensor: reorganize the folder structure Sub-folders for pedometer & pressure recorders are created. Change-Id: Ic4adeb1d52b257f5228e4176886841ef88f95d4c Signed-off-by: Mu-Woong Lee --- src/sensor/CMakeLists.txt | 2 +- src/sensor/CreateProvider.cpp | 4 ++-- src/sensor/{ => pedometer}/Pedometer.cpp | 2 +- src/sensor/{ => pedometer}/Pedometer.h | 2 +- src/sensor/{ => pedometer}/PedometerLogger.cpp | 4 ++-- src/sensor/{ => pedometer}/PedometerLogger.h | 4 ++-- src/sensor/{ => pedometer}/PedometerQuerier.cpp | 2 +- src/sensor/{ => pedometer}/PedometerQuerier.h | 2 +- src/sensor/{ => pressure}/Pressure.cpp | 2 +- src/sensor/{ => pressure}/Pressure.h | 2 +- src/sensor/{ => pressure}/PressureLogger.cpp | 4 ++-- src/sensor/{ => pressure}/PressureLogger.h | 4 ++-- src/sensor/{ => pressure}/PressureQuerier.cpp | 2 +- src/sensor/{ => pressure}/PressureQuerier.h | 2 +- 14 files changed, 19 insertions(+), 19 deletions(-) rename src/sensor/{ => pedometer}/Pedometer.cpp (98%) rename src/sensor/{ => pedometer}/Pedometer.h (97%) rename src/sensor/{ => pedometer}/PedometerLogger.cpp (98%) rename src/sensor/{ => pedometer}/PedometerLogger.h (95%) rename src/sensor/{ => pedometer}/PedometerQuerier.cpp (98%) rename src/sensor/{ => pedometer}/PedometerQuerier.h (97%) rename src/sensor/{ => pressure}/Pressure.cpp (97%) rename src/sensor/{ => pressure}/Pressure.h (96%) rename src/sensor/{ => pressure}/PressureLogger.cpp (97%) rename src/sensor/{ => pressure}/PressureLogger.h (95%) rename src/sensor/{ => pressure}/PressureQuerier.cpp (98%) rename src/sensor/{ => pressure}/PressureQuerier.h (97%) diff --git a/src/sensor/CMakeLists.txt b/src/sensor/CMakeLists.txt index c00256a..5c489b3 100644 --- a/src/sensor/CMakeLists.txt +++ b/src/sensor/CMakeLists.txt @@ -4,7 +4,7 @@ SET(DEPS ${DEPS} sensor ) -FILE(GLOB SRCS *.cpp) +FILE(GLOB_RECURSE SRCS *.cpp) INCLUDE(FindPkgConfig) PKG_CHECK_MODULES(PKG_SENSOR REQUIRED ${DEPS}) diff --git a/src/sensor/CreateProvider.cpp b/src/sensor/CreateProvider.cpp index 47d5ee9..141ea0e 100644 --- a/src/sensor/CreateProvider.cpp +++ b/src/sensor/CreateProvider.cpp @@ -16,8 +16,8 @@ #include #include -#include "Pedometer.h" -#include "Pressure.h" +#include "pedometer/Pedometer.h" +#include "pressure/Pressure.h" using namespace ctx; diff --git a/src/sensor/Pedometer.cpp b/src/sensor/pedometer/Pedometer.cpp similarity index 98% rename from src/sensor/Pedometer.cpp rename to src/sensor/pedometer/Pedometer.cpp index cac1e89..8752754 100644 --- a/src/sensor/Pedometer.cpp +++ b/src/sensor/pedometer/Pedometer.cpp @@ -16,7 +16,7 @@ #include #include -#include "TypesInternal.h" +#include "../TypesInternal.h" #include "PedometerLogger.h" #include "PedometerQuerier.h" #include "Pedometer.h" diff --git a/src/sensor/Pedometer.h b/src/sensor/pedometer/Pedometer.h similarity index 97% rename from src/sensor/Pedometer.h rename to src/sensor/pedometer/Pedometer.h index d4773fe..7fee01f 100644 --- a/src/sensor/Pedometer.h +++ b/src/sensor/pedometer/Pedometer.h @@ -17,7 +17,7 @@ #ifndef __CONTEXT_PEDOMETER_PROVIDER_H__ #define __CONTEXT_PEDOMETER_PROVIDER_H__ -#include "SensorProvider.h" +#include "../SensorProvider.h" namespace ctx { diff --git a/src/sensor/PedometerLogger.cpp b/src/sensor/pedometer/PedometerLogger.cpp similarity index 98% rename from src/sensor/PedometerLogger.cpp rename to src/sensor/pedometer/PedometerLogger.cpp index b091e58..ed73b2a 100644 --- a/src/sensor/PedometerLogger.cpp +++ b/src/sensor/pedometer/PedometerLogger.cpp @@ -16,8 +16,8 @@ #include #include -#include "TypesInternal.h" -#include "ClientInfo.h" +#include "../TypesInternal.h" +#include "../ClientInfo.h" #include "PedometerLogger.h" using namespace ctx; diff --git a/src/sensor/PedometerLogger.h b/src/sensor/pedometer/PedometerLogger.h similarity index 95% rename from src/sensor/PedometerLogger.h rename to src/sensor/pedometer/PedometerLogger.h index e1d021b..57832f9 100644 --- a/src/sensor/PedometerLogger.h +++ b/src/sensor/pedometer/PedometerLogger.h @@ -17,8 +17,8 @@ #ifndef __CONTEXT_PEDOMETER_LOGGER_H__ #define __CONTEXT_PEDOMETER_LOGGER_H__ -#include "SensorLogger.h" -#include "SensorProxy.h" +#include "../SensorLogger.h" +#include "../SensorProxy.h" namespace ctx { diff --git a/src/sensor/PedometerQuerier.cpp b/src/sensor/pedometer/PedometerQuerier.cpp similarity index 98% rename from src/sensor/PedometerQuerier.cpp rename to src/sensor/pedometer/PedometerQuerier.cpp index 37fa7de..020e868 100644 --- a/src/sensor/PedometerQuerier.cpp +++ b/src/sensor/pedometer/PedometerQuerier.cpp @@ -16,7 +16,7 @@ #include #include -#include "TypesInternal.h" +#include "../TypesInternal.h" #include "PedometerQuerier.h" #define PROJECTION \ diff --git a/src/sensor/PedometerQuerier.h b/src/sensor/pedometer/PedometerQuerier.h similarity index 97% rename from src/sensor/PedometerQuerier.h rename to src/sensor/pedometer/PedometerQuerier.h index 5cdc506..0cce36b 100644 --- a/src/sensor/PedometerQuerier.h +++ b/src/sensor/pedometer/PedometerQuerier.h @@ -17,7 +17,7 @@ #ifndef __CONTEXT_PEDOMETER_QUERIER_H__ #define __CONTEXT_PEDOMETER_QUERIER_H__ -#include "Querier.h" +#include "../Querier.h" namespace ctx { diff --git a/src/sensor/Pressure.cpp b/src/sensor/pressure/Pressure.cpp similarity index 97% rename from src/sensor/Pressure.cpp rename to src/sensor/pressure/Pressure.cpp index b50caa2..76b60f4 100644 --- a/src/sensor/Pressure.cpp +++ b/src/sensor/pressure/Pressure.cpp @@ -16,7 +16,7 @@ #include #include -#include "TypesInternal.h" +#include "../TypesInternal.h" #include "PressureLogger.h" #include "PressureQuerier.h" #include "Pressure.h" diff --git a/src/sensor/Pressure.h b/src/sensor/pressure/Pressure.h similarity index 96% rename from src/sensor/Pressure.h rename to src/sensor/pressure/Pressure.h index d12efac..419cfba 100644 --- a/src/sensor/Pressure.h +++ b/src/sensor/pressure/Pressure.h @@ -17,7 +17,7 @@ #ifndef __CONTEXT_PRESSURE_PROVIDER_H__ #define __CONTEXT_PRESSURE_PROVIDER_H__ -#include "SensorProvider.h" +#include "../SensorProvider.h" namespace ctx { diff --git a/src/sensor/PressureLogger.cpp b/src/sensor/pressure/PressureLogger.cpp similarity index 97% rename from src/sensor/PressureLogger.cpp rename to src/sensor/pressure/PressureLogger.cpp index 0dcaca9..e301165 100644 --- a/src/sensor/PressureLogger.cpp +++ b/src/sensor/pressure/PressureLogger.cpp @@ -16,8 +16,8 @@ #include #include -#include "TypesInternal.h" -#include "ClientInfo.h" +#include "../TypesInternal.h" +#include "../ClientInfo.h" #include "PressureLogger.h" #define INSERTION_THRESHOLD 20000 diff --git a/src/sensor/PressureLogger.h b/src/sensor/pressure/PressureLogger.h similarity index 95% rename from src/sensor/PressureLogger.h rename to src/sensor/pressure/PressureLogger.h index 45d0c68..3f8995a 100644 --- a/src/sensor/PressureLogger.h +++ b/src/sensor/pressure/PressureLogger.h @@ -17,8 +17,8 @@ #ifndef __CONTEXT_PRESSURE_LOGGER_H__ #define __CONTEXT_PRESSURE_LOGGER_H__ -#include "SensorLogger.h" -#include "SensorProxy.h" +#include "../SensorLogger.h" +#include "../SensorProxy.h" namespace ctx { diff --git a/src/sensor/PressureQuerier.cpp b/src/sensor/pressure/PressureQuerier.cpp similarity index 98% rename from src/sensor/PressureQuerier.cpp rename to src/sensor/pressure/PressureQuerier.cpp index 5e01662..43d3457 100644 --- a/src/sensor/PressureQuerier.cpp +++ b/src/sensor/pressure/PressureQuerier.cpp @@ -16,7 +16,7 @@ #include #include -#include "TypesInternal.h" +#include "../TypesInternal.h" #include "PressureQuerier.h" #define PROJECTION \ diff --git a/src/sensor/PressureQuerier.h b/src/sensor/pressure/PressureQuerier.h similarity index 97% rename from src/sensor/PressureQuerier.h rename to src/sensor/pressure/PressureQuerier.h index be1788c..1bd9aa6 100644 --- a/src/sensor/PressureQuerier.h +++ b/src/sensor/pressure/PressureQuerier.h @@ -17,7 +17,7 @@ #ifndef __CONTEXT_PRESSURE_QUERIER_H__ #define __CONTEXT_PRESSURE_QUERIER_H__ -#include "Querier.h" +#include "../Querier.h" namespace ctx { -- 2.7.4 From 941beead57c8e5e74e88a7238f05988f04cc617f Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Thu, 30 Jun 2016 10:19:02 +0900 Subject: [PATCH 08/16] sensor: split the time-related functions into TimeUtil class Change-Id: I27c72a76d55aa606b11e94f31a192586f2926e55 Signed-off-by: Mu-Woong Lee --- src/sensor/SensorLogger.cpp | 30 ++---------------- src/sensor/SensorLogger.h | 2 -- src/sensor/TimeUtil.cpp | 52 ++++++++++++++++++++++++++++++++ src/sensor/TimeUtil.h | 36 ++++++++++++++++++++++ src/sensor/pedometer/PedometerLogger.cpp | 3 +- src/sensor/pressure/PressureLogger.cpp | 7 +++-- 6 files changed, 96 insertions(+), 34 deletions(-) create mode 100644 src/sensor/TimeUtil.cpp create mode 100644 src/sensor/TimeUtil.h diff --git a/src/sensor/SensorLogger.cpp b/src/sensor/SensorLogger.cpp index e2462ab..d79ec12 100644 --- a/src/sensor/SensorLogger.cpp +++ b/src/sensor/SensorLogger.cpp @@ -14,12 +14,10 @@ * limitations under the License. */ -#include -#include -#include #include #include #include "TypesInternal.h" +#include "TimeUtil.h" #include "SensorLogger.h" using namespace ctx; @@ -33,30 +31,6 @@ SensorLogger::~SensorLogger() { } -uint64_t SensorLogger::getTime() -{ - struct timeval tv; - double timestamp; - - gettimeofday(&tv, NULL); - timestamp = tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0; - return static_cast(round(timestamp)); -} - -uint64_t SensorLogger::getTime(unsigned long long monotonic) -{ - struct timespec ts; - double timestamp; - uint64_t currentTime = getTime(); - - if (abs(currentTime / 1000 - monotonic / 1000000) < SECONDS_PER_DAY) - return static_cast(round(monotonic / 1000.0)); - - clock_gettime(CLOCK_MONOTONIC, &ts); - timestamp = static_cast(currentTime) - (ts.tv_sec * 1000000000.0 + ts.tv_nsec) / 1000000.0 + monotonic / 1000.0; - return static_cast(round(timestamp)); -} - bool SensorLogger::executeQuery(const char *query) { return __dbMgr.execute(0, query, NULL); @@ -64,7 +38,7 @@ bool SensorLogger::executeQuery(const char *query) void SensorLogger::removeExpired(const char *subject, const char *tableName, const char *timeKey) { - uint64_t timestamp = getTime(); + uint64_t timestamp = TimeUtil::getTime(); if (timestamp - __lastRemovalTime < SEC_TO_MS(SECONDS_PER_HOUR)) return; diff --git a/src/sensor/SensorLogger.h b/src/sensor/SensorLogger.h index eef4df3..cd13883 100644 --- a/src/sensor/SensorLogger.h +++ b/src/sensor/SensorLogger.h @@ -30,8 +30,6 @@ namespace ctx { virtual void stop() = 0; protected: - uint64_t getTime(); - uint64_t getTime(unsigned long long monotonic); bool executeQuery(const char *query); virtual void removeExpired(const char *subject, const char *tableName, const char *timeKey); diff --git a/src/sensor/TimeUtil.cpp b/src/sensor/TimeUtil.cpp new file mode 100644 index 0000000..ecfec5c --- /dev/null +++ b/src/sensor/TimeUtil.cpp @@ -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. + * + */ + +#include +#include +#include +#include "TypesInternal.h" +#include "TimeUtil.h" + +using namespace ctx; + +TimeUtil::TimeUtil() +{ +} + +uint64_t TimeUtil::getTime() +{ + struct timeval tv; + double timestamp; + + gettimeofday(&tv, NULL); + timestamp = tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0; + return static_cast(round(timestamp)); +} + +uint64_t TimeUtil::getTime(unsigned long long monotonic) +{ + struct timespec ts; + double timestamp; + uint64_t currentTime = getTime(); + + if (std::abs(currentTime / 1000 - monotonic / 1000000) < SECONDS_PER_DAY) + return static_cast(round(monotonic / 1000.0)); + + clock_gettime(CLOCK_MONOTONIC, &ts); + timestamp = static_cast(currentTime) - (ts.tv_sec * 1000000000.0 + ts.tv_nsec) / 1000000.0 + monotonic / 1000.0; + return static_cast(round(timestamp)); +} diff --git a/src/sensor/TimeUtil.h b/src/sensor/TimeUtil.h new file mode 100644 index 0000000..0fb3169 --- /dev/null +++ b/src/sensor/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 monotonic); + + private: + TimeUtil(); + }; + +} + +#endif /* __CONTEXT_TIME_UTIL_H__ */ diff --git a/src/sensor/pedometer/PedometerLogger.cpp b/src/sensor/pedometer/PedometerLogger.cpp index ed73b2a..c1103b6 100644 --- a/src/sensor/pedometer/PedometerLogger.cpp +++ b/src/sensor/pedometer/PedometerLogger.cpp @@ -18,6 +18,7 @@ #include #include "../TypesInternal.h" #include "../ClientInfo.h" +#include "../TimeUtil.h" #include "PedometerLogger.h" using namespace ctx; @@ -74,7 +75,7 @@ void PedometerLogger::stop() void PedometerLogger::onEvent(sensor_data_t *eventData) { sensor_pedometer_data_t *pedometerData = reinterpret_cast(eventData); - uint64_t timestamp = getTime(); + uint64_t timestamp = TimeUtil::getTime(); if (__firstEvent) { _D("Baseline event"); diff --git a/src/sensor/pressure/PressureLogger.cpp b/src/sensor/pressure/PressureLogger.cpp index e301165..8f25f11 100644 --- a/src/sensor/pressure/PressureLogger.cpp +++ b/src/sensor/pressure/PressureLogger.cpp @@ -18,6 +18,7 @@ #include #include "../TypesInternal.h" #include "../ClientInfo.h" +#include "../TimeUtil.h" #include "PressureLogger.h" #define INSERTION_THRESHOLD 20000 @@ -57,7 +58,7 @@ bool PressureLogger::start() _I(GREEN("Start to record")); - __lastInsertionTime = getTime(); + __lastInsertionTime = TimeUtil::getTime(); __resetInsertionQuery(); return SensorProxy::start(); @@ -72,7 +73,7 @@ void PressureLogger::stop() void PressureLogger::onEvent(sensor_data_t *eventData) { - uint64_t receivedTime = getTime(); + uint64_t receivedTime = TimeUtil::getTime(); __record(eventData, receivedTime); removeExpired(SUBJ_SENSOR_PRESSURE, PRESSURE_RECORD, KEY_UNIV_TIME); } @@ -81,7 +82,7 @@ void PressureLogger::__record(sensor_data_t *eventData, uint64_t receivedTime) { char buffer[64]; g_snprintf(buffer, sizeof(buffer), "(%llu, %.5f),", - getTime(eventData->timestamp), eventData->values[0]); + TimeUtil::getTime(eventData->timestamp), eventData->values[0]); __insertionQuery += buffer; -- 2.7.4 From 74ff38303ab59cbc66a9761c130a961d101a8e4f Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Thu, 30 Jun 2016 10:19:25 +0900 Subject: [PATCH 09/16] sensor: change SensorProxy::isRunning() to a public member Change-Id: Id92e10fa303ba779289f9e0d633f02d4fd93184b Signed-off-by: Mu-Woong Lee --- src/sensor/SensorProxy.h | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/sensor/SensorProxy.h b/src/sensor/SensorProxy.h index d264668..ba60b35 100644 --- a/src/sensor/SensorProxy.h +++ b/src/sensor/SensorProxy.h @@ -35,6 +35,7 @@ namespace ctx { virtual bool start(); virtual void stop(); + bool isRunning(); void flush(); protected: @@ -47,8 +48,6 @@ namespace ctx { static bool isSupported(sensor_type_t type); - bool isRunning(); - virtual void onEvent(sensor_data_t *eventData) = 0; private: -- 2.7.4 From aea4896e46f2c31efb7d144117a219826d9c7c79 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Thu, 30 Jun 2016 10:19:41 +0900 Subject: [PATCH 10/16] sensor: rename SensorProxy::start() and stop() to listen() and unlisten() start() and stop() are being used by logger classes with different meanings, thus it would be better to rename them to avoid ambiguity. Change-Id: Iaeb1aea86997f0659a768a31d88d47a371bda653 Signed-off-by: Mu-Woong Lee --- src/sensor/SensorProxy.cpp | 6 +++--- src/sensor/SensorProxy.h | 4 ++-- src/sensor/pedometer/PedometerLogger.cpp | 10 +++++----- src/sensor/pressure/PressureLogger.cpp | 10 +++++----- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/sensor/SensorProxy.cpp b/src/sensor/SensorProxy.cpp index f927ec1..98dd0a6 100644 --- a/src/sensor/SensorProxy.cpp +++ b/src/sensor/SensorProxy.cpp @@ -34,7 +34,7 @@ SensorProxy::SensorProxy() : SensorProxy::~SensorProxy() { - stop(); + unlisten(); } void SensorProxy::setSensor(sensor_type_t type) @@ -62,7 +62,7 @@ void SensorProxy::setUserData(void *data) userData = data; } -bool SensorProxy::start() +bool SensorProxy::listen() { _D("#Sensor = %#x", sensorType); @@ -90,7 +90,7 @@ bool SensorProxy::start() return true; } -void SensorProxy::stop() +void SensorProxy::unlisten() { IF_FAIL_VOID(sensorHandle >= 0); diff --git a/src/sensor/SensorProxy.h b/src/sensor/SensorProxy.h index ba60b35..7ae1c87 100644 --- a/src/sensor/SensorProxy.h +++ b/src/sensor/SensorProxy.h @@ -33,8 +33,8 @@ namespace ctx { void setBatchLatency(unsigned int latency); void setUserData(void *data); - virtual bool start(); - virtual void stop(); + bool listen(); + void unlisten(); bool isRunning(); void flush(); diff --git a/src/sensor/pedometer/PedometerLogger.cpp b/src/sensor/pedometer/PedometerLogger.cpp index c1103b6..c215d30 100644 --- a/src/sensor/pedometer/PedometerLogger.cpp +++ b/src/sensor/pedometer/PedometerLogger.cpp @@ -47,16 +47,15 @@ PedometerLogger::PedometerLogger() : PedometerLogger::~PedometerLogger() { + stop(); } bool PedometerLogger::start() { - if (SensorProxy::isRunning()) - return true; - + IF_FAIL_RETURN_TAG(!isRunning(), true, _D, "Started already"); _I(GREEN("Start to record")); - if (SensorProxy::start()) { + if (listen()) { flush(); return true; } @@ -66,9 +65,10 @@ bool PedometerLogger::start() void PedometerLogger::stop() { + IF_FAIL_VOID_TAG(isRunning(), _D, "Stopped already"); _I(GREEN("Stop recording")); - SensorProxy::stop(); + unlisten(); __firstEvent = true; } diff --git a/src/sensor/pressure/PressureLogger.cpp b/src/sensor/pressure/PressureLogger.cpp index 8f25f11..5f2f459 100644 --- a/src/sensor/pressure/PressureLogger.cpp +++ b/src/sensor/pressure/PressureLogger.cpp @@ -49,26 +49,26 @@ PressureLogger::PressureLogger() PressureLogger::~PressureLogger() { + stop(); } bool PressureLogger::start() { - if (SensorProxy::isRunning()) - return true; - + IF_FAIL_RETURN_TAG(!isRunning(), true, _D, "Started already"); _I(GREEN("Start to record")); __lastInsertionTime = TimeUtil::getTime(); __resetInsertionQuery(); - return SensorProxy::start(); + return listen(); } void PressureLogger::stop() { + IF_FAIL_VOID_TAG(isRunning(), _D, "Stopped already"); _I(GREEN("Stop recording")); - SensorProxy::stop(); + unlisten(); } void PressureLogger::onEvent(sensor_data_t *eventData) -- 2.7.4 From edb22e5259e529d6844765f2347933d228058af3 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Thu, 30 Jun 2016 10:19:55 +0900 Subject: [PATCH 11/16] sensor: define sleep monitor & hrm record table names Change-Id: I4b867daf235c28f1108c5b7e757fb373794d813c Signed-off-by: Mu-Woong Lee --- src/sensor/TypesInternal.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/sensor/TypesInternal.h b/src/sensor/TypesInternal.h index a39a452..8d84066 100644 --- a/src/sensor/TypesInternal.h +++ b/src/sensor/TypesInternal.h @@ -18,10 +18,13 @@ #define __CONTEXT_SENSOR_RECORDER_TYPES_INTERNAL_H__ /* Tables */ -#define PEDOMETER_RECORD "SensorPedometerRecord" -#define PRESSURE_RECORD "SensorPressureRecord" #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" -- 2.7.4 From 3c71bf5261569be97a762751a8fd46467ea8d8f9 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Thu, 30 Jun 2016 10:20:10 +0900 Subject: [PATCH 12/16] sensor: add the sensor recorder for sleep monitor Change-Id: Ifc16ed955e9bce1284de202c1983626a68a4c675 Signed-off-by: Mu-Woong Lee --- src/sensor/CreateProvider.cpp | 2 + src/sensor/sleep/Sleep.cpp | 54 ++++++++++++ src/sensor/sleep/Sleep.h | 37 +++++++++ src/sensor/sleep/SleepDetector.cpp | 58 +++++++++++++ src/sensor/sleep/SleepDetector.h | 41 +++++++++ src/sensor/sleep/SleepLogger.cpp | 165 +++++++++++++++++++++++++++++++++++++ src/sensor/sleep/SleepLogger.h | 54 ++++++++++++ src/sensor/sleep/SleepMonitor.cpp | 75 +++++++++++++++++ src/sensor/sleep/SleepMonitor.h | 44 ++++++++++ src/sensor/sleep/SleepQuerier.cpp | 55 +++++++++++++ src/sensor/sleep/SleepQuerier.h | 34 ++++++++ 11 files changed, 619 insertions(+) create mode 100644 src/sensor/sleep/Sleep.cpp create mode 100644 src/sensor/sleep/Sleep.h create mode 100644 src/sensor/sleep/SleepDetector.cpp create mode 100644 src/sensor/sleep/SleepDetector.h create mode 100644 src/sensor/sleep/SleepLogger.cpp create mode 100644 src/sensor/sleep/SleepLogger.h create mode 100644 src/sensor/sleep/SleepMonitor.cpp create mode 100644 src/sensor/sleep/SleepMonitor.h create mode 100644 src/sensor/sleep/SleepQuerier.cpp create mode 100644 src/sensor/sleep/SleepQuerier.h diff --git a/src/sensor/CreateProvider.cpp b/src/sensor/CreateProvider.cpp index 141ea0e..768ba81 100644 --- a/src/sensor/CreateProvider.cpp +++ b/src/sensor/CreateProvider.cpp @@ -18,6 +18,7 @@ #include #include "pedometer/Pedometer.h" #include "pressure/Pressure.h" +#include "sleep/Sleep.h" using namespace ctx; @@ -25,6 +26,7 @@ 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); return NULL; } diff --git a/src/sensor/sleep/Sleep.cpp b/src/sensor/sleep/Sleep.cpp new file mode 100644 index 0000000..3ae40c9 --- /dev/null +++ b/src/sensor/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/sensor/sleep/Sleep.h b/src/sensor/sleep/Sleep.h new file mode 100644 index 0000000..c93310e --- /dev/null +++ b/src/sensor/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/sensor/sleep/SleepDetector.cpp b/src/sensor/sleep/SleepDetector.cpp new file mode 100644 index 0000000..5367dac --- /dev/null +++ b/src/sensor/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/sensor/sleep/SleepDetector.h b/src/sensor/sleep/SleepDetector.h new file mode 100644 index 0000000..104678c --- /dev/null +++ b/src/sensor/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/sensor/sleep/SleepLogger.cpp b/src/sensor/sleep/SleepLogger.cpp new file mode 100644 index 0000000..81f1547 --- /dev/null +++ b/src/sensor/sleep/SleepLogger.cpp @@ -0,0 +1,165 @@ +/* + * 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 "../ClientInfo.h" +#include "../TimeUtil.h" +#include "SleepDetector.h" +#include "SleepMonitor.h" +#include "SleepLogger.h" + +#define TIME_GAP 5000 + +using namespace ctx; + +SleepLogger::SleepLogger() : + __sleepDetector(NULL), + __sleepMonitor(NULL), + __startTime(0), + __endTime(0) +{ + /* 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 dynamic_cast(__sleepDetector)->start(); +} + +void SleepLogger::stop() +{ + IF_FAIL_VOID_TAG(__sleepDetector, _D, "Stopped already"); + _I(GREEN("Stop recording")); + + dynamic_cast(__sleepDetector)->stop(); + dynamic_cast(__sleepMonitor)->stop(); + + __appendQuery(__startTime, __endTime); + flush(); + + delete __sleepDetector; + __sleepDetector = NULL; + + delete __sleepMonitor; + __sleepMonitor = NULL; +} + +void SleepLogger::fallAsleep(uint64_t timestamp) +{ + _D("Fall asleep"); + record(timestamp, TimeUtil::getTime(), STATE_SLEEP); + dynamic_cast(__sleepMonitor)->start(); +} + +void SleepLogger::wakeUp(uint64_t timestamp) +{ + _D("Wake up"); + dynamic_cast(__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::flush() +{ + __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), "(%llu, %llu),", startTime, endTime); + __insertionQuery += buffer; +} diff --git a/src/sensor/sleep/SleepLogger.h b/src/sensor/sleep/SleepLogger.h new file mode 100644 index 0000000..12f5dd2 --- /dev/null +++ b/src/sensor/sleep/SleepLogger.h @@ -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. + */ + +#ifndef __CONTEXT_SLEEP_LOGGER_H__ +#define __CONTEXT_SLEEP_LOGGER_H__ + +#include "../SensorLogger.h" +#include "../SensorProxy.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 flush(); + + private: + void __resetInsertionQuery(); + void __appendQuery(uint64_t startTime, uint64_t endTime); + + std::string __insertionQuery; + SensorProxy *__sleepDetector; + SensorProxy *__sleepMonitor; + uint64_t __startTime; + uint64_t __endTime; + }; +} + +#endif /* __CONTEXT_SLEEP_LOGGER_H__ */ diff --git a/src/sensor/sleep/SleepMonitor.cpp b/src/sensor/sleep/SleepMonitor.cpp new file mode 100644 index 0000000..c851ca4 --- /dev/null +++ b/src/sensor/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->flush(); + + if (__lazyStopOn) + stop(); +} diff --git a/src/sensor/sleep/SleepMonitor.h b/src/sensor/sleep/SleepMonitor.h new file mode 100644 index 0000000..7aa37d9 --- /dev/null +++ b/src/sensor/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/sensor/sleep/SleepQuerier.cpp b/src/sensor/sleep/SleepQuerier.cpp new file mode 100644 index 0000000..1a8f8dc --- /dev/null +++ b/src/sensor/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/sensor/sleep/SleepQuerier.h b/src/sensor/sleep/SleepQuerier.h new file mode 100644 index 0000000..7ba674f --- /dev/null +++ b/src/sensor/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 56ee4208d2870b85cd182cced63912aa0a49f3bc Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 1 Jul 2016 15:44:31 +0900 Subject: [PATCH 13/16] sensor: remove necessity of dynamic_cast in SleepLogger Change-Id: I8d9579b7650ebcdaffeab3808968db065a35e97f Signed-off-by: Mu-Woong Lee --- src/sensor/sleep/SleepLogger.cpp | 18 +++++++++++------- src/sensor/sleep/SleepLogger.h | 3 --- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/sensor/sleep/SleepLogger.cpp b/src/sensor/sleep/SleepLogger.cpp index 81f1547..f3e1470 100644 --- a/src/sensor/sleep/SleepLogger.cpp +++ b/src/sensor/sleep/SleepLogger.cpp @@ -27,12 +27,16 @@ using namespace ctx; +static SleepDetector *__sleepDetector = NULL; +static SleepMonitor *__sleepMonitor = NULL; + SleepLogger::SleepLogger() : - __sleepDetector(NULL), - __sleepMonitor(NULL), __startTime(0), __endTime(0) { + __sleepDetector = NULL; + __sleepMonitor = NULL; + /* Create the log table */ executeQuery( "CREATE TABLE IF NOT EXISTS " SLEEP_MONITOR_RECORD " (" \ @@ -81,7 +85,7 @@ bool SleepLogger::start() __endTime = 0; __resetInsertionQuery(); - return dynamic_cast(__sleepDetector)->start(); + return __sleepDetector->start(); } void SleepLogger::stop() @@ -89,8 +93,8 @@ void SleepLogger::stop() IF_FAIL_VOID_TAG(__sleepDetector, _D, "Stopped already"); _I(GREEN("Stop recording")); - dynamic_cast(__sleepDetector)->stop(); - dynamic_cast(__sleepMonitor)->stop(); + __sleepDetector->stop(); + __sleepMonitor->stop(); __appendQuery(__startTime, __endTime); flush(); @@ -106,13 +110,13 @@ void SleepLogger::fallAsleep(uint64_t timestamp) { _D("Fall asleep"); record(timestamp, TimeUtil::getTime(), STATE_SLEEP); - dynamic_cast(__sleepMonitor)->start(); + __sleepMonitor->start(); } void SleepLogger::wakeUp(uint64_t timestamp) { _D("Wake up"); - dynamic_cast(__sleepMonitor)->lazyStop(); + __sleepMonitor->lazyStop(); } void SleepLogger::record(uint64_t startTime, uint64_t endTime, int state) diff --git a/src/sensor/sleep/SleepLogger.h b/src/sensor/sleep/SleepLogger.h index 12f5dd2..447c59c 100644 --- a/src/sensor/sleep/SleepLogger.h +++ b/src/sensor/sleep/SleepLogger.h @@ -18,7 +18,6 @@ #define __CONTEXT_SLEEP_LOGGER_H__ #include "../SensorLogger.h" -#include "../SensorProxy.h" #define STATE_SLEEP 1 #define STATE_WAKE 0 @@ -44,8 +43,6 @@ namespace ctx { void __appendQuery(uint64_t startTime, uint64_t endTime); std::string __insertionQuery; - SensorProxy *__sleepDetector; - SensorProxy *__sleepMonitor; uint64_t __startTime; uint64_t __endTime; }; -- 2.7.4 From 9e3cae38d04d3e1a8934eef6b2aea18e192f39b8 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 1 Jul 2016 15:45:00 +0900 Subject: [PATCH 14/16] sensor: set the maximum retention period (1 month) Change-Id: Id37d909394ad1db7b8aafad4f673f7e9ef326f67 Signed-off-by: Mu-Woong Lee --- src/sensor/SensorProvider.cpp | 3 +++ src/sensor/TypesInternal.h | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/sensor/SensorProvider.cpp b/src/sensor/SensorProvider.cpp index e205246..32f0584 100644 --- a/src/sensor/SensorProvider.cpp +++ b/src/sensor/SensorProvider.cpp @@ -119,6 +119,9 @@ int SensorProvider::__addClient(std::string pkgId, int retentionPeriod, Json opt 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); diff --git a/src/sensor/TypesInternal.h b/src/sensor/TypesInternal.h index 8d84066..1894520 100644 --- a/src/sensor/TypesInternal.h +++ b/src/sensor/TypesInternal.h @@ -33,7 +33,7 @@ #define SECONDS_PER_HOUR 3600 #define SECONDS_PER_DAY 86400 -/* Default Parameters */ +#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 */ -- 2.7.4 From 0da83d12133cf06d128bded7e431a2ab6ec32508 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 1 Jul 2016 15:45:42 +0900 Subject: [PATCH 15/16] sensor: cascade its recording requests if an app is uninstalled Change-Id: I17f2c453896107721cad74b6136b16f4eaf0ba4d Signed-off-by: Mu-Woong Lee --- src/sensor/ClientInfo.cpp | 38 +++++++++++++++++++++--- src/sensor/ClientInfo.h | 4 +++ src/sensor/SensorProvider.cpp | 9 ++++++ src/sensor/SensorProvider.h | 5 ++++ src/sensor/UninstallMonitor.cpp | 66 +++++++++++++++++++++++++++++++++++++++++ src/sensor/UninstallMonitor.h | 40 +++++++++++++++++++++++++ 6 files changed, 158 insertions(+), 4 deletions(-) create mode 100644 src/sensor/UninstallMonitor.cpp create mode 100644 src/sensor/UninstallMonitor.h diff --git a/src/sensor/ClientInfo.cpp b/src/sensor/ClientInfo.cpp index 6a94f01..e1913f7 100644 --- a/src/sensor/ClientInfo.cpp +++ b/src/sensor/ClientInfo.cpp @@ -18,20 +18,23 @@ #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() { - ++__refCnt; - - if (__dbMgr) + 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"); @@ -54,6 +57,9 @@ ClientInfo::~ClientInfo() delete __dbMgr; __dbMgr = NULL; + + delete __uninstallMonitor; + __uninstallMonitor = NULL; } int ClientInfo::get(std::string subject, std::string pkgId, Json& option) @@ -98,7 +104,7 @@ int ClientInfo::get(std::string subject, std::vector& options) IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); IF_FAIL_RETURN(!records.empty(), ERR_NO_DATA); - for (auto jObj : records) { + for (Json& jObj : records) { if (!jObj.get(NULL, KEY_OPTION, &optStr)) continue; options.push_back(Json(optStr)); @@ -157,3 +163,27 @@ bool ClientInfo::remove(std::string subject, std::string pkgId) return ret; } + +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/sensor/ClientInfo.h b/src/sensor/ClientInfo.h index a52cd27..a14dc3c 100644 --- a/src/sensor/ClientInfo.h +++ b/src/sensor/ClientInfo.h @@ -21,6 +21,7 @@ #include #include #include +#include "UninstallMonitor.h" namespace ctx { @@ -36,9 +37,12 @@ namespace ctx { bool set(std::string subject, std::string pkgId, Json option, int retentionPeriod); bool remove(std::string subject, std::string pkgId); + static void purgeClient(std::string pkgId); + private: static unsigned int __refCnt; static DatabaseManager *__dbMgr; + static UninstallMonitor *__uninstallMonitor; }; } diff --git a/src/sensor/SensorProvider.cpp b/src/sensor/SensorProvider.cpp index 32f0584..8cc8e1f 100644 --- a/src/sensor/SensorProvider.cpp +++ b/src/sensor/SensorProvider.cpp @@ -22,14 +22,18 @@ 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; } @@ -155,3 +159,8 @@ int SensorProvider::__removeClient(std::string pkgId) return ERR_NONE; } + +void SensorProvider::removeClient(std::string subject, std::string pkgId) +{ + __providerMap[subject]->__removeClient(pkgId); +} diff --git a/src/sensor/SensorProvider.h b/src/sensor/SensorProvider.h index 4a1cf5b..601b191 100644 --- a/src/sensor/SensorProvider.h +++ b/src/sensor/SensorProvider.h @@ -17,6 +17,7 @@ #ifndef __CONTEXT_SENSOR_PROVIDER_H__ #define __CONTEXT_SENSOR_PROVIDER_H__ +#include #include #include "ClientInfo.h" #include "SensorLogger.h" @@ -34,6 +35,8 @@ namespace ctx { 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; @@ -44,6 +47,8 @@ namespace ctx { int __removeClient(std::string pkgId); ClientInfo __clientInfo; + + static std::map __providerMap; }; } diff --git a/src/sensor/UninstallMonitor.cpp b/src/sensor/UninstallMonitor.cpp new file mode 100644 index 0000000..b3dc8a5 --- /dev/null +++ b/src/sensor/UninstallMonitor.cpp @@ -0,0 +1,66 @@ +/* + * 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_status", "org.tizen.pkgmgr_status", "status", 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 *reqId = NULL; + const gchar *pkgType = NULL; + const gchar *pkgId = NULL; + const gchar *key = NULL; + const gchar *val = NULL; + + g_variant_get(param, "(&s&s&s&s&s)", &reqId, &pkgType, &pkgId, &key, &val); + _D("%s, %s, %s", pkgId, key, val); + + IF_FAIL_VOID_TAG(pkgId && key && val, _E, "Invalid parameter"); + + if (STR_EQ(key, "start")) { + if (STR_EQ(val, "uninstall")) { + __pkgId = pkgId; + } else { + __pkgId.clear(); + } + return; + } + + if (__pkgId.empty() || !STR_EQ(key, "end") || !STR_EQ(val, "ok")) + return; + + _I("'%s' has been removed", __pkgId.c_str()); + + ClientInfo::purgeClient(__pkgId); + + __pkgId.clear(); +} diff --git a/src/sensor/UninstallMonitor.h b/src/sensor/UninstallMonitor.h new file mode 100644 index 0000000..8da2fce --- /dev/null +++ b/src/sensor/UninstallMonitor.h @@ -0,0 +1,40 @@ +/* + * 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 +#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; + std::string __pkgId; + }; + +} + +#endif /* __CONTEXT_UNINSTALL_MONITOR_H__ */ -- 2.7.4 From c68cdb7f0ee1932814da2d51b8e51f2e0c5e3205 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 1 Jul 2016 15:45:58 +0900 Subject: [PATCH 16/16] sensor: align recording request json format with sensor api Change-Id: Ief0236c20797bdd14fa327cbd3a085c93ff1a0bc Signed-off-by: Mu-Woong Lee --- src/sensor/SensorProvider.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/sensor/SensorProvider.cpp b/src/sensor/SensorProvider.cpp index 8cc8e1f..71e4c01 100644 --- a/src/sensor/SensorProvider.cpp +++ b/src/sensor/SensorProvider.cpp @@ -98,6 +98,7 @@ int SensorProvider::write(Json data, Json *requestResult) std::string operation; std::string pkgId; + Json option; int retentionPeriod = DEFAULT_RETENTION; _J("Data", data); @@ -105,13 +106,15 @@ int SensorProvider::write(Json data, Json *requestResult) 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); - if (data.get(NULL, KEY_RETENTION, &retentionPeriod)) - retentionPeriod *= SECONDS_PER_HOUR; + data.get(NULL, KEY_OPTION, &option); - /* TODO: remove the operation & pkg id from the json */ + if (option.get(NULL, KEY_RETENTION, &retentionPeriod)) { + retentionPeriod *= SECONDS_PER_HOUR; + option.remove(NULL, KEY_RETENTION); + } if (operation == VAL_START) - return __addClient(pkgId, retentionPeriod, data); + return __addClient(pkgId, retentionPeriod, option); else if (operation == VAL_STOP) return __removeClient(pkgId); -- 2.7.4