From 27ace6d295841e9f1400eca2c51169b0128186ad Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 12 Aug 2016 09:47:06 +0900 Subject: [PATCH 01/16] Enable MyPlace detector Change-Id: Ibafac614bbce3f86a4152283d929d5e04318ff90 Signed-off-by: Mu-Woong Lee --- packaging/context-provider.spec | 2 +- src/CMakeLists.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index 980913d..7e7b0b5 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -1,6 +1,6 @@ Name: context-provider Summary: Context Provider -Version: 0.9.4 +Version: 0.9.5 Release: 1 Group: Service/Context License: Apache-2.0 diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index bb6ed1d..f41f86b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -20,6 +20,6 @@ ADD_SUBDIRECTORY(email) ADD_SUBDIRECTORY(geofence) ADD_SUBDIRECTORY(media-stats) ADD_SUBDIRECTORY(message) -#ADD_SUBDIRECTORY(my-place) +ADD_SUBDIRECTORY(my-place) ADD_SUBDIRECTORY(social-stats) ENDIF("${PROFILE}" STREQUAL "mobile") -- 2.7.4 From 3bfd314312ada32f441c98f83063a8975e8e14ed Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Mon, 22 Aug 2016 16:25:55 +0900 Subject: [PATCH 02/16] Custom types are modified Change-Id: I9c895c1a879e057bc8cda5fbda0d0ecff26b38a9 Signed-off-by: Somin Kim --- src/custom/CustomManager.cpp | 56 ++++++++++++++++++++++---------------------- src/custom/CustomTypes.h | 45 +++++++++++++++++++---------------- src/shared/DbHandleBase.cpp | 6 ++--- 3 files changed, 56 insertions(+), 51 deletions(-) diff --git a/src/custom/CustomManager.cpp b/src/custom/CustomManager.cpp index 6bb7a5e..5ec516f 100644 --- a/src/custom/CustomManager.cpp +++ b/src/custom/CustomManager.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include "CustomManager.h" #include "CustomProvider.h" #include "CustomTypes.h" @@ -67,27 +68,27 @@ int CustomManager::write(Json data, Json *requestResult) { int error = ERR_NONE; std::string req; - data.get(NULL, CUSTOM_KEY_REQ, &req); + data.get(NULL, TRIG_CUSTOM_KEY_REQ, &req); std::string packageId; std::string name; 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; + data.get(NULL, TRIG_CUSTOM_KEY_NAME, &name); + std::string subj = std::string(SUBJ_CUSTOM) + TRIG_SUBJECT_SEPERATOR + packageId + TRIG_SUBJECT_SEPERATOR + name; - if (req == CUSTOM_REQ_TYPE_ADD) { + if (req == TRIG_CUSTOM_REQ_ADD) { Json tmpl; - data.get(NULL, CUSTOM_KEY_ATTRIBUTES, &tmpl); + data.get(NULL, TRIG_TMPL_KEY_ATTRIBUTE, &tmpl); error = __addCustomItem(subj, name, tmpl, packageId); - } else if (req == CUSTOM_REQ_TYPE_REMOVE) { + } else if (req == TRIG_CUSTOM_REQ_REMOVE) { error = __removeCustomItem(subj); if (error == ERR_NONE) { - requestResult->set(NULL, CUSTOM_KEY_SUBJECT, subj); + requestResult->set(NULL, TRIG_TMPL_KEY_SUBJECT, subj); } - } else if (req == CUSTOM_REQ_TYPE_PUBLISH) { + } else if (req == TRIG_CUSTOM_REQ_PUBLISH) { Json fact; - data.get(NULL, CUSTOM_KEY_FACT, &fact); + data.get(NULL, TRIG_CUSTOM_KEY_FACT, &fact); error = __publishData(subj, fact); } @@ -108,12 +109,11 @@ bool CustomManager::__initialize() { /* Create custom template table */ std::vector record; - bool ret = __dbManager.executeSync(CUSTOM_TEMPLATE_TABLE_SCHEMA, &record); + bool ret = __dbManager.executeSync(CREATE_CUSTOM_TMPL_TABLE_QUERY, &record); IF_FAIL_RETURN_TAG(ret, false, _E, "Create template table failed"); /* Register custom items */ - std::string qSelect = "SELECT * FROM ContextTriggerCustomTemplate"; - ret = __dbManager.executeSync(qSelect.c_str(), &record); + ret = __dbManager.executeSync(SELECT_CUSTOM_TMPL_TABLE_QUERY, &record); IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to query custom templates"); IF_FAIL_RETURN(record.size() > 0, true); @@ -125,10 +125,10 @@ bool CustomManager::__initialize() std::string name; std::string attributes; std::string owner; - elem.get(NULL, CUSTOM_KEY_SUBJECT, &subject); - elem.get(NULL, CUSTOM_KEY_NAME, &name); - elem.get(NULL, CUSTOM_KEY_ATTRIBUTES, &attributes); - elem.get(NULL, CUSTOM_KEY_OWNER, &owner); + elem.get(NULL, CUSTOM_COLUMN_SUBJECT, &subject); + elem.get(NULL, CUSTOM_COLUMN_NAME, &name); + elem.get(NULL, CUSTOM_COLUMN_ATTRIBUTE, &attributes); + elem.get(NULL, CUSTOM_COLUMN_OWNER, &owner); error = __addCustomItem(subject.c_str(), name, Json(attributes), owner, true); if (error != ERR_NONE) { @@ -162,8 +162,8 @@ int CustomManager::__addCustomItem(std::string subject, std::string name, Json t /* Insert item to custom template db */ if (!isInit) { - std::string q = "INSERT OR IGNORE INTO ContextTriggerCustomTemplate (subject, name, attributes, owner) VALUES ('" - + subject + "', '" + name + "', '" + tmpl.str() + "', '" + owner + "'); "; + std::string q = std::string(INSERT_CUSTOM_TMPL_QUERY) + "('" + subject + "', '" + + name + "', '" + tmpl.str() + "', '" + owner + "'); "; std::vector record; bool ret = __dbManager.executeSync(q.c_str(), &record); IF_FAIL_RETURN_TAG(ret, ERR_OPERATION_FAILED, _E, "Failed to query custom templates"); @@ -183,7 +183,7 @@ int CustomManager::__removeCustomItem(std::string subject) __customMap.erase(it); /* Delete item from custom template db */ - std::string q = "DELETE FROM ContextTriggerCustomTemplate WHERE subject = '" + subject + "'"; + std::string q = std::string(DELETE_CUSTOM_TMPL_QUERY) + "'" + subject + "'"; std::vector record; bool ret = __dbManager.executeSync(q.c_str(), &record); IF_FAIL_RETURN_TAG(ret, ERR_OPERATION_FAILED, _E, "Failed to query custom templates"); @@ -217,28 +217,28 @@ bool __isValidFact(std::string subject, Json& fact) std::string key = *it; std::string type; - ret = tmpl.get(key.c_str(), "type", &type); + ret = tmpl.get(key.c_str(), TRIG_TMPL_KEY_TYPE, &type); if (!ret) { - int size = tmpl.getSize(key.c_str(), "enum"); + int size = tmpl.getSize(key.c_str(), TRIG_TMPL_TYPE_ENUM); IF_FAIL_RETURN_TAG(size >= 0, false, _E, "Invalid template"); - type = "enum"; + type = TRIG_TMPL_TYPE_ENUM; } - if (type == "integer") { + if (type == TRIG_TMPL_TYPE_INTEGER) { int val; ret = fact.get(NULL, key.c_str(), &val); IF_FAIL_RETURN_TAG(ret, false, _E, "Custom fact: invalid data type"); ret = __checkValueInt(tmpl, key, val); IF_FAIL_RETURN_TAG(ret, false, _E, "Custom fact: invalid value"); - } else if (type == "string") { + } else if (type == TRIG_TMPL_TYPE_STRING) { std::string val_str; ret = fact.get(NULL, key.c_str(), &val_str); IF_FAIL_RETURN_TAG(ret, false, _E, "Custom fact: invalid data type"); ret = __checkValueString(tmpl, key, val_str); IF_FAIL_RETURN_TAG(ret, false, _E, "Custom fact: invalid value"); - } else if (type == "enum") { + } else if (type == TRIG_TMPL_TYPE_ENUM) { std::string val_str; ret = fact.get(NULL, key.c_str(), &val_str); IF_FAIL_RETURN_TAG(ret, false, _E, "Custom fact: invalid data type"); @@ -258,11 +258,11 @@ bool __checkValueInt(Json& tmpl, std::string key, int value) { int min, max; - if (tmpl.get(key.c_str(), "minimum", &min)) { + if (tmpl.get(key.c_str(), TRIG_TMPL_KEY_MIN, &min)) { IF_FAIL_RETURN(value >= min, false); } - if (tmpl.get(key.c_str(), "maximum", &max)) { + if (tmpl.get(key.c_str(), TRIG_TMPL_KEY_MAX, &max)) { IF_FAIL_RETURN(value <= max, false); } @@ -279,7 +279,7 @@ bool __checkValueEnum(Json& tmpl, std::string key, std::string value) { /* check acceptable value */ std::string tmplValue; - for (int i = 0; tmpl.getAt(key.c_str(), "enum", i, &tmplValue); i++) { + for (int i = 0; tmpl.getAt(key.c_str(), TRIG_TMPL_TYPE_ENUM, i, &tmplValue); i++) { if (tmplValue == value) return true; } diff --git a/src/custom/CustomTypes.h b/src/custom/CustomTypes.h index 8aecdfa..b3f94d5 100644 --- a/src/custom/CustomTypes.h +++ b/src/custom/CustomTypes.h @@ -19,25 +19,30 @@ #include -#define CUSTOM_KEY_REQ "req" -#define CUSTOM_KEY_PACKAGE_ID "packageId" -#define CUSTOM_KEY_NAME "name" -#define CUSTOM_KEY_ATTRIBUTES "attributes" -#define CUSTOM_KEY_FACT "fact" -#define CUSTOM_KEY_SUBJECT "subject" -#define CUSTOM_KEY_OWNER "owner" - -#define CUSTOM_REQ_TYPE_ADD "add" -#define CUSTOM_REQ_TYPE_REMOVE "remove" -#define CUSTOM_REQ_TYPE_PUBLISH "publish" - -#define CUSTOM_SEPERATOR "/" - -#define CUSTOM_TEMPLATE_TABLE_SCHEMA \ - "CREATE TABLE IF NOT EXISTS ContextTriggerCustomTemplate " \ - "(subject TEXT DEFAULT '' NOT NULL PRIMARY KEY, name TEXT DEFAULT '' NOT NULL," \ - " operation INTEGER DEFAULT 3 NOT NULL, attributes TEXT DEFAULT '' NOT NULL, " \ - " owner TEXT DEFAULT '' NOT NULL)" - +#define CUSTOM_TMPL_TABLE "ContextTriggerCustomTemplate" +#define CUSTOM_COLUMN_SUBJECT "subject" +#define CUSTOM_COLUMN_NAME "name" +#define CUSTOM_COLUMN_OPERATION "operation" +#define CUSTOM_COLUMN_ATTRIBUTE "attributes" +#define CUSTOM_COLUMN_OWNER "owner" + +#define CREATE_CUSTOM_TMPL_TABLE_QUERY \ + "CREATE TABLE IF NOT EXISTS " CUSTOM_TMPL_TABLE \ + " (" CUSTOM_COLUMN_SUBJECT " TEXT DEFAULT '' NOT NULL PRIMARY KEY, "\ + CUSTOM_COLUMN_NAME " TEXT DEFAULT '' NOT NULL, " \ + CUSTOM_COLUMN_OPERATION " INTEGER DEFAULT 3 NOT NULL, "\ + CUSTOM_COLUMN_ATTRIBUTE " TEXT DEFAULT '' NOT NULL, "\ + CUSTOM_COLUMN_OWNER " TEXT DEFAULT '' NOT NULL)" + +#define SELECT_CUSTOM_TMPL_TABLE_QUERY \ + "SELECT * FROM " CUSTOM_TMPL_TABLE + +#define INSERT_CUSTOM_TMPL_QUERY \ + "INSERT OR IGNORE INTO " CUSTOM_TMPL_TABLE " ("\ + CUSTOM_COLUMN_SUBJECT ", " CUSTOM_COLUMN_NAME ", "\ + CUSTOM_COLUMN_ATTRIBUTE ", " CUSTOM_COLUMN_OWNER ") VALUES " + +#define DELETE_CUSTOM_TMPL_QUERY \ + "DELETE FROM " CUSTOM_TMPL_TABLE " WHERE " CUSTOM_COLUMN_SUBJECT " = " #endif /* End of _CONTEXT_CUSTOM_TYPES_H_ */ diff --git a/src/shared/DbHandleBase.cpp b/src/shared/DbHandleBase.cpp index 074a7ac..0bf238c 100644 --- a/src/shared/DbHandleBase.cpp +++ b/src/shared/DbHandleBase.cpp @@ -83,7 +83,7 @@ std::string StatsDbHandleBase::createWhereClause(Json filter) int week = 0; int start = 0; int end = 0; - int timespan = DEFAULT_TIMESPAN; + int timeSpan = DEFAULT_TIME_SPAN; std::string appId; std::string weekStr; std::string timeOfDay; @@ -161,8 +161,8 @@ std::string StatsDbHandleBase::createWhereClause(Json filter) } } - filter.get(NULL, KEY_TIMESPAN, ×pan); - whereClause << KEY_UNIV_TIME " > strftime('%s', 'now', '-" << timespan <<" day')"; + filter.get(NULL, KEY_TIME_SPAN, &timeSpan); + whereClause << KEY_UNIV_TIME " > strftime('%s', 'now', '-" << timeSpan <<" day')"; return whereClause.str(); } -- 2.7.4 From c70c9a3e4e1c25ea050bbbda411fc8c7ddc7a7f3 Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Sat, 3 Sep 2016 05:52:55 +0900 Subject: [PATCH 03/16] Per app battery usage (Only foreground app duration considered - based on HEART cpu db) Change-Id: I857e83ae8a20796865a056bd11106fa3254c54d9 Signed-off-by: Somin Kim --- include/ProviderList.h | 1 + src/CMakeLists.txt | 1 + src/battery-stats/BatteryMonitor.cpp | 280 +++++++++++++++++++++++++++++ src/battery-stats/BatteryMonitor.h | 55 ++++++ src/battery-stats/BatteryStatisticsTypes.h | 60 +++++++ src/battery-stats/BatteryStatsLogger.cpp | 49 +++++ src/battery-stats/BatteryStatsLogger.h | 42 +++++ src/battery-stats/BatteryStatsProvider.cpp | 40 +++++ src/battery-stats/BatteryStatsProvider.h | 40 +++++ src/battery-stats/BatteryUsage.cpp | 65 +++++++ src/battery-stats/BatteryUsage.h | 34 ++++ src/battery-stats/BatteryUsageAnalyzer.cpp | 81 +++++++++ src/battery-stats/BatteryUsageAnalyzer.h | 40 +++++ src/battery-stats/CMakeLists.txt | 19 ++ src/battery-stats/CreateProvider.cpp | 31 ++++ src/battery-stats/HeartDbReader.cpp | 135 ++++++++++++++ src/battery-stats/HeartDbReader.h | 46 +++++ src/battery-stats/Querier.cpp | 88 +++++++++ src/battery-stats/Querier.h | 50 ++++++ src/battery-stats/RecentBatteryUsage.cpp | 50 ++++++ src/battery-stats/RecentBatteryUsage.h | 33 ++++ 21 files changed, 1240 insertions(+) create mode 100644 src/battery-stats/BatteryMonitor.cpp create mode 100644 src/battery-stats/BatteryMonitor.h create mode 100644 src/battery-stats/BatteryStatisticsTypes.h create mode 100644 src/battery-stats/BatteryStatsLogger.cpp create mode 100644 src/battery-stats/BatteryStatsLogger.h create mode 100644 src/battery-stats/BatteryStatsProvider.cpp create mode 100644 src/battery-stats/BatteryStatsProvider.h create mode 100644 src/battery-stats/BatteryUsage.cpp create mode 100644 src/battery-stats/BatteryUsage.h create mode 100644 src/battery-stats/BatteryUsageAnalyzer.cpp create mode 100644 src/battery-stats/BatteryUsageAnalyzer.h create mode 100644 src/battery-stats/CMakeLists.txt create mode 100644 src/battery-stats/CreateProvider.cpp create mode 100644 src/battery-stats/HeartDbReader.cpp create mode 100644 src/battery-stats/HeartDbReader.h create mode 100644 src/battery-stats/Querier.cpp create mode 100644 src/battery-stats/Querier.h create mode 100644 src/battery-stats/RecentBatteryUsage.cpp create mode 100644 src/battery-stats/RecentBatteryUsage.h diff --git a/include/ProviderList.h b/include/ProviderList.h index 3042ca2..4da36a8 100644 --- a/include/ProviderList.h +++ b/include/ProviderList.h @@ -39,6 +39,7 @@ const struct { } subjectLibraryList[] = { {SUBJ_ACTIVITY, "activity"}, {SUBJ_APP_STATS, "app-stats"}, + {SUBJ_BATTERY_STATS, "battery-stats"}, {SUBJ_STATE_CALL, "call"}, {SUBJ_STATE_CONTACTS, "contacts"}, {SUBJ_CUSTOM, "custom"}, diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index f41f86b..30d980b 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,6 +14,7 @@ ADD_SUBDIRECTORY(wifi) IF("${PROFILE}" STREQUAL "mobile") ADD_SUBDIRECTORY(app-stats) +ADD_SUBDIRECTORY(battery-stats) ADD_SUBDIRECTORY(call) ADD_SUBDIRECTORY(contacts) ADD_SUBDIRECTORY(email) diff --git a/src/battery-stats/BatteryMonitor.cpp b/src/battery-stats/BatteryMonitor.cpp new file mode 100644 index 0000000..6c9ba5d --- /dev/null +++ b/src/battery-stats/BatteryMonitor.cpp @@ -0,0 +1,280 @@ +/* + * 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 +#include "BatteryStatisticsTypes.h" +#include "HeartDbReader.h" +#include "BatteryMonitor.h" + +#define DEFAULT_ROW_ID_STR "1" + +using namespace ctx; + +static int __lastResetTime = 0; +static int __lastPercent = -1; +static int __lastPercentTime = 0; +static bool __isCharging = 0; +static std::vector __batteryTimeInfoVec; + + +BatteryMonitor::BatteryMonitor() +{ + __initialize(); +} + +BatteryMonitor::~BatteryMonitor() +{ +} + +void BatteryMonitor::__initialize() +{ + std::vector records; + __dbMgr.executeSync( + "CREATE TABLE IF NOT EXISTS " BATTERY_USAGE_TABLE \ + " (" BATTERY_USAGE_TABLE_COLUMNS ")", &records); + + __dbMgr.executeSync( + "CREATE TABLE IF NOT EXISTS " BATTERY_LAST_INFO_TABLE \ + " (" BATTERY_LAST_INFO_TABLE_COLUMNS ")", &records); + + __dbMgr.createTableSync(BATTERY_TEMP_TIME_INFO, BATTERY_TEMP_TIME_INFO_COLUMNS, NULL); +} + +bool BatteryMonitor::__loadLastInfo() +{ + device_battery_is_charging(&__isCharging); + + std::vector records; + bool ret = __dbMgr.executeSync( + "SELECT * FROM " BATTERY_LAST_INFO_TABLE \ + " WHERE " BATTERY_ROW_ID " = " DEFAULT_ROW_ID_STR, &records); + IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to load last info"); + + if (records.size() == 1) { + records[0].get(NULL, BATTERY_LAST_RESET_TIME, &__lastResetTime); + records[0].get(NULL, BATTERY_LAST_PERCENT, &__lastPercent); + records[0].get(NULL, BATTERY_LAST_PERCENT_TIME, &__lastPercentTime); + } + records.clear(); + + __batteryTimeInfoVec.clear(); + ret = __dbMgr.executeSync("SELECT * FROM " BATTERY_TEMP_TIME_INFO , &__batteryTimeInfoVec); + + ret = __dbMgr.executeSync("DELETE FROM " BATTERY_TEMP_TIME_INFO, &records); + + return true; +} + +bool BatteryMonitor::__updateLastInfo() +{ + if (__batteryTimeInfoVec.size() > 0) { + for (unsigned int i = 0; i < __batteryTimeInfoVec.size(); i++) { + int64_t rowId; + __dbMgr.insertSync(BATTERY_TEMP_TIME_INFO, __batteryTimeInfoVec.at(i), &rowId); + } + } + + IF_FAIL_RETURN_TAG(__lastResetTime != 0 || __lastPercentTime != 0, false, _W, "Last info doesn't exist"); + + char *query = sqlite3_mprintf( + "INSERT OR REPLACE INTO " BATTERY_LAST_INFO_TABLE " (" \ + BATTERY_ROW_ID ", " BATTERY_LAST_RESET_TIME ", " \ + BATTERY_LAST_PERCENT ", " BATTERY_LAST_PERCENT_TIME ") VALUES (%s, %d, %d, %d)", + DEFAULT_ROW_ID_STR, __lastResetTime, __lastPercent, __lastPercentTime); + + std::vector records; + bool ret = __dbMgr.executeSync(query, &records); + sqlite3_free(query); + IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to update battery stat last info"); + + return true; +} + +void BatteryMonitor::__batteryChangeCb(device_callback_e type, void* value, void* userData) +{ + IF_FAIL_VOID(type == DEVICE_CALLBACK_BATTERY_CAPACITY); + + int percent = intptr_t(value); + int currentTime = CURRENT_TIME; + BatteryMonitor* instance = static_cast(userData); + + if (!__isCharging && percent == (__lastPercent - 1) && __lastPercentTime != 0) { + _D("Battery capacity decreased: %d% -> %d%", __lastPercent, percent); + + Json battTimeInfo; + battTimeInfo.set(NULL, BATTERY_AMOUNT, percent); + battTimeInfo.set(NULL, BATTERY_START_TIME, __lastPercentTime); + battTimeInfo.set(NULL, BATTERY_END_TIME, currentTime); + __batteryTimeInfoVec.push_back(battTimeInfo); + + instance->processBatteryUsage(); + } + + __lastPercentTime = currentTime; + __lastPercent = percent; +} + +void BatteryMonitor::__chargerChangeCb(device_callback_e type, void* value, void* userData) +{ + IF_FAIL_VOID(type == DEVICE_CALLBACK_BATTERY_CHARGING); + + __isCharging = intptr_t(value); + IF_FAIL_VOID(!__isCharging); + + int percent; + if (__lastPercent < 0) { + int error = device_battery_get_percent(&percent); + IF_FAIL_VOID_TAG(error == DEVICE_ERROR_NONE, _E, "Failed to get battery capacity"); + } else { + percent = __lastPercent; + } + + // If charger is disconnected after 100% charged + if (percent == 100) { + __lastResetTime = CURRENT_TIME; + __lastPercentTime = __lastResetTime; + _D("Charger is disconnected after fully charged. ResetTime: %d", __lastResetTime); + } +} + +int BatteryMonitor::start() +{ + __loadLastInfo(); + + int error = device_add_callback(DEVICE_CALLBACK_BATTERY_CAPACITY, __batteryChangeCb, this); + IF_FAIL_RETURN_TAG(error == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Failed to set battery capacity change cb"); + + error = device_add_callback(DEVICE_CALLBACK_BATTERY_CHARGING, __chargerChangeCb, NULL); + IF_FAIL_RETURN_TAG(error == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Failed to set battery charging change cb"); + + return ERR_NONE; +} + +int BatteryMonitor::stop() +{ + __updateLastInfo(); + + int error = device_remove_callback(DEVICE_CALLBACK_BATTERY_CAPACITY, __batteryChangeCb); + IF_FAIL_RETURN_TAG(error == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Failed to remove callback for battery capacity"); + + error = device_remove_callback(DEVICE_CALLBACK_BATTERY_CHARGING, __chargerChangeCb); + IF_FAIL_RETURN_TAG(error == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Failed to remove callback for charger status"); + + return ERR_NONE; +} + +bool BatteryMonitor::processBatteryUsage() +{ + IF_FAIL_RETURN_TAG(__batteryTimeInfoVec.size() > 0, true, _D, "All per-app battery usages are already calculated"); + + int totalStartTime; + int totalEndTime; + __batteryTimeInfoVec.front().get(NULL, BATTERY_START_TIME, &totalStartTime); + __batteryTimeInfoVec.back().get(NULL, BATTERY_END_TIME, &totalEndTime); + + // Read cpu table from heart db for time span of stacked in __batteryTimeInfoVec + HeartDbReader heartReader; + bool ret = heartReader.open(); + IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to open heart db"); + + std::vector appLog; + ret = heartReader.readAppLaunchLog(totalStartTime, totalEndTime, &appLog); + heartReader.close(); + IF_FAIL_RETURN_TAG(ret, false, _E, "Cannot read from heart cpu table"); + IF_FAIL_RETURN_TAG(appLog.size() > 0, true, _W, "Heart cpu data is not prepared yet (%d ~ %d)", totalStartTime, totalEndTime); + _D("Read %d rows from heart cpu table from %d to %d", appLog.size(), totalStartTime, totalEndTime); + + // Get the last timestamp of HEART cpu data + int lastHeartTimestamp; + appLog.back().get(NULL, BATTERY_TIMESTAMP, &lastHeartTimestamp); + + unsigned int i; + for (i = 0; i < __batteryTimeInfoVec.size(); i++) { + int startTime; + int endTime; + + Json row = __batteryTimeInfoVec[i].str(); + row.get(NULL, BATTERY_START_TIME, &startTime); + row.get(NULL, BATTERY_END_TIME, &endTime); + + if (endTime > lastHeartTimestamp) { + _W("[%d] Heart cpu data is not prepared yet (%d ~ %d)", i, startTime, endTime); + break; + } + + // Calculate per app battery usage + std::vector usage; + ret = __analyzer.calculateBatteryUsage(startTime, endTime, appLog, &usage); + if (!ret) { + _E("[%d] Failed to calculate battery usage (%d ~ %d)", i, startTime, endTime); + continue; + } + _D("[%d] Battery usage per app calculated (%d ~ %d)", i, startTime, endTime); + + // Insert battery usage + ret = __insertUsageLog(usage); + if (!ret) { + _E("Failed to insert per app battery usage"); + } + } + + // Remove completed time info + _D("Total %d time intervals, %d intervals are calculated", __batteryTimeInfoVec.size(), i); + __batteryTimeInfoVec.erase(__batteryTimeInfoVec.begin(), __batteryTimeInfoVec.begin() + i); + + return true; +} + +bool BatteryMonitor::__insertUsageLog(std::vector& usage) +{ + IF_FAIL_RETURN_TAG(usage.size(), true, _W, "No data"); + std::string query = std::string("INSERT INTO " BATTERY_USAGE_TABLE \ + "(" BATTERY_APP_ID ", " BATTERY_START_TIME ", " BATTERY_END_TIME "," BATTERY_AMOUNT ") VALUES"); + + std::string appId; + int startTime; + int endTime; + double amount; + + for (unsigned int i = 0; i < usage.size(); i++) { + usage[i].get(NULL, BATTERY_APP_ID, &appId); + usage[i].get(NULL, BATTERY_START_TIME, &startTime); + usage[i].get(NULL, BATTERY_END_TIME, &endTime); + usage[i].get(NULL, BATTERY_AMOUNT, &amount); + + query += std::string(" ('" + appId + "', " + std::to_string(startTime) + ", " + + std::to_string(endTime) + ", " + std::to_string((int) (amount * 10000)) + ")"); + + if (i != usage.size() - 1 ) { + query += ", "; + } + } + + _D("Insert %d rows of per app battery usage", usage.size()); + std::vector records; + return __dbMgr.executeSync(query.c_str(), &records); +} + +int BatteryMonitor::getLastResetTime() +{ + IF_FAIL_RETURN_TAG(__lastResetTime != 0, CURRENT_TIME, _D, "Last reset time doesn't exist"); + return __lastResetTime; +} diff --git a/src/battery-stats/BatteryMonitor.h b/src/battery-stats/BatteryMonitor.h new file mode 100644 index 0000000..361a08f --- /dev/null +++ b/src/battery-stats/BatteryMonitor.h @@ -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. + */ + +#ifndef _CONTEXT_BATTERY_MONITOR_H_ +#define _CONTEXT_BATTERY_MONITOR_H_ + +#include +#include +#include +#include "BatteryUsageAnalyzer.h" + +namespace ctx { + + class BatteryMonitor { + public: + BatteryMonitor(); + ~BatteryMonitor(); + + int start(); + int stop(); + + static int getLastResetTime(); + bool processBatteryUsage(); + + private: + void __initialize(); + bool __loadLastInfo(); + bool __updateLastInfo(); + + static void __batteryChangeCb(device_callback_e type, void* value, void* userData); + static void __chargerChangeCb(device_callback_e type, void* value, void* userData); + + bool __insertUsageLog(std::vector& usage); + + DatabaseManager __dbMgr; + BatteryUsageAnalyzer __analyzer; + + }; + +} /* namespace ctx */ + +#endif /* _CONTEXT_BATTERY_MONITOR_H_ */ diff --git a/src/battery-stats/BatteryStatisticsTypes.h b/src/battery-stats/BatteryStatisticsTypes.h new file mode 100644 index 0000000..dc43678 --- /dev/null +++ b/src/battery-stats/BatteryStatisticsTypes.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_STATS_BATTERY_TYPES_H_ +#define _CONTEXT_STATS_BATTERY_TYPES_H_ + +#include + +#define BATTERY_HISTORY_PRIV PRIV_APP_HISTORY + +#define BATTERY_USAGE_TABLE "Log_BatteryUsagePerApp" +#define BATTERY_USAGE_TABLE_COLUMNS \ + "AppId TEXT NOT NULL, StartTime INTEGER NOT NULL DEFAULT 0, " \ + "EndTime INTEGER NOT NULL DEFAULT 0, Amount INTEGER NOT NULL DEFAULT 0" + +#define BATTERY_LAST_INFO_TABLE "Battery_LastInfo" +#define BATTERY_LAST_INFO_TABLE_COLUMNS \ + "RowId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " \ + "LastResetTime UNSIGNED INT NOT NULL DEFAULT 0, " \ + "LastPercent UNSIGNED INT NOT NULL DEFAULT 0," \ + "LastPercentTime UNSIGNED INT NOT NULL DEFAULT 0" + +#define BATTERY_TEMP_TIME_INFO "Temp_BatteryTimeInfo" +#define BATTERY_TEMP_TIME_INFO_COLUMNS \ + "Amount INTEGER NOT NULL DEFAULT 0, StartTime INTEGER NOT NULL DEFAULT 0, " \ + "EndTime INTEGER NOT NULL DEFAULT 0" + +#define BATTERY_APP_ID "AppId" +#define BATTERY_TIMESTAMP "Timestamp" +#define BATTERY_TYPE "Type" +#define BATTERY_START_TIME "StartTime" +#define BATTERY_END_TIME "EndTime" +#define BATTERY_AMOUNT "Amount" +#define BATTERY_LAST_RESET_TIME "LastResetTime" +#define BATTERY_LAST_PERCENT "LastPercent" +#define BATTERY_LAST_PERCENT_TIME "LastPercentTime" +#define BATTERY_ROW_ID "RowId" + +#define CURRENT_TIME (int)(time(0)) + +enum AppLaunchType { + TYPE_SERVICE = 0, + TYPE_FOREGROUND, + TYPE_BACKGROUND +}; + +#endif /* End of _CONTEXT_STATS_BATTERY_TYPES_H_ */ diff --git a/src/battery-stats/BatteryStatsLogger.cpp b/src/battery-stats/BatteryStatsLogger.cpp new file mode 100644 index 0000000..89e0309 --- /dev/null +++ b/src/battery-stats/BatteryStatsLogger.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 "BatteryStatisticsTypes.h" +#include "BatteryMonitor.h" +#include "BatteryStatsLogger.h" + +using namespace ctx; + +BatteryStatsLogger::BatteryStatsLogger() : + ContextProvider(SUBJ_BATTERY_LOGGER), + __monitor(NULL) +{ + __monitor = new(std::nothrow) BatteryMonitor(); + IF_FAIL_VOID_TAG(__monitor, _E, "Memory allocation failed"); +} + +BatteryStatsLogger::~BatteryStatsLogger() +{ + delete __monitor; +} + +void BatteryStatsLogger::getPrivilege(std::vector &privilege) +{ + privilege.push_back(BATTERY_HISTORY_PRIV); +} + +int BatteryStatsLogger::subscribe(Json option, Json* requestResult) +{ + return __monitor->start(); +} + +int BatteryStatsLogger::unsubscribe(Json option) +{ + return __monitor->stop(); +} diff --git a/src/battery-stats/BatteryStatsLogger.h b/src/battery-stats/BatteryStatsLogger.h new file mode 100644 index 0000000..026b72e --- /dev/null +++ b/src/battery-stats/BatteryStatsLogger.h @@ -0,0 +1,42 @@ +/* + * 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_BATTERY_STATS_LOGGER_H_ +#define _CONTEXT_BATTERY_STATS_LOGGER_H_ + +#include + +namespace ctx { + + class BatteryMonitor; + + class BatteryStatsLogger : public ContextProvider { + public: + BatteryStatsLogger(); + ~BatteryStatsLogger(); + + int subscribe(Json option, Json *requestResult); + int unsubscribe(Json option); + + void getPrivilege(std::vector &privilege); + + private: + BatteryMonitor *__monitor; + }; + +} /* namespace ctx */ + +#endif /* _CONTEXT_BATTERY_STATS_LOGGER_H_ */ diff --git a/src/battery-stats/BatteryStatsProvider.cpp b/src/battery-stats/BatteryStatsProvider.cpp new file mode 100644 index 0000000..53899ff --- /dev/null +++ b/src/battery-stats/BatteryStatsProvider.cpp @@ -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. + */ + +#include "BatteryStatsProvider.h" + +using namespace ctx; + +BatteryStatsProvider::BatteryStatsProvider(const char *subject) : + ContextProvider(subject) +{ +} + +BatteryStatsProvider::~BatteryStatsProvider() +{ +} + +void BatteryStatsProvider::getPrivilege(std::vector &privilege) +{ + privilege.push_back(BATTERY_HISTORY_PRIV); +} + +BatteryStatsQuerier* BatteryStatsProvider::getQuerier(Json option) +{ + BatteryStatsQuerier *querier = new(std::nothrow) BatteryStatsQuerier(this, option); + IF_FAIL_RETURN_TAG(querier, NULL, _E, "Memory allocation failed"); + return querier; +} diff --git a/src/battery-stats/BatteryStatsProvider.h b/src/battery-stats/BatteryStatsProvider.h new file mode 100644 index 0000000..94d0341 --- /dev/null +++ b/src/battery-stats/BatteryStatsProvider.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_BATTERY_STATS_PROVIDER_H_ +#define _CONTEXT_BATTERY_STATS_PROVIDER_H_ + +#include +#include "BatteryStatisticsTypes.h" +#include "Querier.h" + +namespace ctx { + + class BatteryStatsProvider : public ContextProvider { + public: + virtual int read(Json option, Json *requestResult) = 0; + void getPrivilege(std::vector &privilege); + + protected: + BatteryStatsProvider(const char *subject); + virtual ~BatteryStatsProvider(); + + BatteryStatsQuerier* getQuerier(Json option); + }; + +} /* namespace ctx */ + +#endif /* _CONTEXT_BATTERY_STATS_PROVIDER_H_ */ diff --git a/src/battery-stats/BatteryUsage.cpp b/src/battery-stats/BatteryUsage.cpp new file mode 100644 index 0000000..631308d --- /dev/null +++ b/src/battery-stats/BatteryUsage.cpp @@ -0,0 +1,65 @@ +/* + * 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 "BatteryUsage.h" + +#define SECONDS_IN_A_DAY 86400 + +using namespace ctx; + +BatteryUsageProvider::BatteryUsageProvider() : + BatteryStatsProvider(SUBJ_BATTERY_USAGE) +{ +} + +BatteryUsageProvider::~BatteryUsageProvider() +{ +} + +int BatteryUsageProvider::read(Json option, Json *requestResult) +{ + int startTime; + int endTime; + int timeSpan = DEFAULT_TIME_SPAN; + int timeSpanPoint; + + option.get(NULL, KEY_TIME_SPAN, &timeSpan); + timeSpanPoint = CURRENT_TIME - timeSpan * SECONDS_IN_A_DAY; + + if (!option.get(NULL, KEY_START_TIME, &startTime)) { + startTime = timeSpanPoint; + } + + if (!option.get(NULL, KEY_END_TIME, &endTime)) { + endTime = CURRENT_TIME; + } + + int resultSize; + bool hasLimit = option.get(NULL, KEY_RESULT_SIZE, &resultSize); + + BatteryStatsQuerier *querier = getQuerier(option); + IF_FAIL_RETURN(querier, ERR_OPERATION_FAILED); + + int error; + if (hasLimit) { + error = querier->queryRangeLimit((startTime > timeSpanPoint)? startTime : timeSpanPoint, endTime, resultSize); + } else { + error = querier->queryRange((startTime > timeSpanPoint)? startTime : timeSpanPoint, endTime); + } + IF_FAIL_RETURN_TAG(error == ERR_NONE, ERR_OPERATION_FAILED, _E, "Failed to get app battery usage"); + + return ERR_NONE; +} diff --git a/src/battery-stats/BatteryUsage.h b/src/battery-stats/BatteryUsage.h new file mode 100644 index 0000000..f446dd3 --- /dev/null +++ b/src/battery-stats/BatteryUsage.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_BATTERY_USAGE_PROVIDER_H_ +#define _CONTEXT_BATTERY_USAGE_PROVIDER_H_ + +#include "BatteryStatsProvider.h" + +namespace ctx { + + class BatteryUsageProvider : public BatteryStatsProvider { + + public: + BatteryUsageProvider(); + ~BatteryUsageProvider(); + + int read(Json option, Json *requestResult); + }; +} + +#endif /* _CONTEXT_BATTERY_USAGE_PROVIDER_H_ */ diff --git a/src/battery-stats/BatteryUsageAnalyzer.cpp b/src/battery-stats/BatteryUsageAnalyzer.cpp new file mode 100644 index 0000000..e02b7be --- /dev/null +++ b/src/battery-stats/BatteryUsageAnalyzer.cpp @@ -0,0 +1,81 @@ +/* + * 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 "BatteryStatisticsTypes.h" +#include "BatteryUsageAnalyzer.h" + +using namespace ctx; + +bool BatteryUsageAnalyzer::calculateBatteryUsage(int lastTime, int currTime, std::vector& appLog, std::vector* usage) +{ + int timeInterval = currTime - lastTime; + IF_FAIL_RETURN(timeInterval > 0, false); + + std::map lastAppTimeMap; + std::string appId; + int timestamp; + int type; + + for (unsigned int i = 0; i < appLog.size(); i++) { + appLog[i].get(NULL, BATTERY_APP_ID, &appId); + appLog[i].get(NULL, BATTERY_TIMESTAMP, ×tamp); + appLog[i].get(NULL, BATTERY_TYPE, &type); + + if (timestamp < lastTime) { + continue; + } + + if (timestamp > currTime) { + break; + } + + if (type == TYPE_FOREGROUND) { // Mark timestamp of foreground + lastAppTimeMap[appId] = timestamp; + } else if (type == TYPE_BACKGROUND) { // Foreground duration calculation (Foreground->Background) + Json row; + if (lastAppTimeMap.find(appId) == lastAppTimeMap.end() || lastAppTimeMap[appId] == 0) { + __createBatteryUsage(appId, lastTime, timestamp, timeInterval, &row); + } else { + __createBatteryUsage(appId, lastAppTimeMap[appId], timestamp, timeInterval, &row); + lastAppTimeMap[appId] = 0; + } + usage->push_back(row); + } + } + + // Not closed app + for (auto it = lastAppTimeMap.begin(); it != lastAppTimeMap.end(); it++) { + if (it->second == 0) { + continue; + } + + Json row; + __createBatteryUsage(it->first, it->second, currTime, timeInterval, &row); + usage->push_back(row); + } + + return true; +} + +void BatteryUsageAnalyzer::__createBatteryUsage(std::string appId, int startTime, int endTime, int timeInterval, Json* record) +{ + record->set(NULL, BATTERY_APP_ID, appId); + record->set(NULL, BATTERY_START_TIME, startTime); + record->set(NULL, BATTERY_END_TIME, endTime); + record->set(NULL, BATTERY_AMOUNT, (double)(endTime - startTime) / (double)timeInterval); +} diff --git a/src/battery-stats/BatteryUsageAnalyzer.h b/src/battery-stats/BatteryUsageAnalyzer.h new file mode 100644 index 0000000..982ca59 --- /dev/null +++ b/src/battery-stats/BatteryUsageAnalyzer.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_BATTERY_USAGE_ANALYZER_H_ +#define _CONTEXT_BATTERY_USAGE_ANALYZER_H_ + +#include +#include + +namespace ctx { + + class BatteryUsageAnalyzer { + + public: + BatteryUsageAnalyzer() {}; + ~BatteryUsageAnalyzer() {}; + + bool calculateBatteryUsage(int lastTime, int currTime, std::vector& appLog, std::vector* usage); + + private: + void __createBatteryUsage(std::string appId, int startTime, int endTime, int timeInterval, Json* record); + + }; + +} /* namespace ctx */ + +#endif /* _CONTEXT_BATTERY_USAGE_ANALYZER_H_ */ diff --git a/src/battery-stats/CMakeLists.txt b/src/battery-stats/CMakeLists.txt new file mode 100644 index 0000000..00fbdf8 --- /dev/null +++ b/src/battery-stats/CMakeLists.txt @@ -0,0 +1,19 @@ +SET(target "${target_prefix}-battery-stats") + +SET(DEPS ${DEPS} + capi-system-device +) + +FILE(GLOB SRCS *.cpp) + +INCLUDE(FindPkgConfig) +PKG_CHECK_MODULES(PKG_BATTERY_STATS REQUIRED ${DEPS}) + +FOREACH(flag ${PKG_BATTERY_STATS_CFLAGS}) + SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}") +ENDFOREACH(flag) + +ADD_LIBRARY(${target} SHARED ${SRCS}) +TARGET_LINK_LIBRARIES(${target} ${PKG_BATTERY_LDFLAGS} ${target_shared}) + +INSTALL(TARGETS ${target} DESTINATION ${CMAKE_INSTALL_LIBDIR}/${target_dir}) diff --git a/src/battery-stats/CreateProvider.cpp b/src/battery-stats/CreateProvider.cpp new file mode 100644 index 0000000..c1c07e9 --- /dev/null +++ b/src/battery-stats/CreateProvider.cpp @@ -0,0 +1,31 @@ +/* + * 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 "BatteryStatsLogger.h" +#include "BatteryUsage.h" +#include "RecentBatteryUsage.h" + +using namespace ctx; + +extern "C" SO_EXPORT ContextProvider* CreateProvider(const char *subject) +{ + ADD_PROVIDER(SUBJ_BATTERY_LOGGER, BatteryStatsLogger); + ADD_PROVIDER(SUBJ_BATTERY_USAGE, BatteryUsageProvider); + ADD_PROVIDER(SUBJ_BATTERY_RECENT_USAGE, RecentBatteryUsageProvider); + + return NULL; +} diff --git a/src/battery-stats/HeartDbReader.cpp b/src/battery-stats/HeartDbReader.cpp new file mode 100644 index 0000000..dcb5efc --- /dev/null +++ b/src/battery-stats/HeartDbReader.cpp @@ -0,0 +1,135 @@ +/* + * 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 "BatteryStatisticsTypes.h" +#include "HeartDbReader.h" + +#define HEART_CPU_TABLE "cpu" +#define HEART_APP_ID "appid" +#define HEART_TIME "time" +#define HEART_DATA "data" + +#ifdef LEGACY_FILE_PATH +#define HEART_DB_PATH "/opt/usr/dbspace/.resourced-logging.db" +#else +#include +#define HEART_DB_PATH tzplatform_mkpath(TZ_USER_DB, ".resourced-heart-default.db") +#endif + +using namespace ctx; + +HeartDbReader::HeartDbReader() : + __heartDb(NULL) +{ +} + +HeartDbReader::~HeartDbReader() +{ + if (__heartDb) { + close(); + } +} + +bool HeartDbReader::open() +{ + sqlite3 *db = NULL; + int ret; + ret = sqlite3_open_v2(HEART_DB_PATH, &db, SQLITE_OPEN_READONLY, NULL); + IF_FAIL_RETURN_TAG(ret == SQLITE_OK, false, _E, "Failed to open HEART db: %s", sqlite3_errmsg(db)); + + __heartDb = db; + + return true; +} + +void HeartDbReader::close() +{ + sqlite3_close(__heartDb); + __heartDb = NULL; +} + +bool HeartDbReader::readAppLaunchLog(int startTime, int endTime, std::vector* appLog) +{ + IF_FAIL_RETURN(__heartDb, false); + + char* sql = sqlite3_mprintf( + "SELECT " HEART_APP_ID ", " HEART_TIME ", " HEART_DATA " FROM " HEART_CPU_TABLE \ + " WHERE " HEART_TIME " >= %d AND " HEART_TIME " < %d", startTime, endTime); + + char* err = NULL; + int ret = sqlite3_exec(__heartDb, sql, __appLaunchLogCb, appLog, &err); + sqlite3_free(sql); + if (ret != SQLITE_OK) { + _E("Failed to read heart DB: Error(%s)", err); + sqlite3_free(err); + return false; + } + + return true; +} + +int HeartDbReader::__appLaunchLogCb(void *userData, int dim, char **value, char **column) +{ + IF_FAIL_RETURN(userData, 0); + + std::vector *records = static_cast*>(userData); + Json row; + Json newRow; + bool columnNull = false; + + for (int i = 0; i < dim; ++i) { + if (!value[i]) { + columnNull = true; + _W(RED("Null columns exist")); + break; + } + + row.set(NULL, column[i], value[i]); + } + + if (!columnNull) { + __convertAppLaunchLog(row, &newRow); + records->push_back(newRow); + } + + return 0; +} + +void HeartDbReader::__convertAppLaunchLog(Json& row, Json* newRow) +{ + std::string appId; + std::string timestamp; + std::string data; +/* int utime; + int stime; + int pid; + int type; +*/ + row.get(NULL, HEART_APP_ID, &appId); + row.get(NULL, HEART_TIME, ×tamp); + row.get(NULL, HEART_DATA, &data); +/* + std::stringstream buf = data; // TODO use utim & stime + buf >> utime >> stime >> pid >> type; +*/ + std::string type = data.substr(data.length() - 2, 1); + + newRow->set(NULL, BATTERY_APP_ID, appId); + newRow->set(NULL, BATTERY_TIMESTAMP, atoi(timestamp.c_str())); + newRow->set(NULL, BATTERY_TYPE, atoi(type.c_str())); +} diff --git a/src/battery-stats/HeartDbReader.h b/src/battery-stats/HeartDbReader.h new file mode 100644 index 0000000..f355233 --- /dev/null +++ b/src/battery-stats/HeartDbReader.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2016 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _CONTEXT_HEART_DB_READER_H_ +#define _CONTEXT_HEART_DB_READER_H_ + +#include +#include +#include + +namespace ctx { + + class HeartDbReader { + + public: + HeartDbReader(); + ~HeartDbReader(); + + bool open(); + void close(); + + bool readAppLaunchLog(int startTime, int endTime, std::vector* appLog); + + private: + static int __appLaunchLogCb(void *userData, int dim, char **value, char **column); + static void __convertAppLaunchLog(Json& row, Json* newRow); + + sqlite3 *__heartDb; + }; + +} /* namespace ctx */ + +#endif /* _CONTEXT_HEART_DB_READER_H_ */ diff --git a/src/battery-stats/Querier.cpp b/src/battery-stats/Querier.cpp new file mode 100644 index 0000000..f0f043a --- /dev/null +++ b/src/battery-stats/Querier.cpp @@ -0,0 +1,88 @@ +/* + * 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 "BatteryStatisticsTypes.h" +#include "Querier.h" + +#define BATTERY_USAGE_DEFAULT_QUERY \ + "SELECT " BATTERY_APP_ID " AS " KEY_APP_ID ", ROUND(SUM(" BATTERY_AMOUNT ")/10000.0, 2) AS " KEY_TOTAL_AMOUNT \ + " FROM " BATTERY_USAGE_TABLE " WHERE " BATTERY_START_TIME " >= %d AND " BATTERY_END_TIME " <= %d" \ + " GROUP BY " KEY_APP_ID " ORDER BY " KEY_TOTAL_AMOUNT " DESC" + +using namespace ctx; + +BatteryStatsQuerier::BatteryStatsQuerier(ContextProvider *provider, Json option) : + __provider(provider), + __option(option) +{ +} + +BatteryStatsQuerier::~BatteryStatsQuerier() +{ +} + +int BatteryStatsQuerier::query(const char *sql) +{ + return __dbMgr.execute(0, sql, this) ? ERR_NONE : ERR_OPERATION_FAILED; +} + +int BatteryStatsQuerier::queryRange(int startTime, int endTime) +{ + char *sql = sqlite3_mprintf(BATTERY_USAGE_DEFAULT_QUERY, startTime, endTime); + + int error = query(sql); + sqlite3_free(sql); + + return error; +} + +int BatteryStatsQuerier::queryRangeLimit(int startTime, int endTime, int resultSize) +{ + char *sql = sqlite3_mprintf(BATTERY_USAGE_DEFAULT_QUERY " LIMIT %d", startTime, endTime, resultSize); + + int error = query(sql); + sqlite3_free(sql); + + return error; +} + +void BatteryStatsQuerier::onTableCreated(unsigned int queryId, int error) +{ +} + +void BatteryStatsQuerier::onInserted(unsigned int queryId, int error, int64_t rowId) +{ +} + +void BatteryStatsQuerier::onExecuted(unsigned int queryId, int error, std::vector& records) +{ + Json response; + __convertToResponse(records, response); + __provider->replyToRead(__option, error, response); + + delete this; +} + +void BatteryStatsQuerier::__convertToResponse(std::vector &sqlResult, Json &response) +{ + response = "{\"" KEY_QUERY_RESULT "\":[]}"; + + for (Json& tuple : sqlResult) { + response.append(NULL, KEY_QUERY_RESULT, tuple); + } +} diff --git a/src/battery-stats/Querier.h b/src/battery-stats/Querier.h new file mode 100644 index 0000000..2385a2f --- /dev/null +++ b/src/battery-stats/Querier.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_BATTERY_STATS_QUERIER_H_ +#define _CONTEXT_BATTERY_STATS_QUERIER_H_ + +#include +#include + +namespace ctx { + + class BatteryStatsQuerier : public IDatabaseListener { + public: + BatteryStatsQuerier(ContextProvider *provider, Json option); + ~BatteryStatsQuerier(); + + // For now, Default result size(10) isn't applied, unlike other history type. + int queryRange(int startTime, int endTime); + int queryRangeLimit(int startTime, int endTime, int resultSize); + + 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_BATTERY_STATS_QUERIER_H_ */ diff --git a/src/battery-stats/RecentBatteryUsage.cpp b/src/battery-stats/RecentBatteryUsage.cpp new file mode 100644 index 0000000..0663650 --- /dev/null +++ b/src/battery-stats/RecentBatteryUsage.cpp @@ -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. + */ + +#include "BatteryMonitor.h" +#include "RecentBatteryUsage.h" + +using namespace ctx; + +RecentBatteryUsageProvider::RecentBatteryUsageProvider() : + BatteryStatsProvider(SUBJ_BATTERY_RECENT_USAGE) +{ +} + +RecentBatteryUsageProvider::~RecentBatteryUsageProvider() +{ +} + +int RecentBatteryUsageProvider::read(Json option, Json *requestResult) +{ + int resultSize; + bool hasLimit = option.get(NULL, KEY_RESULT_SIZE, &resultSize); + + BatteryStatsQuerier *querier = getQuerier(option); + IF_FAIL_RETURN(querier, ERR_OPERATION_FAILED); + + int error; + if (hasLimit) { + error = querier->queryRangeLimit(BatteryMonitor::getLastResetTime(), CURRENT_TIME, resultSize); + } else { + error = querier->queryRange(BatteryMonitor::getLastResetTime(), CURRENT_TIME); + } + IF_FAIL_RETURN_TAG(error == ERR_NONE, ERR_OPERATION_FAILED, _E, "Failed to get recent app battery usage"); + + return ERR_NONE; +} + + diff --git a/src/battery-stats/RecentBatteryUsage.h b/src/battery-stats/RecentBatteryUsage.h new file mode 100644 index 0000000..2cb7c54 --- /dev/null +++ b/src/battery-stats/RecentBatteryUsage.h @@ -0,0 +1,33 @@ +/* + * 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_RECENT_BATTERY_USAGE_PROVIDER_H_ +#define _CONTEXT_RECENT_BATTERY_USAGE_PROVIDER_H_ + +#include "BatteryStatsProvider.h" + +namespace ctx { + + class RecentBatteryUsageProvider : public BatteryStatsProvider { + public: + RecentBatteryUsageProvider(); + ~RecentBatteryUsageProvider(); + + int read(Json option, Json *requestResult); + }; +} + +#endif /* _CONTEXT_RECENT_BATTERY_USAGE_PROVIDER_H_ */ -- 2.7.4 From bb04e71adf07d98d0059778ae8e6481f974cd0dd Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Wed, 7 Sep 2016 21:18:33 +0900 Subject: [PATCH 04/16] Version 0.9.6 Change-Id: I5282c2984a524aa14bf9a067a3b5510ec076f179 Signed-off-by: Mu-Woong Lee --- packaging/context-provider.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index 7e7b0b5..af282f9 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -1,6 +1,6 @@ Name: context-provider Summary: Context Provider -Version: 0.9.5 +Version: 0.9.6 Release: 1 Group: Service/Context License: Apache-2.0 -- 2.7.4 From 6307f226dabf315cd181ba5c695eace208e04723 Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Fri, 9 Sep 2016 17:44:00 +0900 Subject: [PATCH 05/16] Fix coding rule violations Change-Id: Ifed0d9c3accdb5f1de3957591fa86ce9d85708e7 Signed-off-by: Somin Kim --- src/app-stats/app_inactive_detector/InactiveDetectorStorage.cpp | 2 +- src/prediction/assoc_rule_miner.cpp | 2 +- src/prediction/assoc_rule_producer.h | 4 ++-- src/prediction/basket_compressor.cpp | 4 ++-- src/prediction/item_catalogue.cpp | 2 +- src/prediction/item_catalogue.h | 4 ++-- src/prediction/weight_apriori.cpp | 2 +- src/prediction/weight_apriori.h | 2 +- src/social-stats/LogAggregator.cpp | 2 +- 9 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/app-stats/app_inactive_detector/InactiveDetectorStorage.cpp b/src/app-stats/app_inactive_detector/InactiveDetectorStorage.cpp index 7fd11a7..8349947 100644 --- a/src/app-stats/app_inactive_detector/InactiveDetectorStorage.cpp +++ b/src/app-stats/app_inactive_detector/InactiveDetectorStorage.cpp @@ -178,7 +178,7 @@ void ctx::InactiveDetectorStorage::__injectParams(std::string& str, const std::s return; size_t startPos = 0; - while((startPos = str.find(from, startPos)) != std::string::npos) { + while ((startPos = str.find(from, startPos)) != std::string::npos) { str.replace(startPos, from.length(), to); startPos += to.length(); } diff --git a/src/prediction/assoc_rule_miner.cpp b/src/prediction/assoc_rule_miner.cpp index a639af8..38affde 100644 --- a/src/prediction/assoc_rule_miner.cpp +++ b/src/prediction/assoc_rule_miner.cpp @@ -30,7 +30,7 @@ std::list ctx::AssocRuleMiner::mine_from_baskets( std::string consequentCategory) { SingleCategoryItemIdFilter itemIdFilter(consequentCategory, itemCatalogue); - BasketFilter::filter_in_place(initBaskets,itemIdFilter); + BasketFilter::filter_in_place(initBaskets, itemIdFilter); std::list compressedBaskets = BasketCompressor::compress(initBaskets); diff --git a/src/prediction/assoc_rule_producer.h b/src/prediction/assoc_rule_producer.h index 2b02b79..17c5d3a 100644 --- a/src/prediction/assoc_rule_producer.h +++ b/src/prediction/assoc_rule_producer.h @@ -28,14 +28,14 @@ namespace ctx { public: static std::list generate_rules( - const std::list> &freqItemIdSets, + const std::list> &freqItemIdSets, const IItemIdFilter &itemIdFilter, double minConfidence); static AssocRuleOfIds rule_template(const ItemIdSet &sourceItemIdSet, const IItemIdFilter &antecedentItemIdFilter); private: - static double supportOf(const std::list> &allFreqItemIdSets, const ItemIdSet &wanted); + static double supportOf(const std::list> &allFreqItemIdSets, const ItemIdSet &wanted); }; diff --git a/src/prediction/basket_compressor.cpp b/src/prediction/basket_compressor.cpp index f46c40d..31086bd 100644 --- a/src/prediction/basket_compressor.cpp +++ b/src/prediction/basket_compressor.cpp @@ -29,7 +29,7 @@ std::string ctx::BasketCompressor::itemset_string(const ctx::ItemIdSet& itemIdSe std::list ctx::BasketCompressor::compress(const std::list& inputBaskets) { - std::map basketsMap; + std::map basketsMap; // TODO: maybe it is worth to resign from string keys and use std::map instead. for (const Basket& basket : inputBaskets) { @@ -37,7 +37,7 @@ std::list ctx::BasketCompressor::compress(const std::list(itemSetStr, basket)); + basketsMap.insert(std::pair(itemSetStr, basket)); } else { Basket& compressedBasket = findResult->second; compressedBasket.weight += basket.weight; diff --git a/src/prediction/item_catalogue.cpp b/src/prediction/item_catalogue.cpp index 666b5a8..57189c4 100644 --- a/src/prediction/item_catalogue.cpp +++ b/src/prediction/item_catalogue.cpp @@ -20,7 +20,7 @@ int ctx::ItemCatalogue::id_of(const ctx::Item& item) { std::string s = ItemStringConverter::item_to_string(item); - std::map::iterator it = mItemIdsOfStrings.find(s); + std::map::iterator it = mItemIdsOfStrings.find(s); if (it == mItemIdsOfStrings.end()) { // new item mMaxId++; mItemIdsOfStrings[s] = mMaxId; diff --git a/src/prediction/item_catalogue.h b/src/prediction/item_catalogue.h index 404765b..92f727d 100644 --- a/src/prediction/item_catalogue.h +++ b/src/prediction/item_catalogue.h @@ -40,10 +40,10 @@ namespace ctx { private: /* Translates item string to its id */ - std::map mItemIdsOfStrings; + std::map mItemIdsOfStrings; /* Translating category string to int */ - std::map> mCategoryItemIds; + std::map> mCategoryItemIds; /* Stores item strings (index is item's id) */ std::vector mItemStrings; diff --git a/src/prediction/weight_apriori.cpp b/src/prediction/weight_apriori.cpp index 92aaebc..c95fe0d 100644 --- a/src/prediction/weight_apriori.cpp +++ b/src/prediction/weight_apriori.cpp @@ -82,7 +82,7 @@ std::list> ctx::WeightApriori::find_frequent_i double support = basketAgregator.supportOf(candidate); if (support >= supportThreshold) { freqItemsetsOfCurrSize.push_back(candidate); - allFreqItemsets.push_back(std::make_pair(candidate,support)); + allFreqItemsets.push_back(std::make_pair(candidate, support)); } } candidates = find_wider_candidates(freqItemsetsOfCurrSize, ++candidateSize); diff --git a/src/prediction/weight_apriori.h b/src/prediction/weight_apriori.h index 6cb493d..2749023 100644 --- a/src/prediction/weight_apriori.h +++ b/src/prediction/weight_apriori.h @@ -32,7 +32,7 @@ namespace ctx { static bool survives_prunning(ItemIdSet &widerCandidate, const std::list &narrowFreqSets); /* Find frequent itemsets along with its support value. */ - static std::list> find_frequent_itemid_sets(BasketsAgregator &basketAgregator, double supportThreshold); + static std::list> find_frequent_itemid_sets(BasketsAgregator &basketAgregator, double supportThreshold); private: static std::list single_size_candidates(BasketsAgregator &basketAgregator); diff --git a/src/social-stats/LogAggregator.cpp b/src/social-stats/LogAggregator.cpp index 63dbfea..fc7576f 100644 --- a/src/social-stats/LogAggregator.cpp +++ b/src/social-stats/LogAggregator.cpp @@ -154,7 +154,7 @@ void ctx::ContactLogAggregator::__insertContactLogList(contacts_list_h list) __dbManager.insert(0, SOCIAL_TABLE_CONTACT_LOG, data, NULL); - } while(contacts_list_next(list) == CONTACTS_ERROR_NONE); + } while (contacts_list_next(list) == CONTACTS_ERROR_NONE); } void ctx::ContactLogAggregator::__removeExpiredLog() -- 2.7.4 From 26505d5222395d8e21a8d46f3506f73fc1553783 Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Wed, 14 Sep 2016 17:31:21 +0200 Subject: [PATCH 06/16] [my-place] Small SVACE fixes. Change-Id: Iceb1c004934a013021a0bae5bcaa8b3ad726b41c Signed-off-by: Marcin Masternak --- src/my-place/facade/UserPlaces.h | 3 +++ src/my-place/visit-detector/LocationLogger.h | 11 +++++++---- src/my-place/visit-detector/VisitDetector.h | 3 +++ src/my-place/visit-detector/WifiLogger.cpp | 1 + 4 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/my-place/facade/UserPlaces.h b/src/my-place/facade/UserPlaces.h index a760a5f..31bac72 100644 --- a/src/my-place/facade/UserPlaces.h +++ b/src/my-place/facade/UserPlaces.h @@ -57,6 +57,9 @@ namespace ctx { bool onTimerExpired(int timerId); + UserPlaces(const UserPlaces&) = delete; + UserPlaces& operator=(const UserPlaces&) = delete; + public: UserPlaces(PlaceRecogMode energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE); ~UserPlaces(); diff --git a/src/my-place/visit-detector/LocationLogger.h b/src/my-place/visit-detector/LocationLogger.h index c3a145c..b901dee 100644 --- a/src/my-place/visit-detector/LocationLogger.h +++ b/src/my-place/visit-detector/LocationLogger.h @@ -64,10 +64,6 @@ namespace ctx { class LocationLogger : public ITimerListener, public IVisitListener { - public: - LocationLogger(ILocationListener *listener = nullptr); - ~LocationLogger(); - private: /* INPUT */ void onVisitStart(); @@ -156,6 +152,13 @@ namespace ctx { double direction, double climb, void *userData); bool __locationManagerRequestSingleLocation(); + LocationLogger(const LocationLogger&) = delete; + LocationLogger& operator=(const LocationLogger&) = delete; + + public: + LocationLogger(ILocationListener *listener = nullptr); + ~LocationLogger(); + }; /* class LocationLogger */ } /* namespace ctx */ diff --git a/src/my-place/visit-detector/VisitDetector.h b/src/my-place/visit-detector/VisitDetector.h index 33faacb..98bbda3 100644 --- a/src/my-place/visit-detector/VisitDetector.h +++ b/src/my-place/visit-detector/VisitDetector.h @@ -92,6 +92,9 @@ namespace ctx { void __categorize(Visit &visit); + VisitDetector(const VisitDetector&) = delete; + VisitDetector& operator=(const VisitDetector&) = delete; + public: VisitDetector(time_t startScan, PlaceRecogMode energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE, bool testMode = false); ~VisitDetector(); diff --git a/src/my-place/visit-detector/WifiLogger.cpp b/src/my-place/visit-detector/WifiLogger.cpp index be688dc..2baa24c 100644 --- a/src/my-place/visit-detector/WifiLogger.cpp +++ b/src/my-place/visit-detector/WifiLogger.cpp @@ -69,6 +69,7 @@ int ctx::WifiLogger::__dbInsertLogs() ctx::WifiLogger::WifiLogger(IWifiListener * listener, PlaceRecogMode energyMode) : __timerOn(false), + __timerId(-1), __intervalMinutes(WIFI_LOGGER_INTERVAL_MINUTES_HIGH_ACCURACY), __listener(listener), __lastScanTime(time_t(0)), -- 2.7.4 From c1512c4b3c9419feb9f7bb35ea6c86624df742c2 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Tue, 27 Sep 2016 19:22:15 +0900 Subject: [PATCH 07/16] Remove unnecessary build macros Change-Id: I5848f82f9426e6d5f26302dabb3e9294d0a9e034 Signed-off-by: Mu-Woong Lee --- packaging/context-provider.spec | 9 +-------- src/battery-stats/HeartDbReader.cpp | 6 +----- 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index af282f9..3d197b0 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -68,10 +68,6 @@ export CXXFLAGS+=" -std=c++0x" #export CFLAGS+=" -Wcast-qual" #export CXXFLAGS+=" -Wcast-qual" -#export CFLAGS+=" -DTIZEN_ENGINEER_MODE" -#export CXXFLAGS+=" -DTIZEN_ENGINEER_MODE" -#export FFLAGS+=" -DTIZEN_ENGINEER_MODE" - cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} -DMAJORVER=${MAJORVER} -DFULLVER=%{version} -DPROFILE=%{?BUILD_PROFILE} make %{?jobs:-j%jobs} @@ -79,9 +75,6 @@ make %{?jobs:-j%jobs} rm -rf %{buildroot} %make_install -mkdir -p %{buildroot}/usr/share/license -cp LICENSE %{buildroot}/usr/share/license/%{name} - %post /sbin/ldconfig @@ -91,9 +84,9 @@ cp LICENSE %{buildroot}/usr/share/license/%{name} %files %manifest packaging/%{name}.manifest %defattr(-,root,root,-) -/usr/share/license/%{name} %{_libdir}/*.so* %{_libdir}/context-service/*.so* +%license LICENSE %package devel Summary: Context Provider Shared Header (Development) diff --git a/src/battery-stats/HeartDbReader.cpp b/src/battery-stats/HeartDbReader.cpp index dcb5efc..5b65b33 100644 --- a/src/battery-stats/HeartDbReader.cpp +++ b/src/battery-stats/HeartDbReader.cpp @@ -15,6 +15,7 @@ */ //#include +#include #include #include "BatteryStatisticsTypes.h" #include "HeartDbReader.h" @@ -24,12 +25,7 @@ #define HEART_TIME "time" #define HEART_DATA "data" -#ifdef LEGACY_FILE_PATH -#define HEART_DB_PATH "/opt/usr/dbspace/.resourced-logging.db" -#else -#include #define HEART_DB_PATH tzplatform_mkpath(TZ_USER_DB, ".resourced-heart-default.db") -#endif using namespace ctx; -- 2.7.4 From ae6494e00bf9c4b5eb7f9e688a518430d36fc6ff Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 14 Oct 2016 15:14:29 +0900 Subject: [PATCH 08/16] Version 0.9.7 Change-Id: Ie7ecfb0eed82c059f2b1ad9d5b9c9e348a15df6c Signed-off-by: Mu-Woong Lee --- packaging/context-provider.spec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index 3d197b0..4c2ed87 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -1,6 +1,6 @@ Name: context-provider Summary: Context Provider -Version: 0.9.6 +Version: 0.9.7 Release: 1 Group: Service/Context License: Apache-2.0 -- 2.7.4 From 6e772451a83b524f9187a11a025f644e52392893 Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Fri, 14 Oct 2016 12:59:42 +0200 Subject: [PATCH 09/16] Remove the macro for the hard-coded so file path Change-Id: I2450e87001b3d64858e3f91b64e1ac6491336698 Signed-off-by: Mu-Woong Lee --- CMakeLists.txt | 1 + include/ProviderList.h | 3 +-- packaging/context-provider.spec | 2 +- src/media-stats/MediaContentMonitor.cpp | 2 +- src/my-place/facade/UserPlaces.cpp | 2 +- src/my-place/visit-detector/VisitDetector.cpp | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 04316da..303cca7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,7 @@ INCLUDE_DIRECTORIES( ADD_DEFINITIONS(-O2 -Wall -fPIC -fdata-sections -ffunction-sections) ADD_DEFINITIONS(-fvisibility=hidden) ADD_DEFINITIONS(-DLOG_TAG="CONTEXT") +ADD_DEFINITIONS(-D_LIBDIR_="${LIBDIR}") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fPIC -Wl,--as-needed -Wl,--gc-section -Wl,--print-gc-section") # Profiles diff --git a/include/ProviderList.h b/include/ProviderList.h index 4da36a8..6f8dff4 100644 --- a/include/ProviderList.h +++ b/include/ProviderList.h @@ -22,8 +22,7 @@ #include #include -#define LIB_DIRECTORY "/usr/lib/context-service/" -#define LIB_PREFIX "libctx-prvd-" +#define LIB_PREFIX "/context-service/libctx-prvd-" #define LIB_EXTENSION ".so" /* Json Formats */ diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index 4c2ed87..2a2a1d6 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -68,7 +68,7 @@ export CXXFLAGS+=" -std=c++0x" #export CFLAGS+=" -Wcast-qual" #export CXXFLAGS+=" -Wcast-qual" -cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} -DMAJORVER=${MAJORVER} -DFULLVER=%{version} -DPROFILE=%{?BUILD_PROFILE} +cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} -DLIBDIR=%{_libdir} -DMAJORVER=${MAJORVER} -DFULLVER=%{version} -DPROFILE=%{?BUILD_PROFILE} make %{?jobs:-j%jobs} %install diff --git a/src/media-stats/MediaContentMonitor.cpp b/src/media-stats/MediaContentMonitor.cpp index d99da36..8fe1a06 100644 --- a/src/media-stats/MediaContentMonitor.cpp +++ b/src/media-stats/MediaContentMonitor.cpp @@ -23,7 +23,7 @@ #include "DbHandle.h" #include "MediaContentMonitor.h" -#define SO_PATH "/usr/lib/context-service/libctx-prvd-media-stats-util.so" +#define SO_PATH _LIBDIR_ "context-service/libctx-prvd-media-stats-util.so" #define PLAYCOUNT_RETENTION_PERIOD 259200 /* 1 month in secs */ #define ONE_DAY_IN_SEC 86400 diff --git a/src/my-place/facade/UserPlaces.cpp b/src/my-place/facade/UserPlaces.cpp index 0c593b4..a8e25ea 100755 --- a/src/my-place/facade/UserPlaces.cpp +++ b/src/my-place/facade/UserPlaces.cpp @@ -24,7 +24,7 @@ #include #include -#define SO_PATH "/usr/lib/context-service/libctx-prvd-my-place-places-detector.so" +#define SO_PATH _LIBDIR_ "context-service/libctx-prvd-my-place-places-detector.so" typedef void (*places_detector_t)(); diff --git a/src/my-place/visit-detector/VisitDetector.cpp b/src/my-place/visit-detector/VisitDetector.cpp index f8af125..ac05087 100644 --- a/src/my-place/visit-detector/VisitDetector.cpp +++ b/src/my-place/visit-detector/VisitDetector.cpp @@ -29,7 +29,7 @@ #include #include -#define SO_PATH "/usr/lib/context-service/libctx-prvd-my-place-visit-categer.so" +#define SO_PATH _LIBDIR_ "context-service/libctx-prvd-my-place-visit-categer.so" typedef void (*visit_categer_t)(ctx::Visit &visit); -- 2.7.4 From e736528949fa2e42b169afaf303d924d2ba9009f Mon Sep 17 00:00:00 2001 From: Kunal Date: Thu, 29 Sep 2016 15:53:56 +0900 Subject: [PATCH 10/16] Battery Stats Algorithm modified to include CPU Usage of both background and foreground app events Applied code review comments and coding rules, and bug fixes Change-Id: I264d5b8350da9b6322b5fcbccb265130ffa9b86d Signed-off-by: Kunal --- src/battery-stats/BatteryMonitor.cpp | 130 +++++++++++++++++++++++------ src/battery-stats/BatteryMonitor.h | 4 +- src/battery-stats/BatteryStatisticsTypes.h | 29 ++++++- src/battery-stats/BatteryUsageAnalyzer.cpp | 109 ++++++++++++++++-------- src/battery-stats/BatteryUsageAnalyzer.h | 5 +- src/battery-stats/HeartDbReader.cpp | 32 +++---- src/battery-stats/HeartDbReader.h | 6 +- 7 files changed, 232 insertions(+), 83 deletions(-) diff --git a/src/battery-stats/BatteryMonitor.cpp b/src/battery-stats/BatteryMonitor.cpp index 6c9ba5d..4352019 100644 --- a/src/battery-stats/BatteryMonitor.cpp +++ b/src/battery-stats/BatteryMonitor.cpp @@ -20,7 +20,6 @@ #include #include #include -#include "BatteryStatisticsTypes.h" #include "HeartDbReader.h" #include "BatteryMonitor.h" @@ -31,6 +30,7 @@ using namespace ctx; static int __lastResetTime = 0; static int __lastPercent = -1; static int __lastPercentTime = 0; +static int __lastHeartTimestamp = 0; static bool __isCharging = 0; static std::vector __batteryTimeInfoVec; @@ -55,6 +55,10 @@ void BatteryMonitor::__initialize() "CREATE TABLE IF NOT EXISTS " BATTERY_LAST_INFO_TABLE \ " (" BATTERY_LAST_INFO_TABLE_COLUMNS ")", &records); + __dbMgr.executeSync( + "CREATE TABLE IF NOT EXISTS " BATTERY_LAST_CPU_USAGE_TABLE \ + " (" BATTERY_LAST_CPU_USAGE_TABLE_COLUMNS ")", &records); + __dbMgr.createTableSync(BATTERY_TEMP_TIME_INFO, BATTERY_TEMP_TIME_INFO_COLUMNS, NULL); } @@ -72,11 +76,12 @@ bool BatteryMonitor::__loadLastInfo() records[0].get(NULL, BATTERY_LAST_RESET_TIME, &__lastResetTime); records[0].get(NULL, BATTERY_LAST_PERCENT, &__lastPercent); records[0].get(NULL, BATTERY_LAST_PERCENT_TIME, &__lastPercentTime); + records[0].get(NULL, BATTERY_LAST_HEART_TIMESTAMP, &__lastHeartTimestamp); } records.clear(); __batteryTimeInfoVec.clear(); - ret = __dbMgr.executeSync("SELECT * FROM " BATTERY_TEMP_TIME_INFO , &__batteryTimeInfoVec); + ret = __dbMgr.executeSync("SELECT * FROM " BATTERY_TEMP_TIME_INFO , &__batteryTimeInfoVec); ret = __dbMgr.executeSync("DELETE FROM " BATTERY_TEMP_TIME_INFO, &records); @@ -97,8 +102,8 @@ bool BatteryMonitor::__updateLastInfo() char *query = sqlite3_mprintf( "INSERT OR REPLACE INTO " BATTERY_LAST_INFO_TABLE " (" \ BATTERY_ROW_ID ", " BATTERY_LAST_RESET_TIME ", " \ - BATTERY_LAST_PERCENT ", " BATTERY_LAST_PERCENT_TIME ") VALUES (%s, %d, %d, %d)", - DEFAULT_ROW_ID_STR, __lastResetTime, __lastPercent, __lastPercentTime); + BATTERY_LAST_PERCENT ", " BATTERY_LAST_PERCENT_TIME ", " BATTERY_LAST_HEART_TIMESTAMP ") VALUES (%s, %d, %d, %d, %d)", + DEFAULT_ROW_ID_STR, __lastResetTime, __lastPercent, __lastPercentTime, __lastHeartTimestamp); std::vector records; bool ret = __dbMgr.executeSync(query, &records); @@ -181,6 +186,36 @@ int BatteryMonitor::stop() return ERR_NONE; } +bool BatteryMonitor::__getLastCpuUsageTable(CpuUsageMap* lastCpuUsage) +{ + std::vector lastCpuUsageLog; + bool ret = __dbMgr.executeSync( + "SELECT * FROM " BATTERY_LAST_CPU_USAGE_TABLE, + &lastCpuUsageLog); + IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to load last Cpu Times of Apps"); + + unsigned int k = 0; + std::string appId; + int timestamp; + int stime; + int utime; + + while (k < lastCpuUsageLog.size()) { + lastCpuUsageLog[k].get(NULL, BATTERY_APP_ID, &appId); + lastCpuUsageLog[k].get(NULL, BATTERY_TIMESTAMP, ×tamp); + lastCpuUsageLog[k].get(NULL, BATTERY_UTIME, &utime); + lastCpuUsageLog[k].get(NULL, BATTERY_STIME, &stime); + k++; + + LastAppCpuUsageInfo lastAppCpuUsage; + lastAppCpuUsage.timestamp = timestamp; + lastAppCpuUsage.utime = utime; + lastAppCpuUsage.stime = stime; + (*lastCpuUsage)[appId] = lastAppCpuUsage; + } + return true; +} + bool BatteryMonitor::processBatteryUsage() { IF_FAIL_RETURN_TAG(__batteryTimeInfoVec.size() > 0, true, _D, "All per-app battery usages are already calculated"); @@ -195,16 +230,17 @@ bool BatteryMonitor::processBatteryUsage() bool ret = heartReader.open(); IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to open heart db"); - std::vector appLog; - ret = heartReader.readAppLaunchLog(totalStartTime, totalEndTime, &appLog); + std::vector cpuUsageLog; + ret = heartReader.readCpuUsageLog(totalStartTime, totalEndTime, &cpuUsageLog); heartReader.close(); IF_FAIL_RETURN_TAG(ret, false, _E, "Cannot read from heart cpu table"); - IF_FAIL_RETURN_TAG(appLog.size() > 0, true, _W, "Heart cpu data is not prepared yet (%d ~ %d)", totalStartTime, totalEndTime); - _D("Read %d rows from heart cpu table from %d to %d", appLog.size(), totalStartTime, totalEndTime); + IF_FAIL_RETURN_TAG(cpuUsageLog.size() > 0, true, _W, "Heart cpu data is not prepared yet (%d ~ %d)", totalStartTime, totalEndTime); + _D("Read %d rows from heart cpu table from %d to %d", cpuUsageLog.size(), totalStartTime, totalEndTime); - // Get the last timestamp of HEART cpu data - int lastHeartTimestamp; - appLog.back().get(NULL, BATTERY_TIMESTAMP, &lastHeartTimestamp); + // Get the last timestamp of HEART cpu data and maximum app times tables in cache + cpuUsageLog.back().get(NULL, BATTERY_TIMESTAMP, &__lastHeartTimestamp); + CpuUsageMap lastCpuUsage; + ret = __getLastCpuUsageTable(&lastCpuUsage); unsigned int i; for (i = 0; i < __batteryTimeInfoVec.size(); i++) { @@ -215,14 +251,14 @@ bool BatteryMonitor::processBatteryUsage() row.get(NULL, BATTERY_START_TIME, &startTime); row.get(NULL, BATTERY_END_TIME, &endTime); - if (endTime > lastHeartTimestamp) { + if (endTime > __lastHeartTimestamp) { _W("[%d] Heart cpu data is not prepared yet (%d ~ %d)", i, startTime, endTime); break; } // Calculate per app battery usage std::vector usage; - ret = __analyzer.calculateBatteryUsage(startTime, endTime, appLog, &usage); + ret = __analyzer.calculateBatteryUsage(startTime, endTime, cpuUsageLog, lastCpuUsage, &usage); if (!ret) { _E("[%d] Failed to calculate battery usage (%d ~ %d)", i, startTime, endTime); continue; @@ -230,12 +266,20 @@ bool BatteryMonitor::processBatteryUsage() _D("[%d] Battery usage per app calculated (%d ~ %d)", i, startTime, endTime); // Insert battery usage - ret = __insertUsageLog(usage); + ret = __insertBatteryUsageLog(usage); if (!ret) { _E("Failed to insert per app battery usage"); } } + // Insert log of last times of apps + if (i != 0) { + ret = __insertLastCpuUsageLog(lastCpuUsage); + if (!ret) { + _E("Failed to insert last Cpu Usage of apps"); + } + } + // Remove completed time info _D("Total %d time intervals, %d intervals are calculated", __batteryTimeInfoVec.size(), i); __batteryTimeInfoVec.erase(__batteryTimeInfoVec.begin(), __batteryTimeInfoVec.begin() + i); @@ -243,14 +287,17 @@ bool BatteryMonitor::processBatteryUsage() return true; } -bool BatteryMonitor::__insertUsageLog(std::vector& usage) +bool BatteryMonitor::__insertBatteryUsageLog(std::vector& usage) { IF_FAIL_RETURN_TAG(usage.size(), true, _W, "No data"); - std::string query = std::string("INSERT INTO " BATTERY_USAGE_TABLE \ - "(" BATTERY_APP_ID ", " BATTERY_START_TIME ", " BATTERY_END_TIME "," BATTERY_AMOUNT ") VALUES"); + std::string query("INSERT INTO " BATTERY_USAGE_TABLE \ + "(" BATTERY_APP_ID ", " BATTERY_START_TIME ", " \ + BATTERY_END_TIME ", " BATTERY_UTIME ", " \ + BATTERY_STIME ", " BATTERY_AMOUNT ") VALUES"); std::string appId; int startTime; + int stime, utime; int endTime; double amount; @@ -258,19 +305,54 @@ bool BatteryMonitor::__insertUsageLog(std::vector& usage) usage[i].get(NULL, BATTERY_APP_ID, &appId); usage[i].get(NULL, BATTERY_START_TIME, &startTime); usage[i].get(NULL, BATTERY_END_TIME, &endTime); + usage[i].get(NULL, BATTERY_UTIME, &utime); + usage[i].get(NULL, BATTERY_STIME, &stime); usage[i].get(NULL, BATTERY_AMOUNT, &amount); - query += std::string(" ('" + appId + "', " + std::to_string(startTime) + ", " + - std::to_string(endTime) + ", " + std::to_string((int) (amount * 10000)) + ")"); + query += " ('" + appId + "', " + + std::to_string(startTime) + ", " + + std::to_string(endTime) + ", " + + std::to_string(utime) + ", " + + std::to_string(stime) + ", " + + std::to_string((int) (amount * 10000)) + ")"; - if (i != usage.size() - 1 ) { - query += ", "; - } + query += ", "; } + query = query.substr(0, query.size() - 2); _D("Insert %d rows of per app battery usage", usage.size()); - std::vector records; - return __dbMgr.executeSync(query.c_str(), &records); + return __dbMgr.executeSync(query.c_str(), NULL); +} + +bool BatteryMonitor::__insertLastCpuUsageLog(CpuUsageMap& usage) +{ + IF_FAIL_RETURN_TAG(usage.size(), true, _W, "No data"); + _D("Delete all rows from app last times table"); + __dbMgr.executeSync("DELETE FROM " BATTERY_LAST_CPU_USAGE_TABLE, NULL); + + std::string query("INSERT INTO " BATTERY_LAST_CPU_USAGE_TABLE "(" BATTERY_APP_ID ", " BATTERY_UTIME ", " BATTERY_STIME "," BATTERY_TIMESTAMP ") VALUES"); + + std::string appId; + int stime, utime; + int timestamp; + + for (auto it = usage.begin(); it != usage.end(); it++) { + appId = it->first; + timestamp = (it->second).timestamp; + utime = (it->second).utime; + stime = (it->second).stime; + + query += " ('" + appId + + "', " + std::to_string(utime) + + ", " + std::to_string(stime) + + ", " + std::to_string(timestamp) + ")"; + + query += ", "; + } + + _D("Insert %d rows in app last times table", usage.size()); + query = query.substr(0, query.size() - 2); + return __dbMgr.executeSync(query.c_str(), NULL); } int BatteryMonitor::getLastResetTime() diff --git a/src/battery-stats/BatteryMonitor.h b/src/battery-stats/BatteryMonitor.h index 361a08f..7ec34f8 100644 --- a/src/battery-stats/BatteryMonitor.h +++ b/src/battery-stats/BatteryMonitor.h @@ -43,7 +43,9 @@ namespace ctx { static void __batteryChangeCb(device_callback_e type, void* value, void* userData); static void __chargerChangeCb(device_callback_e type, void* value, void* userData); - bool __insertUsageLog(std::vector& usage); + bool __insertBatteryUsageLog(std::vector& usage); + bool __insertLastCpuUsageLog(CpuUsageMap& usage); + bool __getLastCpuUsageTable(CpuUsageMap* lastCpuUsage); DatabaseManager __dbMgr; BatteryUsageAnalyzer __analyzer; diff --git a/src/battery-stats/BatteryStatisticsTypes.h b/src/battery-stats/BatteryStatisticsTypes.h index dc43678..d22faa7 100644 --- a/src/battery-stats/BatteryStatisticsTypes.h +++ b/src/battery-stats/BatteryStatisticsTypes.h @@ -18,39 +18,62 @@ #define _CONTEXT_STATS_BATTERY_TYPES_H_ #include +#include #define BATTERY_HISTORY_PRIV PRIV_APP_HISTORY #define BATTERY_USAGE_TABLE "Log_BatteryUsagePerApp" #define BATTERY_USAGE_TABLE_COLUMNS \ "AppId TEXT NOT NULL, StartTime INTEGER NOT NULL DEFAULT 0, " \ - "EndTime INTEGER NOT NULL DEFAULT 0, Amount INTEGER NOT NULL DEFAULT 0" + "EndTime INTEGER NOT NULL DEFAULT 0, Amount INTEGER NOT NULL DEFAULT 0, " \ + "Utime INTEGER NOT NULL DEFAULT 0, Stime INTEGER NOT NULL DEFAULT 0" #define BATTERY_LAST_INFO_TABLE "Battery_LastInfo" #define BATTERY_LAST_INFO_TABLE_COLUMNS \ "RowId INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " \ "LastResetTime UNSIGNED INT NOT NULL DEFAULT 0, " \ - "LastPercent UNSIGNED INT NOT NULL DEFAULT 0," \ - "LastPercentTime UNSIGNED INT NOT NULL DEFAULT 0" + "LastPercent UNSIGNED INT NOT NULL DEFAULT 0, " \ + "LastPercentTime UNSIGNED INT NOT NULL DEFAULT 0, " \ + "LastHeartTimestamp UNSIGNED INT NOT NULL DEFAULT 0" #define BATTERY_TEMP_TIME_INFO "Temp_BatteryTimeInfo" #define BATTERY_TEMP_TIME_INFO_COLUMNS \ "Amount INTEGER NOT NULL DEFAULT 0, StartTime INTEGER NOT NULL DEFAULT 0, " \ "EndTime INTEGER NOT NULL DEFAULT 0" +#define BATTERY_LAST_CPU_USAGE_TABLE "Temp_LastCpuUsagePerApp" +#define BATTERY_LAST_CPU_USAGE_TABLE_COLUMNS \ + "AppId TEXT PRIMARY KEY, Utime INTEGER NOT NULL DEFAULT 0, " \ + "Stime INTEGER NOT NULL DEFAULT 0, Timestamp INTEGER NOT NULL DEFAULT 0" + #define BATTERY_APP_ID "AppId" +#define BATTERY_INDEX "idx" #define BATTERY_TIMESTAMP "Timestamp" #define BATTERY_TYPE "Type" +#define BATTERY_DATA "Data" #define BATTERY_START_TIME "StartTime" #define BATTERY_END_TIME "EndTime" +#define BATTERY_UTIME "Utime" +#define BATTERY_STIME "Stime" #define BATTERY_AMOUNT "Amount" #define BATTERY_LAST_RESET_TIME "LastResetTime" #define BATTERY_LAST_PERCENT "LastPercent" #define BATTERY_LAST_PERCENT_TIME "LastPercentTime" +#define BATTERY_LAST_HEART_TIMESTAMP "LastHeartTimestamp" #define BATTERY_ROW_ID "RowId" #define CURRENT_TIME (int)(time(0)) +/* Typedefs */ +namespace ctx { + struct LastAppCpuUsageInfo { + int timestamp; + int utime; + int stime; + }; + typedef std::map CpuUsageMap; +} + enum AppLaunchType { TYPE_SERVICE = 0, TYPE_FOREGROUND, diff --git a/src/battery-stats/BatteryUsageAnalyzer.cpp b/src/battery-stats/BatteryUsageAnalyzer.cpp index e02b7be..73f1b2c 100644 --- a/src/battery-stats/BatteryUsageAnalyzer.cpp +++ b/src/battery-stats/BatteryUsageAnalyzer.cpp @@ -16,66 +16,103 @@ #include #include -#include "BatteryStatisticsTypes.h" #include "BatteryUsageAnalyzer.h" using namespace ctx; -bool BatteryUsageAnalyzer::calculateBatteryUsage(int lastTime, int currTime, std::vector& appLog, std::vector* usage) +void BatteryUsageAnalyzer::__normalizeBatteryUsage(std::vector* usage, int totalUtime, int totalStime) +{ + if (totalStime + totalUtime == 0) { + return; + } + + int utime; + int stime; + double batteryUsage; + + for (unsigned int i= 0; i < usage->size(); i++) { + (*usage)[i].get(NULL, BATTERY_UTIME, &utime); + (*usage)[i].get(NULL, BATTERY_STIME, &stime); + batteryUsage = ((double)(utime + stime)) / ((double)(totalUtime + totalStime)); + (*usage)[i].set(NULL, BATTERY_AMOUNT, batteryUsage); + } +} + +bool BatteryUsageAnalyzer::calculateBatteryUsage(int lastTime, int currTime, std::vector& cpuUsageLog, CpuUsageMap& lastCpuUsage, std::vector* usage) { int timeInterval = currTime - lastTime; IF_FAIL_RETURN(timeInterval > 0, false); - std::map lastAppTimeMap; std::string appId; int timestamp; - int type; + int stime; + int utime; + int idx; + int totalUtime = 0; + int totalStime = 0; - for (unsigned int i = 0; i < appLog.size(); i++) { - appLog[i].get(NULL, BATTERY_APP_ID, &appId); - appLog[i].get(NULL, BATTERY_TIMESTAMP, ×tamp); - appLog[i].get(NULL, BATTERY_TYPE, &type); + for (unsigned int i = 0; i < cpuUsageLog.size(); i++) { + cpuUsageLog[i].get(NULL, BATTERY_APP_ID, &appId); + cpuUsageLog[i].get(NULL, BATTERY_TIMESTAMP, ×tamp); + cpuUsageLog[i].get(NULL, BATTERY_UTIME, &utime); + cpuUsageLog[i].get(NULL, BATTERY_STIME, &stime); + cpuUsageLog[i].get(NULL, BATTERY_INDEX, &idx); if (timestamp < lastTime) { continue; } - if (timestamp > currTime) { break; } - if (type == TYPE_FOREGROUND) { // Mark timestamp of foreground - lastAppTimeMap[appId] = timestamp; - } else if (type == TYPE_BACKGROUND) { // Foreground duration calculation (Foreground->Background) + //If CPU table is reset, clear last app times and make lastTime as the timestamp + if (idx == 0) { + lastCpuUsage.clear(); + lastTime = timestamp; + } + + auto lastAppCpuUsage = lastCpuUsage.find(appId); + int prevUtime = 0; + int prevStime = 0; + int prevTimestamp = 0; + + if (lastAppCpuUsage != lastCpuUsage.end()) { + prevTimestamp = (lastAppCpuUsage->second).timestamp; + prevUtime = (lastAppCpuUsage->second).utime; + prevStime = (lastAppCpuUsage->second).stime; + Json row; - if (lastAppTimeMap.find(appId) == lastAppTimeMap.end() || lastAppTimeMap[appId] == 0) { - __createBatteryUsage(appId, lastTime, timestamp, timeInterval, &row); - } else { - __createBatteryUsage(appId, lastAppTimeMap[appId], timestamp, timeInterval, &row); - lastAppTimeMap[appId] = 0; - } + row.set(NULL, BATTERY_APP_ID, appId); + row.set(NULL, BATTERY_START_TIME, prevTimestamp); + row.set(NULL, BATTERY_END_TIME, timestamp); + row.set(NULL, BATTERY_AMOUNT, 0); + row.set(NULL, BATTERY_UTIME, utime - prevUtime); + row.set(NULL, BATTERY_STIME, stime - prevStime); + + totalUtime += utime - prevUtime; + totalStime += stime - prevStime; usage->push_back(row); - } - } - // Not closed app - for (auto it = lastAppTimeMap.begin(); it != lastAppTimeMap.end(); it++) { - if (it->second == 0) { - continue; + } else { + Json row; + row.set(NULL, BATTERY_APP_ID, appId); + row.set(NULL, BATTERY_START_TIME, lastTime); + row.set(NULL, BATTERY_END_TIME, timestamp); + row.set(NULL, BATTERY_AMOUNT, 0); + row.set(NULL, BATTERY_UTIME, utime); + row.set(NULL, BATTERY_STIME, stime); + + totalStime += stime; + totalUtime += utime; + usage->push_back(row); } - Json row; - __createBatteryUsage(it->first, it->second, currTime, timeInterval, &row); - usage->push_back(row); + LastAppCpuUsageInfo lastAppUsage; + lastAppUsage.timestamp = timestamp; + lastAppUsage.utime = utime; + lastAppUsage.stime = stime; + lastCpuUsage[appId] = lastAppUsage; } - + __normalizeBatteryUsage(usage, totalUtime, totalStime); return true; } - -void BatteryUsageAnalyzer::__createBatteryUsage(std::string appId, int startTime, int endTime, int timeInterval, Json* record) -{ - record->set(NULL, BATTERY_APP_ID, appId); - record->set(NULL, BATTERY_START_TIME, startTime); - record->set(NULL, BATTERY_END_TIME, endTime); - record->set(NULL, BATTERY_AMOUNT, (double)(endTime - startTime) / (double)timeInterval); -} diff --git a/src/battery-stats/BatteryUsageAnalyzer.h b/src/battery-stats/BatteryUsageAnalyzer.h index 982ca59..f5c8333 100644 --- a/src/battery-stats/BatteryUsageAnalyzer.h +++ b/src/battery-stats/BatteryUsageAnalyzer.h @@ -19,6 +19,7 @@ #include #include +#include "BatteryStatisticsTypes.h" namespace ctx { @@ -28,10 +29,10 @@ namespace ctx { BatteryUsageAnalyzer() {}; ~BatteryUsageAnalyzer() {}; - bool calculateBatteryUsage(int lastTime, int currTime, std::vector& appLog, std::vector* usage); + bool calculateBatteryUsage(int lastTime, int currTime, std::vector& cpuUsageLog, CpuUsageMap& lastCpuUsage, std::vector* usage); private: - void __createBatteryUsage(std::string appId, int startTime, int endTime, int timeInterval, Json* record); + void __normalizeBatteryUsage(std::vector* usage, int totalUtime, int totalStime); }; diff --git a/src/battery-stats/HeartDbReader.cpp b/src/battery-stats/HeartDbReader.cpp index 5b65b33..456d0d5 100644 --- a/src/battery-stats/HeartDbReader.cpp +++ b/src/battery-stats/HeartDbReader.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -//#include +#include #include #include #include "BatteryStatisticsTypes.h" @@ -24,6 +24,7 @@ #define HEART_APP_ID "appid" #define HEART_TIME "time" #define HEART_DATA "data" +#define HEART_INDEX "idx" #define HEART_DB_PATH tzplatform_mkpath(TZ_USER_DB, ".resourced-heart-default.db") @@ -59,16 +60,16 @@ void HeartDbReader::close() __heartDb = NULL; } -bool HeartDbReader::readAppLaunchLog(int startTime, int endTime, std::vector* appLog) +bool HeartDbReader::readCpuUsageLog(int startTime, int endTime, std::vector* cpuUsageLog) { IF_FAIL_RETURN(__heartDb, false); char* sql = sqlite3_mprintf( - "SELECT " HEART_APP_ID ", " HEART_TIME ", " HEART_DATA " FROM " HEART_CPU_TABLE \ + "SELECT " HEART_APP_ID ", " HEART_TIME ", " HEART_DATA ", " HEART_INDEX " FROM " HEART_CPU_TABLE \ " WHERE " HEART_TIME " >= %d AND " HEART_TIME " < %d", startTime, endTime); char* err = NULL; - int ret = sqlite3_exec(__heartDb, sql, __appLaunchLogCb, appLog, &err); + int ret = sqlite3_exec(__heartDb, sql, __cpuUsageLogCb, cpuUsageLog, &err); sqlite3_free(sql); if (ret != SQLITE_OK) { _E("Failed to read heart DB: Error(%s)", err); @@ -79,7 +80,7 @@ bool HeartDbReader::readAppLaunchLog(int startTime, int endTime, std::vectorpush_back(newRow); } return 0; } -void HeartDbReader::__convertAppLaunchLog(Json& row, Json* newRow) +void HeartDbReader::__convertCpuUsageLog(Json& row, Json* newRow) { std::string appId; std::string timestamp; std::string data; -/* int utime; + int utime; int stime; int pid; int type; -*/ + int index; + row.get(NULL, HEART_APP_ID, &appId); row.get(NULL, HEART_TIME, ×tamp); row.get(NULL, HEART_DATA, &data); -/* - std::stringstream buf = data; // TODO use utim & stime + row.get(NULL, HEART_INDEX, &index); + + std::stringstream buf(data); buf >> utime >> stime >> pid >> type; -*/ - std::string type = data.substr(data.length() - 2, 1); newRow->set(NULL, BATTERY_APP_ID, appId); newRow->set(NULL, BATTERY_TIMESTAMP, atoi(timestamp.c_str())); - newRow->set(NULL, BATTERY_TYPE, atoi(type.c_str())); + newRow->set(NULL, BATTERY_UTIME, utime); + newRow->set(NULL, BATTERY_STIME, stime); + newRow->set(NULL, BATTERY_TYPE, type); + newRow->set(NULL, BATTERY_INDEX, index); } diff --git a/src/battery-stats/HeartDbReader.h b/src/battery-stats/HeartDbReader.h index f355233..4c72902 100644 --- a/src/battery-stats/HeartDbReader.h +++ b/src/battery-stats/HeartDbReader.h @@ -32,11 +32,11 @@ namespace ctx { bool open(); void close(); - bool readAppLaunchLog(int startTime, int endTime, std::vector* appLog); + bool readCpuUsageLog(int startTime, int endTime, std::vector* cpuUsageLog); private: - static int __appLaunchLogCb(void *userData, int dim, char **value, char **column); - static void __convertAppLaunchLog(Json& row, Json* newRow); + static int __cpuUsageLogCb(void *userData, int dim, char **value, char **column); + static void __convertCpuUsageLog(Json& row, Json* newRow); sqlite3 *__heartDb; }; -- 2.7.4 From 31bb566294352ae07d69c2b0526771ddb09a2118 Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Wed, 26 Oct 2016 18:31:24 +0200 Subject: [PATCH 11/16] hardcoded so files path fix Change-Id: I0265a54487111e6e10bbc435f01531a691b81bab Signed-off-by: Marcin Masternak --- src/media-stats/MediaContentMonitor.cpp | 2 +- src/my-place/facade/UserPlaces.cpp | 2 +- src/my-place/visit-detector/VisitDetector.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/media-stats/MediaContentMonitor.cpp b/src/media-stats/MediaContentMonitor.cpp index 8fe1a06..bf29b2d 100644 --- a/src/media-stats/MediaContentMonitor.cpp +++ b/src/media-stats/MediaContentMonitor.cpp @@ -23,7 +23,7 @@ #include "DbHandle.h" #include "MediaContentMonitor.h" -#define SO_PATH _LIBDIR_ "context-service/libctx-prvd-media-stats-util.so" +#define SO_PATH _LIBDIR_ "/context-service/libctx-prvd-media-stats-util.so" #define PLAYCOUNT_RETENTION_PERIOD 259200 /* 1 month in secs */ #define ONE_DAY_IN_SEC 86400 diff --git a/src/my-place/facade/UserPlaces.cpp b/src/my-place/facade/UserPlaces.cpp index a8e25ea..e989ab7 100755 --- a/src/my-place/facade/UserPlaces.cpp +++ b/src/my-place/facade/UserPlaces.cpp @@ -24,7 +24,7 @@ #include #include -#define SO_PATH _LIBDIR_ "context-service/libctx-prvd-my-place-places-detector.so" +#define SO_PATH _LIBDIR_ "/context-service/libctx-prvd-my-place-places-detector.so" typedef void (*places_detector_t)(); diff --git a/src/my-place/visit-detector/VisitDetector.cpp b/src/my-place/visit-detector/VisitDetector.cpp index ac05087..0aa53c5 100644 --- a/src/my-place/visit-detector/VisitDetector.cpp +++ b/src/my-place/visit-detector/VisitDetector.cpp @@ -29,7 +29,7 @@ #include #include -#define SO_PATH _LIBDIR_ "context-service/libctx-prvd-my-place-visit-categer.so" +#define SO_PATH _LIBDIR_ "/context-service/libctx-prvd-my-place-visit-categer.so" typedef void (*visit_categer_t)(ctx::Visit &visit); -- 2.7.4 From 0096c66ccacc042ddc1c1425387be6e13770f9bd Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Wed, 26 Oct 2016 19:13:53 +0200 Subject: [PATCH 12/16] [my-place] Submodules dynamic loading bug fix (utils static library). Change-Id: I872e137d3f44c4093ee0a0cecb0448e636601f79 Signed-off-by: Marcin Masternak --- src/my-place/CMakeLists.txt | 8 ++++++-- src/my-place/facade/UserPlaces.h | 3 +-- src/my-place/place/CMakeLists.txt | 3 +++ src/my-place/place/PlaceCateger.cpp | 6 +++--- src/my-place/place/PlaceCateger.h | 2 +- src/my-place/place/PlacesDetector.cpp | 14 +++++++------- src/my-place/place/PlacesDetector.h | 2 +- src/my-place/utils/CMakeLists.txt | 5 +++++ src/my-place/utils/Gmap.h | 2 +- src/my-place/utils/Median.h | 2 +- src/my-place/utils/Similarity.h | 2 +- src/my-place/{facade => utils}/UserPlacesParams.h | 0 src/my-place/{facade => utils}/UserPlacesTypes.cpp | 2 +- src/my-place/{facade => utils}/UserPlacesTypes.h | 0 src/my-place/visit-categer/CMakeLists.txt | 3 +++ src/my-place/visit-categer/Mahal.h | 2 +- src/my-place/visit-categer/PiecewiseLin.h | 2 +- src/my-place/visit-categer/VisitCateger.h | 2 +- src/my-place/visit-detector/LocationListenerIface.h | 2 +- src/my-place/visit-detector/LocationLogger.cpp | 6 +++--- src/my-place/visit-detector/VisitDetector.cpp | 10 +++++----- src/my-place/visit-detector/VisitDetector.h | 2 +- src/my-place/visit-detector/WifiListenerIface.h | 2 +- src/my-place/visit-detector/WifiLogger.cpp | 4 ++-- src/my-place/visit-detector/WifiLogger.h | 2 +- 25 files changed, 51 insertions(+), 37 deletions(-) create mode 100644 src/my-place/utils/CMakeLists.txt rename src/my-place/{facade => utils}/UserPlacesParams.h (100%) rename src/my-place/{facade => utils}/UserPlacesTypes.cpp (99%) rename src/my-place/{facade => utils}/UserPlacesTypes.h (100%) diff --git a/src/my-place/CMakeLists.txt b/src/my-place/CMakeLists.txt index 7ea03ee..cc19619 100644 --- a/src/my-place/CMakeLists.txt +++ b/src/my-place/CMakeLists.txt @@ -1,4 +1,7 @@ SET(target "${target_prefix}-my-place") +SET(target_myplace_utils_static "${target}-utils_static") + +INCLUDE_DIRECTORIES(utils) SET(DEPS ${DEPS} gmodule-2.0 @@ -6,7 +9,7 @@ SET(DEPS ${DEPS} capi-network-wifi ) -FILE(GLOB SRCS *.cpp facade/*.cpp utils/*.cpp visit-detector/*.cpp) +FILE(GLOB SRCS *.cpp facade/*.cpp visit-detector/*.cpp) INCLUDE(FindPkgConfig) PKG_CHECK_MODULES(PKG_MYPLACE REQUIRED ${DEPS}) @@ -16,9 +19,10 @@ FOREACH(flag ${PKG_MYPLACE_CFLAGS}) ENDFOREACH(flag) ADD_LIBRARY(${target} SHARED ${SRCS}) -TARGET_LINK_LIBRARIES(${target} ${PKG_MYPLACE_LDFLAGS} ${target_shared}) +TARGET_LINK_LIBRARIES(${target} ${PKG_MYPLACE_LDFLAGS} ${target_shared} ${target_myplace_utils_static}) INSTALL(TARGETS ${target} DESTINATION ${CMAKE_INSTALL_LIBDIR}/${target_dir}) +ADD_SUBDIRECTORY(utils) ADD_SUBDIRECTORY(place) ADD_SUBDIRECTORY(visit-categer) \ No newline at end of file diff --git a/src/my-place/facade/UserPlaces.h b/src/my-place/facade/UserPlaces.h index 31bac72..bc552cc 100644 --- a/src/my-place/facade/UserPlaces.h +++ b/src/my-place/facade/UserPlaces.h @@ -24,8 +24,7 @@ #include #include #include "../visit-detector/VisitDetector.h" -#include "../place/PlacesDetector.h" -#include "UserPlacesTypes.h" +#include namespace ctx { diff --git a/src/my-place/place/CMakeLists.txt b/src/my-place/place/CMakeLists.txt index fc2c120..7ac705f 100644 --- a/src/my-place/place/CMakeLists.txt +++ b/src/my-place/place/CMakeLists.txt @@ -1,7 +1,10 @@ SET(target "${target_prefix}-my-place-places-detector") +INCLUDE_DIRECTORIES(../utils) + FILE(GLOB SRCS *.cpp) ADD_LIBRARY(${target} SHARED ${SRCS}) +TARGET_LINK_LIBRARIES(${target} ${target_myplace_utils_static}) INSTALL(TARGETS ${target} DESTINATION ${CMAKE_INSTALL_LIBDIR}/${target_dir}) \ No newline at end of file diff --git a/src/my-place/place/PlaceCateger.cpp b/src/my-place/place/PlaceCateger.cpp index 1b956a8..603e857 100644 --- a/src/my-place/place/PlaceCateger.cpp +++ b/src/my-place/place/PlaceCateger.cpp @@ -15,9 +15,9 @@ */ #include "PlaceCateger.h" -#include "../utils/Median.h" -#include "../facade/UserPlacesParams.h" -#include "../facade/UserPlacesTypes.h" +#include +#include +#include #include #include diff --git a/src/my-place/place/PlaceCateger.h b/src/my-place/place/PlaceCateger.h index 44927b3..dd6943f 100644 --- a/src/my-place/place/PlaceCateger.h +++ b/src/my-place/place/PlaceCateger.h @@ -17,7 +17,7 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_PLACE_CATEGER_ #define _CONTEXT_PLACE_RECOGNITION_PLACE_CATEGER_ -#include "../facade/UserPlacesTypes.h" +#include #include #include #include diff --git a/src/my-place/place/PlacesDetector.cpp b/src/my-place/place/PlacesDetector.cpp index e66c5ee..115a44b 100644 --- a/src/my-place/place/PlacesDetector.cpp +++ b/src/my-place/place/PlacesDetector.cpp @@ -17,18 +17,18 @@ #include #include #include -#include "../utils/Similarity.h" +#include #include "PlacesDetector.h" #include "PlaceCateger.h" -#include "../utils/Median.h" +#include #ifdef TIZEN_ENGINEER_MODE -#include "../utils/Gmap.h" +#include #endif /* TIZEN_ENGINEER_MODE */ -#include "../facade/UserPlacesTypes.h" +#include #include #include -#include "../facade/UserPlacesParams.h" -#include "../utils/DebugUtils.h" +#include +#include #include #define __DELETE_PLACES_QUERY "DELETE FROM " PLACE_TABLE @@ -89,7 +89,7 @@ double ctx::PlacesDetector::__doubleValueFromJson(Json &row, const char* key) { double value; row.get(NULL, key, &value); - _D("__doubleValueFromJson, key:%s, value: %lf", key, value); + _D("key: %s, value: %lf", key, value); return value; } diff --git a/src/my-place/place/PlacesDetector.h b/src/my-place/place/PlacesDetector.h index d9c47cb..81c6a44 100644 --- a/src/my-place/place/PlacesDetector.h +++ b/src/my-place/place/PlacesDetector.h @@ -20,7 +20,7 @@ #include #include #include -#include "../facade/UserPlacesTypes.h" +#include #include #include "Graph.h" diff --git a/src/my-place/utils/CMakeLists.txt b/src/my-place/utils/CMakeLists.txt new file mode 100644 index 0000000..2ecc5e4 --- /dev/null +++ b/src/my-place/utils/CMakeLists.txt @@ -0,0 +1,5 @@ +SET(target ${target_myplace_utils_static}) + +FILE(GLOB SRCS *.cpp) + +ADD_LIBRARY(${target} STATIC ${SRCS}) \ No newline at end of file diff --git a/src/my-place/utils/Gmap.h b/src/my-place/utils/Gmap.h index 891b851..c6a5482 100644 --- a/src/my-place/utils/Gmap.h +++ b/src/my-place/utils/Gmap.h @@ -17,7 +17,7 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_GMAP_H_ #define _CONTEXT_PLACE_RECOGNITION_GMAP_H_ -#include "../facade/UserPlacesTypes.h" +#include "UserPlacesTypes.h" #define GMAP_FILE "/tmp/user_places_map.html" diff --git a/src/my-place/utils/Median.h b/src/my-place/utils/Median.h index b33e7b2..275fa13 100644 --- a/src/my-place/utils/Median.h +++ b/src/my-place/utils/Median.h @@ -17,7 +17,7 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_MEDIAN_ #define _CONTEXT_PLACE_RECOGNITION_MEDIAN_ -#include "../facade/UserPlacesTypes.h" +#include "UserPlacesTypes.h" #include namespace ctx { diff --git a/src/my-place/utils/Similarity.h b/src/my-place/utils/Similarity.h index e006164..f78b675 100644 --- a/src/my-place/utils/Similarity.h +++ b/src/my-place/utils/Similarity.h @@ -17,7 +17,7 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_SIMILAR_H_ #define _CONTEXT_PLACE_RECOGNITION_SIMILAR_H_ -#include "../facade/UserPlacesTypes.h" +#include "UserPlacesTypes.h" namespace ctx { diff --git a/src/my-place/facade/UserPlacesParams.h b/src/my-place/utils/UserPlacesParams.h similarity index 100% rename from src/my-place/facade/UserPlacesParams.h rename to src/my-place/utils/UserPlacesParams.h diff --git a/src/my-place/facade/UserPlacesTypes.cpp b/src/my-place/utils/UserPlacesTypes.cpp similarity index 99% rename from src/my-place/facade/UserPlacesTypes.cpp rename to src/my-place/utils/UserPlacesTypes.cpp index bf00798..c5ed30c 100644 --- a/src/my-place/facade/UserPlacesTypes.cpp +++ b/src/my-place/utils/UserPlacesTypes.cpp @@ -22,7 +22,7 @@ #include #include "UserPlacesTypes.h" #include "UserPlacesParams.h" -#include "../utils/DebugUtils.h" +#include "DebugUtils.h" #define __MAC_STRING_COMPONENTS_SEPARATOR ':' #define __MAC_SET_STRING_DELIMITER ',' diff --git a/src/my-place/facade/UserPlacesTypes.h b/src/my-place/utils/UserPlacesTypes.h similarity index 100% rename from src/my-place/facade/UserPlacesTypes.h rename to src/my-place/utils/UserPlacesTypes.h diff --git a/src/my-place/visit-categer/CMakeLists.txt b/src/my-place/visit-categer/CMakeLists.txt index 93fb055..f127d61 100644 --- a/src/my-place/visit-categer/CMakeLists.txt +++ b/src/my-place/visit-categer/CMakeLists.txt @@ -1,7 +1,10 @@ SET(target "${target_prefix}-my-place-visit-categer") +INCLUDE_DIRECTORIES(../utils) + FILE(GLOB SRCS *.cpp) ADD_LIBRARY(${target} SHARED ${SRCS}) +TARGET_LINK_LIBRARIES(${target} ${target_myplace_utils_static}) INSTALL(TARGETS ${target} DESTINATION ${CMAKE_INSTALL_LIBDIR}/${target_dir}) \ No newline at end of file diff --git a/src/my-place/visit-categer/Mahal.h b/src/my-place/visit-categer/Mahal.h index 54ec7f3..26e6235 100644 --- a/src/my-place/visit-categer/Mahal.h +++ b/src/my-place/visit-categer/Mahal.h @@ -18,7 +18,7 @@ #define _CONTEXT_PLACE_RECOGNITION_MAHAL_H_ #include -#include "../facade/UserPlacesTypes.h" +#include namespace ctx { diff --git a/src/my-place/visit-categer/PiecewiseLin.h b/src/my-place/visit-categer/PiecewiseLin.h index a0e92d7..4ff497b 100644 --- a/src/my-place/visit-categer/PiecewiseLin.h +++ b/src/my-place/visit-categer/PiecewiseLin.h @@ -17,7 +17,7 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_PIECEWISE_LIN_ #define _CONTEXT_PLACE_RECOGNITION_PIECEWISE_LIN_ -#include "../facade/UserPlacesTypes.h" +#include namespace ctx { diff --git a/src/my-place/visit-categer/VisitCateger.h b/src/my-place/visit-categer/VisitCateger.h index f1c5456..3edfb93 100644 --- a/src/my-place/visit-categer/VisitCateger.h +++ b/src/my-place/visit-categer/VisitCateger.h @@ -17,7 +17,7 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_VISIT_CATEGER_H_ #define _CONTEXT_PLACE_RECOGNITION_VISIT_CATEGER_H_ -#include "../facade/UserPlacesTypes.h" +#include #include "Mahal.h" #include "PiecewiseLin.h" #include diff --git a/src/my-place/visit-detector/LocationListenerIface.h b/src/my-place/visit-detector/LocationListenerIface.h index 46f2b3f..7d2aef2 100644 --- a/src/my-place/visit-detector/LocationListenerIface.h +++ b/src/my-place/visit-detector/LocationListenerIface.h @@ -17,7 +17,7 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_LOCATION_LISTENER_IFACE_H_ #define _CONTEXT_PLACE_RECOGNITION_LOCATION_LISTENER_IFACE_H_ -#include "../facade/UserPlacesTypes.h" +#include namespace ctx { diff --git a/src/my-place/visit-detector/LocationLogger.cpp b/src/my-place/visit-detector/LocationLogger.cpp index 4b95eed..372ee74 100644 --- a/src/my-place/visit-detector/LocationLogger.cpp +++ b/src/my-place/visit-detector/LocationLogger.cpp @@ -18,9 +18,9 @@ #include #include #include -#include "../facade/UserPlacesTypes.h" -#include "../facade/UserPlacesParams.h" -#include "../utils/DebugUtils.h" +#include +#include +#include #include "LocationLogger.h" #ifdef TIZEN_ENGINEER_MODE diff --git a/src/my-place/visit-detector/VisitDetector.cpp b/src/my-place/visit-detector/VisitDetector.cpp index 0aa53c5..98460c2 100644 --- a/src/my-place/visit-detector/VisitDetector.cpp +++ b/src/my-place/visit-detector/VisitDetector.cpp @@ -20,12 +20,12 @@ #include #include #include -#include "../facade/UserPlacesTypes.h" +#include #include "VisitDetector.h" -#include "../facade/UserPlacesParams.h" -#include "../utils/Similarity.h" -#include "../utils/Median.h" -#include "../utils/DebugUtils.h" +#include +#include +#include +#include #include #include diff --git a/src/my-place/visit-detector/VisitDetector.h b/src/my-place/visit-detector/VisitDetector.h index 98bbda3..b476942 100644 --- a/src/my-place/visit-detector/VisitDetector.h +++ b/src/my-place/visit-detector/VisitDetector.h @@ -22,7 +22,7 @@ #include #include #include -#include "../facade/UserPlacesTypes.h" +#include #include #include "VisitListenerIface.h" #include "LocationLogger.h" diff --git a/src/my-place/visit-detector/WifiListenerIface.h b/src/my-place/visit-detector/WifiListenerIface.h index 56307d0..84ef489 100644 --- a/src/my-place/visit-detector/WifiListenerIface.h +++ b/src/my-place/visit-detector/WifiListenerIface.h @@ -17,7 +17,7 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_WIFI_LISTENER_IFACE_H_ #define _CONTEXT_PLACE_RECOGNITION_WIFI_LISTENER_IFACE_H_ -#include "../facade/UserPlacesTypes.h" +#include namespace ctx { diff --git a/src/my-place/visit-detector/WifiLogger.cpp b/src/my-place/visit-detector/WifiLogger.cpp index 2baa24c..874f494 100644 --- a/src/my-place/visit-detector/WifiLogger.cpp +++ b/src/my-place/visit-detector/WifiLogger.cpp @@ -17,8 +17,8 @@ #include #include #include -#include "../facade/UserPlacesTypes.h" -#include "../utils/DebugUtils.h" +#include +#include #include "WifiLogger.h" #define __WIFI_CREATE_TABLE_COLUMNS \ diff --git a/src/my-place/visit-detector/WifiLogger.h b/src/my-place/visit-detector/WifiLogger.h index 0134c2d..7c627a1 100644 --- a/src/my-place/visit-detector/WifiLogger.h +++ b/src/my-place/visit-detector/WifiLogger.h @@ -24,7 +24,7 @@ #include #include "WifiListenerIface.h" #include "VisitListenerIface.h" -#include "../facade/UserPlacesParams.h" +#include /* Database usage flag */ #define WIFI_LOGGER_DATABASE false -- 2.7.4 From a2bbc482c6e50c8f4852736b5e23f224c6b957b3 Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Wed, 26 Oct 2016 19:14:46 +0200 Subject: [PATCH 13/16] [my-place] PlacesDetector::detectPlaces() fix. Change-Id: I6849d1ace7f4d27bc74ab645149805e23a63d7b4 Signed-off-by: Marcin Masternak --- src/my-place/place/PlacesDetector.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/my-place/place/PlacesDetector.cpp b/src/my-place/place/PlacesDetector.cpp index 115a44b..298506d 100644 --- a/src/my-place/place/PlacesDetector.cpp +++ b/src/my-place/place/PlacesDetector.cpp @@ -74,6 +74,7 @@ void ctx::PlacesDetector::detectPlaces() __dbDeleteOldEntries(); std::vector records = __dbGetVisits(); Visits visits = __visitsFromJsons(records); + __processVisits(visits); } std::vector ctx::PlacesDetector::__dbGetVisits() -- 2.7.4 From 5259bd5ad85d39ef5d214a9e14abeb1e3cdb231c Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Wed, 26 Oct 2016 19:29:07 +0200 Subject: [PATCH 14/16] [my-place] Make PlacesDetector pure static. Change-Id: Iaaef19e42b8af8480acae24f1dd397ae7ac16ed6 Signed-off-by: Marcin Masternak --- src/my-place/place/PlacesDetector.cpp | 25 ++++-------------- src/my-place/place/PlacesDetector.h | 48 ++++++++++++++++------------------- 2 files changed, 27 insertions(+), 46 deletions(-) diff --git a/src/my-place/place/PlacesDetector.cpp b/src/my-place/place/PlacesDetector.cpp index 298506d..5ecd6eb 100644 --- a/src/my-place/place/PlacesDetector.cpp +++ b/src/my-place/place/PlacesDetector.cpp @@ -61,15 +61,10 @@ PLACE_COLUMN_WIFI_APS " STRING, "\ PLACE_COLUMN_CREATE_DATE " timestamp" -bool ctx::PlacesDetector::onTimerExpired(int timerId) { - _D(""); - detectPlaces(); - return true; -} - void ctx::PlacesDetector::detectPlaces() { _D(""); + __dbCreateTable(); __dbDeletePlaces(); __dbDeleteOldEntries(); std::vector records = __dbGetVisits(); @@ -168,7 +163,7 @@ void ctx::PlacesDetector::__reduceOutliers(ctx::Visits &visits) _D("Visits number from %d to %d (to short and to long reduction)", size, newSize); } -std::vector> ctx::PlacesDetector::__processVisits(ctx::Visits &visits) +std::vector> ctx::PlacesDetector::__processVisits(ctx::Visits &visits, bool testMode) { #ifdef TIZEN_ENGINEER_MODE std::vector placesVisits; // TODO: remove from final solution. @@ -181,7 +176,7 @@ std::vector> ctx::PlacesDetector::__processVisits(ct for (std::shared_ptr component : *components) { // Small places outliers reduction - if (!__testMode && component->size() < PLACES_DETECTOR_MIN_VISITS_PER_BIG_PLACE) + if (!testMode && component->size() < PLACES_DETECTOR_MIN_VISITS_PER_BIG_PLACE) continue; std::shared_ptr merged = std::make_shared(); for (graph::Node i : *component) { @@ -191,7 +186,7 @@ std::vector> ctx::PlacesDetector::__processVisits(ct if (place->categId == PLACE_CATEG_ID_NONE) continue; newDetectedPlaces.push_back(place); - if (!__testMode) + if (!testMode) __dbInsertPlace(*place); #ifdef TIZEN_ENGINEER_MODE @@ -342,14 +337,6 @@ void ctx::PlacesDetector::__dbDeleteOlderWifiAPsThan(time_t threshold) _D("deleting Wifi APs older than: %d, result: %s", threshold, ret ? "SUCCESS" : "FAIL"); } -ctx::PlacesDetector::PlacesDetector(bool testMode): - __testMode(testMode) -{ - if (testMode) - return; - __dbCreateTable(); -} - void ctx::PlacesDetector::__dbCreateTable() { DatabaseManager dbManager; @@ -385,7 +372,5 @@ void ctx::PlacesDetector::__dbInsertPlace(const Place &place) extern "C" SO_EXPORT void detectPlaces() { - _D(""); - ctx::PlacesDetector placesDetector; - placesDetector.detectPlaces(); + ctx::PlacesDetector::detectPlaces(); } diff --git a/src/my-place/place/PlacesDetector.h b/src/my-place/place/PlacesDetector.h index 81c6a44..ad07355 100644 --- a/src/my-place/place/PlacesDetector.h +++ b/src/my-place/place/PlacesDetector.h @@ -19,46 +19,42 @@ #include #include -#include #include #include #include "Graph.h" namespace ctx { - class PlacesDetector : public ITimerListener { + class PlacesDetector { private: - bool __testMode; - - double __doubleValueFromJson(Json &row, const char* key); - Categs __visitCategsFromJson(Json &row); - void __visitLocationFromJson(Json &row, ctx::Visit &visit); - Visit __visitFromJson(Json &row); - Visits __visitsFromJsons(std::vector& records); - - std::shared_ptr __graphFromVisits(const std::vector &visits); - - void __dbCreateTable(); - void __dbDeletePlaces(); - void __dbDeleteOldEntries(); - void __dbDeleteOlderVisitsThan(time_t threshold); - void __dbDeleteOlderWifiAPsThan(time_t threshold); - std::vector __dbGetVisits(); - void __dbInsertPlace(const Place &place); - - std::shared_ptr __placeFromMergedVisits(Visits &mergedVisits); - std::vector> __processVisits(Visits &visits); + static double __doubleValueFromJson(Json &row, const char* key); + static Categs __visitCategsFromJson(Json &row); + static void __visitLocationFromJson(Json &row, ctx::Visit &visit); + static Visit __visitFromJson(Json &row); + static Visits __visitsFromJsons(std::vector& records); + + static std::shared_ptr __graphFromVisits(const std::vector &visits); + + static void __dbCreateTable(); + static void __dbDeletePlaces(); + static void __dbDeleteOldEntries(); + static void __dbDeleteOlderVisitsThan(time_t threshold); + static void __dbDeleteOlderWifiAPsThan(time_t threshold); + static std::vector __dbGetVisits(); + static void __dbInsertPlace(const Place &place); + + static std::shared_ptr __placeFromMergedVisits(Visits &mergedVisits); + static std::vector> __processVisits(Visits &visits, bool testMode = false); static void __mergeLocation(const Visits &mergedVisits, Place &place); - std::shared_ptr __mergeVisits(const std::vector &visits); + static std::shared_ptr __mergeVisits(const std::vector &visits); static void __reduceOutliers(Visits &visits); static void __reduceOutliers(std::shared_ptr &cc); - bool onTimerExpired(int timerId); + PlacesDetector(); public: - PlacesDetector(bool testMode = false); - void detectPlaces(); + static void detectPlaces(); }; /* class PlacesDetector */ -- 2.7.4 From f5951b5f047087a3a7432c047fd54e0243890284 Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Fri, 28 Oct 2016 17:13:32 +0200 Subject: [PATCH 15/16] [my-place] Forgotten data to detected places database add. Change-Id: I6df5a35b1ea04c4d820bd04460bc0b668749e6ad Signed-off-by: Marcin Masternak --- src/my-place/facade/UserPlaces.cpp | 1 + src/my-place/place/PlacesDetector.cpp | 10 +++++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/my-place/facade/UserPlaces.cpp b/src/my-place/facade/UserPlaces.cpp index e989ab7..01b0683 100755 --- a/src/my-place/facade/UserPlaces.cpp +++ b/src/my-place/facade/UserPlaces.cpp @@ -108,6 +108,7 @@ ctx::Json ctx::UserPlaces::__composeJson(std::vector> pla placeJson.set(NULL, PLACE_CREATE_DATE, static_cast(place->createDate)); data.append(NULL, PLACE_DATA_READ, placeJson); } + _J("returns ", data); return data; } diff --git a/src/my-place/place/PlacesDetector.cpp b/src/my-place/place/PlacesDetector.cpp index 5ecd6eb..03fd1d5 100644 --- a/src/my-place/place/PlacesDetector.cpp +++ b/src/my-place/place/PlacesDetector.cpp @@ -253,9 +253,17 @@ std::shared_ptr ctx::PlacesDetector::__placeFromMergedVisits(Visits } std::shared_ptr allMacs = macSetsUnion(macSets); __mergeLocation(mergedVisits, *place); - PlaceCateger::categorize(mergedVisits, *place); + /* + * At this stage getting network names associated with Wifi AP MAC addresses is not needed (by looking + * to Wifi APs MAC addresses to network names map in database). This additional information for place + * is needed only when place is returned for external clients (getting straight from the database). + */ + for (ctx::Mac mac : *allMacs) { + place->wifiAps.insert(std::pair(mac, "")); + } + return place; } -- 2.7.4 From 98624afe7d6376db4bee80f26ea6fbc2c4909ea9 Mon Sep 17 00:00:00 2001 From: MyungJoo Ham Date: Tue, 20 Sep 2016 04:03:13 +0000 Subject: [PATCH 16/16] [4.0] Remove ExcludeArch and dead copmiler definitions If TV-profile should not include this package, it should be removed from the ks file (meta-tv.git). As we are trying to merge build projects, trying not to build for a specific profile will become meaningless soon. Thus, the ExcludeArch statement in the specfile is useless and confuses the system. So, it is removed. CMakeLists.txt states as if there are code with compiler definitions of "_MOBILE_" and "_WEARABLE". However, grep on the source code has revealed that there are no such code. Therefore, these two definitions are deadcode. We have not yet completely removed profile build dependencies. There will be another patch following this soon from me. Change-Id: I59025327e0ca933fd5599388b13939973a81081a Signed-off-by: MyungJoo Ham --- CMakeLists.txt | 9 --------- packaging/context-provider.spec | 4 ---- 2 files changed, 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 303cca7..2c21cb6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,15 +15,6 @@ ADD_DEFINITIONS(-DLOG_TAG="CONTEXT") ADD_DEFINITIONS(-D_LIBDIR_="${LIBDIR}") SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fPIC -Wl,--as-needed -Wl,--gc-section -Wl,--print-gc-section") -# Profiles -IF("${PROFILE}" STREQUAL "mobile") - ADD_DEFINITIONS("-D_MOBILE_") -ENDIF("${PROFILE}" STREQUAL "mobile") - -IF("${PROFILE}" STREQUAL "wearable") - ADD_DEFINITIONS("-D_WEARABLE_") -ENDIF("${PROFILE}" STREQUAL "wearable") - INSTALL( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${target_dir}/internal diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index 2a2a1d6..765f485 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -8,10 +8,6 @@ Source0: %{name}-%{version}.tar.gz %define BUILD_PROFILE %{?profile}%{!?profile:%{?tizen_profile_name}} -%if "%{?BUILD_PROFILE}" == "tv" -ExcludeArch: %{arm} aarch64 %ix86 x86_64 -%endif - BuildRequires: cmake BuildRequires: pkgconfig(gmodule-2.0) -- 2.7.4