From f12d988670c3f8498e54eba260f6b41a950aa56e Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Thu, 31 Mar 2016 14:18:44 +0200 Subject: [PATCH 01/16] [place-recognition] Small SVACE defects fix. Change-Id: I64f9551a55bf97c0dd16792b999e659871e5b02b Signed-off-by: Marcin Masternak --- src/place/recognition/place_recognition.cpp | 2 +- src/place/recognition/user_places/location_logger.cpp | 2 ++ src/place/recognition/user_places/piecewise_lin.cpp | 1 + src/place/recognition/user_places/wifi_logger.cpp | 1 + 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/place/recognition/place_recognition.cpp b/src/place/recognition/place_recognition.cpp index 7fb092f..9cdd6f6 100644 --- a/src/place/recognition/place_recognition.cpp +++ b/src/place/recognition/place_recognition.cpp @@ -54,7 +54,7 @@ int ctx::place_recognition_provider::read(const char *subject, ctx::Json option, _J("Option", option); std::vector> places = engine.get_places(); - Json data_read = engine.compose_json(places); + Json data_read = UserPlaces::compose_json(places); // The below function needs to be called once. // It does not need to be called within this read() function. diff --git a/src/place/recognition/user_places/location_logger.cpp b/src/place/recognition/user_places/location_logger.cpp index 6bee94b..3a4fb93 100644 --- a/src/place/recognition/user_places/location_logger.cpp +++ b/src/place/recognition/user_places/location_logger.cpp @@ -207,6 +207,8 @@ ctx::LocationLogger::LocationLogger(ILocationListener *listener_, bool test_mode , location_count(0) , active_request_succeeded(false) , active_location_succeeded(false) + , timer_id(-1) + , timer_timestamp(0) , timer_purpose(LOCATION_LOGGER_WAITING_FOR_PASSIVE_INTERVAL) , location_service_state(LOCATIONS_SERVICE_DISABLED) , location_method(LOCATION_LOGGER_METHOD) diff --git a/src/place/recognition/user_places/piecewise_lin.cpp b/src/place/recognition/user_places/piecewise_lin.cpp index f22d37c..e1cbd46 100644 --- a/src/place/recognition/user_places/piecewise_lin.cpp +++ b/src/place/recognition/user_places/piecewise_lin.cpp @@ -18,6 +18,7 @@ #include ctx::PiecewiseLin::PiecewiseLin(std::vector _xs, std::vector _vs) + : n(0) { if (_xs.size() != _vs.size()) { _E("Input arguments have different sizes"); diff --git a/src/place/recognition/user_places/wifi_logger.cpp b/src/place/recognition/user_places/wifi_logger.cpp index 5a6dfba..7d0c89d 100644 --- a/src/place/recognition/user_places/wifi_logger.cpp +++ b/src/place/recognition/user_places/wifi_logger.cpp @@ -72,6 +72,7 @@ ctx::WifiLogger::WifiLogger(IWifiListener * listener_, place_recog_mode_e energy , timer_on(false) , interval_minutes(WIFI_LOGGER_INTERVAL_MINUTES_HIGH_ACCURACY) , during_visit(false) + , connected_to_wifi_ap(false) , started(false) , running(false) { -- 2.7.4 From 1d2138758fbe5daac5f2a7462fccdc2e902d7382 Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Fri, 1 Apr 2016 13:59:34 +0200 Subject: [PATCH 02/16] [place-recognition] SVACE buffer overflow warning fix. Change-Id: I7fca0ab40c652c78968880883c05209b4a48b81a Signed-off-by: Marcin Masternak --- .../recognition/user_places/user_places_types.cpp | 32 +++++++++++++++------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/place/recognition/user_places/user_places_types.cpp b/src/place/recognition/user_places/user_places_types.cpp index 3d72852..81e253c 100644 --- a/src/place/recognition/user_places/user_places_types.cpp +++ b/src/place/recognition/user_places/user_places_types.cpp @@ -24,36 +24,43 @@ #include "user_places_params.h" #include "debug_utils.h" +#define MAC_STRING_COMPONENTS_SEPARATOR ':' #define MAC_SET_STRING_DELIMITER ',' ctx::Mac::Mac(const std::string& str) { std::stringstream ss(str); - ss >> *this; + try { + ss >> *this; + } catch (std::runtime_error &e) { + _E("%s", e.what()); + } } ctx::Mac::Mac(const char *str) { std::stringstream ss(str); - ss >> *this; + try { + ss >> *this; + } catch (std::runtime_error &e) { + _E("%s", e.what()); + } } std::istream& ctx::operator>>(std::istream &input, ctx::Mac &mac) { int h; char colon; - size_t i = 0; - while (true) { + for (size_t i = 0; i < ctx::Mac::MAC_SIZE; i++) { input >> std::hex; input >> h; mac.c[i] = h; - i++; - if (i >= ctx::Mac::MAC_SIZE) { + if (i + 1 >= ctx::Mac::MAC_SIZE) { break; } input >> colon; - if (colon != ':') { - throw std::runtime_error("Invalid mac format"); + if (colon != MAC_STRING_COMPONENTS_SEPARATOR) { + throw std::runtime_error("Invalid MAC format"); } } input >> std::dec; @@ -70,7 +77,7 @@ std::ostream& ctx::operator<<(std::ostream &output, const ctx::Mac &mac) if (i >= Mac::MAC_SIZE) { break; } - output << ":"; + output << MAC_STRING_COMPONENTS_SEPARATOR; } output << std::dec; return output; @@ -119,7 +126,12 @@ std::istream& ctx::operator>>(std::istream &input, ctx::mac_set_t &mac_set) Mac mac; char delimeter; while (!input.eof()) { - input >> mac; + try { + input >> mac; + } catch (std::runtime_error &e) { + _E("Cannot read mac_set. Exception: %s", e.what()); + break; + } mac_set.insert(mac); if (input.eof()) { break; -- 2.7.4 From 89330c31f4651690955890e3a0e902a1bb4949cf Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Fri, 1 Apr 2016 18:46:29 +0200 Subject: [PATCH 03/16] [place-recognition] Change database asynchronous queries to synchronous. Change-Id: Ibde511e03c713008ca731acd65da27ec6dfb5b28 Signed-off-by: Marcin Masternak --- .../recognition/user_places/location_logger.cpp | 3 +- .../recognition/user_places/places_detector.cpp | 65 ++++++++-------------- .../recognition/user_places/places_detector.h | 18 +----- .../recognition/user_places/visit_detector.cpp | 3 +- 4 files changed, 29 insertions(+), 60 deletions(-) diff --git a/src/place/recognition/user_places/location_logger.cpp b/src/place/recognition/user_places/location_logger.cpp index 3a4fb93..3bcd109 100644 --- a/src/place/recognition/user_places/location_logger.cpp +++ b/src/place/recognition/user_places/location_logger.cpp @@ -193,7 +193,8 @@ int ctx::LocationLogger::db_insert_log(location_event_s location_event) data.set(NULL, LOCATION_COLUMN_METHOD, static_cast(location_event.method)); #endif /* TIZEN_ENGINEER_MODE */ - bool ret = ctx::db_manager::insert(0, LOCATION_TABLE_NAME, data); + int64_t row_id; + bool ret = db_manager::insert_sync(LOCATION_TABLE_NAME, data, &row_id); _D("%s -> DB: location table insert result", ret ? "SUCCESS" : "FAIL"); return ret; } diff --git a/src/place/recognition/user_places/places_detector.cpp b/src/place/recognition/user_places/places_detector.cpp index a3ea9a5..98cb399 100644 --- a/src/place/recognition/user_places/places_detector.cpp +++ b/src/place/recognition/user_places/places_detector.cpp @@ -74,53 +74,27 @@ bool ctx::PlacesDetector::onTimerExpired(int timerId) { _D(""); db_delete_places(); + db_delete_old_visits(); + std::vector records = db_get_visits(); + visits_t visits = visits_from_jsons(records); + process_visits(visits); return true; } -void ctx::PlacesDetector::on_query_result_received(unsigned int query_id, int error, std::vector& records) +std::vector ctx::PlacesDetector::db_get_visits() { - // TODO: - // The below "state machine" approach was choosen because it is not possible to use synchronized database queries in the main thread. - // Probably the more elegant approach would be to use event_driven_thread class where synchronized queries are allowed. - // Consider refactoring. - if (error != ERR_NONE) { - _E("on_query_result_received query_id:%d, error:%d", query_id, error); - } - else if (query_id == PLACES_DETECTOR_QUERY_ID_DELETE_PLACES) { - db_delete_old_visits(); - } - else if (query_id == PLACES_DETECTOR_QUERY_ID_DELETE_OLD_VISITS) { - db_get_visits(); - } - else if (query_id == PLACES_DETECTOR_QUERY_ID_GET_VISITS) { - visits_t visits = visits_from_jsons(records); - process_visits(visits); - } - else if (query_id == PLACES_DETECTOR_QUERY_ID_INSERT_VISIT) { - // Don't do anything. It is fine. - } - else if (query_id == PLACES_DETECTOR_QUERY_ID_INSERT_PLACE) { - // Don't do anything. It is fine. - } - else if (query_id == PLACES_DETECTOR_QUERY_ID_GET_PLACES) { - std::vector> db_places = places_from_jsons(records); - detected_places_update(db_places); - } - else { - _E("on_query_result_received unknown query_id:%d", query_id); - } -} - -void ctx::PlacesDetector::db_get_visits() -{ - bool ret = db_manager::execute(PLACES_DETECTOR_QUERY_ID_GET_VISITS, GET_VISITS_QUERY, this); + std::vector records; + bool ret = db_manager::execute_sync(GET_VISITS_QUERY, &records); _D("load visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); + return records; } -void ctx::PlacesDetector::db_get_places() +std::vector ctx::PlacesDetector::db_get_places() { - bool ret = db_manager::execute(PLACES_DETECTOR_QUERY_ID_GET_PLACES, GET_PLACES_QUERY, this); + std::vector records; + bool ret = db_manager::execute_sync(GET_PLACES_QUERY, &records); _D("load places execute query result: %s", ret ? "SUCCESS" : "FAIL"); + return records; } double ctx::PlacesDetector::double_value_from_json(Json &row, const char* key) @@ -389,7 +363,8 @@ std::shared_ptr ctx::PlacesDetector::graph_from_visits(const std:: void ctx::PlacesDetector::db_delete_places() { - bool ret = db_manager::execute(PLACES_DETECTOR_QUERY_ID_DELETE_PLACES, DELETE_PLACES_QUERY, this); + std::vector records; + bool ret = db_manager::execute_sync(DELETE_PLACES_QUERY, &records); _D("delete places execute query result: %s", ret ? "SUCCESS" : "FAIL"); } @@ -407,8 +382,9 @@ void ctx::PlacesDetector::db_delete_older_visits(time_t threshold) std::stringstream query; query << "DELETE FROM " << VISIT_TABLE; query << " WHERE " << VISIT_COLUMN_END_TIME << " < " << threshold; - // query << " AND 0"; // Always false condition. Uncomment it for not deleting any visit during development. - bool ret = db_manager::execute(PLACES_DETECTOR_QUERY_ID_DELETE_OLD_VISITS, query.str().c_str(), this); + // query << " AND 0"; // XXX: Always false condition. Uncomment it for not deleting any visit during development. + std::vector records; + bool ret = db_manager::execute_sync(query.str().c_str(), &records); _D("delete old visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); } @@ -419,7 +395,9 @@ ctx::PlacesDetector::PlacesDetector(bool test_mode_) return; } db_create_table(); - db_get_places(); + std::vector records = db_get_places(); + std::vector> db_places = places_from_jsons(records); + detected_places_update(db_places); } void ctx::PlacesDetector::db_create_table() @@ -442,7 +420,8 @@ void ctx::PlacesDetector::db_insert_place(const Place &place) data.set(NULL, PLACE_COLUMN_WIFI_APS, place.wifi_aps); data.set(NULL, PLACE_COLUMN_CREATE_DATE, static_cast(place.create_date)); - bool ret = db_manager::insert(PLACES_DETECTOR_QUERY_ID_INSERT_PLACE, PLACE_TABLE, data); + int64_t row_id; + bool ret = db_manager::insert_sync(PLACE_TABLE, data, &row_id); _D("insert place execute query result: %s", ret ? "SUCCESS" : "FAIL"); } diff --git a/src/place/recognition/user_places/places_detector.h b/src/place/recognition/user_places/places_detector.h index fb08ee4..e0461d9 100644 --- a/src/place/recognition/user_places/places_detector.h +++ b/src/place/recognition/user_places/places_detector.h @@ -26,16 +26,7 @@ namespace ctx { - enum { - PLACES_DETECTOR_QUERY_ID_DELETE_PLACES = 1, - PLACES_DETECTOR_QUERY_ID_DELETE_OLD_VISITS = 2, - PLACES_DETECTOR_QUERY_ID_GET_VISITS = 3, - PLACES_DETECTOR_QUERY_ID_INSERT_VISIT = 4, - PLACES_DETECTOR_QUERY_ID_INSERT_PLACE = 5, - PLACES_DETECTOR_QUERY_ID_GET_PLACES = 6 - }; - - class PlacesDetector : public ITimerListener, public db_listener_iface { + class PlacesDetector : public ITimerListener { private: bool test_mode; @@ -50,8 +41,8 @@ namespace ctx { void db_delete_places(); void db_delete_old_visits(); void db_delete_older_visits(time_t threshold); - void db_get_visits(); - void db_get_places(); + std::vector db_get_visits(); + std::vector db_get_places(); void db_insert_place(const Place &place); std::shared_ptr place_from_merged(visits_t &merged_visits); std::vector> detected_places; @@ -64,9 +55,6 @@ namespace ctx { static void merge_location(const visits_t &merged_visits, Place &place); PlacesDetector(bool test_mode_ = false); bool onTimerExpired(int timerId); - void on_creation_result_received(unsigned int query_id, int error) {} - void on_insertion_result_received(unsigned int query_id, int error, int64_t row_id) {} - void on_query_result_received(unsigned int query_id, int error, std::vector& records); std::shared_ptr merge_visits(const std::vector &visits); std::vector> get_places(); diff --git a/src/place/recognition/user_places/visit_detector.cpp b/src/place/recognition/user_places/visit_detector.cpp index 84abb5e..26c3bb5 100644 --- a/src/place/recognition/user_places/visit_detector.cpp +++ b/src/place/recognition/user_places/visit_detector.cpp @@ -420,7 +420,8 @@ int ctx::VisitDetector::db_insert_visit(visit_s visit) _D("db: visit table insert interval: (%d, %d)", visit.interval.start, visit.interval.end); #endif /* TIZEN_ENGINEER_MODE */ - bool ret = db_manager::insert(0, VISIT_TABLE, data); + int64_t row_id; + bool ret = db_manager::insert_sync(VISIT_TABLE, data, &row_id); _D("db: visit table insert result: %s", ret ? "SUCCESS" : "FAIL"); return ret; } -- 2.7.4 From bb52ea000bf973bd227090af3f7f216d0bd4883a Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Mon, 4 Apr 2016 13:21:59 +0900 Subject: [PATCH 04/16] Apply Tizen C++ coding style based on context-common changes - ContextManager, IContextManager, ContextProviderBase(context_provider_iface) Change-Id: Icfbdfaaf570a98aba2115cb3c169722a3f01b7ab Signed-off-by: Somin Kim --- include/custom_context_provider.h | 8 +-- src/custom/custom_base.cpp | 14 ++-- src/custom/custom_base.h | 10 +-- src/custom/custom_context_provider.cpp | 30 ++++----- src/device/activity/activity.h | 4 +- src/device/activity/activity_base.cpp | 14 ++-- src/device/activity/activity_base.h | 2 +- src/device/device_context_provider.cpp | 74 +++++++++++----------- ...{provider_base.cpp => device_provider_base.cpp} | 8 +-- .../{provider_base.h => device_provider_base.h} | 14 ++-- src/device/social/call.cpp | 6 +- src/device/social/call.h | 2 +- src/device/social/contacts.cpp | 4 +- src/device/social/contacts.h | 2 +- src/device/social/email.cpp | 16 ++--- src/device/social/email.h | 2 +- src/device/social/message.cpp | 4 +- src/device/social/message.h | 2 +- src/device/system/alarm.cpp | 18 +++--- src/device/system/alarm.h | 12 ++-- src/device/system/battery.cpp | 20 +++--- src/device/system/battery.h | 2 +- src/device/system/headphone.cpp | 6 +- src/device/system/headphone.h | 2 +- src/device/system/psmode.cpp | 16 ++--- src/device/system/psmode.h | 2 +- src/device/system/runtime-info/base_rtinfo.h | 2 +- src/device/system/runtime-info/charger.cpp | 16 ++--- src/device/system/runtime-info/gps.cpp | 16 ++--- src/device/system/runtime-info/usb.cpp | 16 ++--- src/device/system/time.cpp | 14 ++-- src/device/system/time.h | 2 +- src/device/system/wifi.cpp | 12 ++-- src/device/system/wifi.h | 2 +- src/place/geofence/myplace_handle.cpp | 2 +- src/place/geofence/place_geofence.cpp | 12 ++-- src/place/geofence/place_geofence.h | 12 ++-- src/place/place_context_provider.cpp | 14 ++-- src/place/recognition/place_recognition.cpp | 14 ++-- src/place/recognition/place_recognition.h | 12 ++-- src/statistics/app/app_stats_provider.cpp | 12 ++-- src/statistics/app/app_stats_provider.h | 12 ++-- src/statistics/app/db_handle.cpp | 4 +- src/statistics/media/db_handle.cpp | 4 +- src/statistics/media/media_stats_provider.cpp | 14 ++-- src/statistics/media/media_stats_provider.h | 12 ++-- src/statistics/shared/db_handle_base.cpp | 6 +- src/statistics/social/db_handle.cpp | 4 +- src/statistics/social/social_stats_provider.cpp | 12 ++-- src/statistics/social/social_stats_provider.h | 12 ++-- src/statistics/statistics_context_provider.cpp | 50 +++++++-------- 51 files changed, 291 insertions(+), 291 deletions(-) rename src/device/{provider_base.cpp => device_provider_base.cpp} (93%) rename src/device/{provider_base.h => device_provider_base.h} (89%) diff --git a/include/custom_context_provider.h b/include/custom_context_provider.h index 17c8cc4..918dfa6 100644 --- a/include/custom_context_provider.h +++ b/include/custom_context_provider.h @@ -21,11 +21,11 @@ namespace ctx { bool init_custom_context_provider(); namespace custom_context_provider { - int add_item(std::string subject, std::string name, ctx::Json tmpl, const char* owner, bool is_init = false); - int remove_item(std::string subject); - int publish_data(std::string subject, ctx::Json fact); + int addItem(std::string subject, std::string name, ctx::Json tmpl, const char* owner, bool is_init = false); + int removeItem(std::string subject); + int publishData(std::string subject, ctx::Json fact); - context_provider_iface* create(void* data); + ContextProviderBase* create(void* data); void destroy(void* data); } } diff --git a/src/custom/custom_base.cpp b/src/custom/custom_base.cpp index c5ac58d..4371202 100644 --- a/src/custom/custom_base.cpp +++ b/src/custom/custom_base.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "custom_base.h" ctx::custom_base::custom_base(std::string subject, std::string name, ctx::Json tmpl, std::string owner) : @@ -36,16 +36,16 @@ bool ctx::custom_base::is_supported() void ctx::custom_base::submit_trigger_item() { - context_manager::register_trigger_item(_subject.c_str(), OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(_subject.c_str(), OPS_SUBSCRIBE | OPS_READ, _tmpl.str(), NULL, _owner.c_str()); } void ctx::custom_base::unsubmit_trigger_item() { - context_manager::unregister_trigger_item(_subject.c_str()); + context_manager::unregisterTriggerItem(_subject.c_str()); } -int ctx::custom_base::subscribe(const char *subject, ctx::Json option, ctx::Json *request_result) +int ctx::custom_base::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) { return ERR_NONE; @@ -56,14 +56,14 @@ int ctx::custom_base::unsubscribe(const char *subject, ctx::Json option) return ERR_NONE; } -int ctx::custom_base::read(const char *subject, ctx::Json option, ctx::Json *request_result) +int ctx::custom_base::read(const char *subject, ctx::Json option, ctx::Json *requestResult) { ctx::Json data = latest.str(); - ctx::context_manager::reply_to_read(_subject.c_str(), NULL, ERR_NONE, data); + ctx::context_manager::replyToRead(_subject.c_str(), NULL, ERR_NONE, data); return ERR_NONE; } -int ctx::custom_base::write(const char *subject, ctx::Json data, ctx::Json *request_result) +int ctx::custom_base::write(const char *subject, ctx::Json data, ctx::Json *requestResult) { return ERR_NONE; } diff --git a/src/custom/custom_base.h b/src/custom/custom_base.h index 0278e0f..68e45cc 100644 --- a/src/custom/custom_base.h +++ b/src/custom/custom_base.h @@ -18,20 +18,20 @@ #define _CUSTOM_BASE_H_ #include -#include +#include #include namespace ctx { - class custom_base : public context_provider_iface { + class custom_base : public ContextProviderBase { public: custom_base(std::string subject, std::string name, ctx::Json tmpl, std::string owner); ~custom_base(); - int subscribe(const char *subject, ctx::Json option, ctx::Json *request_result); + int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); - int read(const char *subject, ctx::Json option, ctx::Json *request_result); - int write(const char *subject, ctx::Json data, ctx::Json *request_result); + int read(const char *subject, ctx::Json option, ctx::Json *requestResult); + int write(const char *subject, ctx::Json data, ctx::Json *requestResult); static bool is_supported(); void submit_trigger_item(); diff --git a/src/custom/custom_context_provider.cpp b/src/custom/custom_context_provider.cpp index 29c9100..88aca00 100644 --- a/src/custom/custom_context_provider.cpp +++ b/src/custom/custom_context_provider.cpp @@ -17,8 +17,8 @@ #include #include #include -#include -#include +#include +#include #include #include #include "custom_base.h" @@ -29,24 +29,24 @@ static bool is_valid_fact(std::string subject, ctx::Json& fact); static bool check_value_int(ctx::Json& tmpl, std::string key, int value); static bool check_value_string(ctx::Json& tmpl, std::string key, std::string value); -void register_provider(const char *subject, const char *privilege) +void registerProvider(const char *subject, const char *privilege) { - ctx::context_provider_info provider_info(ctx::custom_context_provider::create, + ctx::ContextProviderInfo providerInfo(ctx::custom_context_provider::create, ctx::custom_context_provider::destroy, const_cast(subject), privilege); - ctx::context_manager::register_provider(subject, provider_info); + ctx::context_manager::registerProvider(subject, providerInfo); custom_map[subject]->submit_trigger_item(); } -void unregister_provider(const char* subject) +void unregisterProvider(const char* subject) { custom_map[subject]->unsubmit_trigger_item(); - ctx::context_manager::unregister_provider(subject); + ctx::context_manager::unregisterProvider(subject); } -EXTAPI ctx::context_provider_iface* ctx::custom_context_provider::create(void *data) +EXTAPI ctx::ContextProviderBase* ctx::custom_context_provider::create(void *data) { - // Already created in add_item() function. Return corresponding custom provider + // Already created in addItem() function. Return corresponding custom provider return custom_map[static_cast(data)]; } @@ -89,7 +89,7 @@ EXTAPI bool ctx::init_custom_context_provider() elem.get(NULL, "attributes", &attributes); elem.get(NULL, "owner", &owner); - error = ctx::custom_context_provider::add_item(subject, name, ctx::Json(attributes), owner.c_str(), true); + error = ctx::custom_context_provider::addItem(subject, name, ctx::Json(attributes), owner.c_str(), true); if (error != ERR_NONE) { _E("Failed to add custom item(%s): %#x", subject.c_str(), error); } @@ -98,7 +98,7 @@ EXTAPI bool ctx::init_custom_context_provider() return true; } -EXTAPI int ctx::custom_context_provider::add_item(std::string subject, std::string name, ctx::Json tmpl, const char* owner, bool is_init) +EXTAPI int ctx::custom_context_provider::addItem(std::string subject, std::string name, ctx::Json tmpl, const char* owner, bool is_init) { std::map::iterator it; it = custom_map.find(subject); @@ -116,7 +116,7 @@ EXTAPI int ctx::custom_context_provider::add_item(std::string subject, std::stri IF_FAIL_RETURN_TAG(custom, ERR_OUT_OF_MEMORY, _E, "Memory allocation failed"); custom_map[subject] = custom; - register_provider(custom->get_subject(), NULL); + registerProvider(custom->get_subject(), NULL); // Add item to custom template db if (!is_init) { @@ -130,13 +130,13 @@ EXTAPI int ctx::custom_context_provider::add_item(std::string subject, std::stri return ERR_NONE; } -EXTAPI int ctx::custom_context_provider::remove_item(std::string subject) +EXTAPI int ctx::custom_context_provider::removeItem(std::string subject) { std::map::iterator it; it = custom_map.find(subject); IF_FAIL_RETURN_TAG(it != custom_map.end(), ERR_NOT_SUPPORTED, _E, "%s not supported", subject.c_str()); - unregister_provider(subject.c_str()); + unregisterProvider(subject.c_str()); // Remove item from custom template db std::string q = "DELETE FROM context_trigger_custom_template WHERE subject = '" + subject + "'"; @@ -147,7 +147,7 @@ EXTAPI int ctx::custom_context_provider::remove_item(std::string subject) return ERR_NONE; } -EXTAPI int ctx::custom_context_provider::publish_data(std::string subject, ctx::Json fact) +EXTAPI int ctx::custom_context_provider::publishData(std::string subject, ctx::Json fact) { std::map::iterator it; it = custom_map.find(subject); diff --git a/src/device/activity/activity.h b/src/device/activity/activity.h index d0e0951..2f44267 100644 --- a/src/device/activity/activity.h +++ b/src/device/activity/activity.h @@ -23,7 +23,7 @@ #define GENERATE_ACTIVITY_PROVIDER(act_prvd, act_subj, act_type) \ class act_prvd : public user_activity_base { \ public: \ - static context_provider_iface *create(void *data) \ + static ContextProviderBase *create(void *data) \ { \ CREATE_INSTANCE(ctx::act_prvd); \ } \ @@ -37,7 +37,7 @@ } \ static void submit_trigger_item() \ { \ - context_manager::register_trigger_item((act_subj), OPS_SUBSCRIBE, \ + context_manager::registerTriggerItem((act_subj), OPS_SUBSCRIBE, \ "{\"Event\":{\"type\":\"string\", \"values\":[\"Detected\"]}}", \ "{\"Accuracy\":{\"type\":\"string\", \"values\":[\"Low\", \"Normal\", \"High\"]}}" \ ); \ diff --git a/src/device/activity/activity_base.cpp b/src/device/activity/activity_base.cpp index e0a9027..30201ca 100644 --- a/src/device/activity/activity_base.cpp +++ b/src/device/activity/activity_base.cpp @@ -15,7 +15,7 @@ */ #include -#include +#include #include "activity_types.h" #include "activity_base.h" @@ -44,25 +44,25 @@ void ctx::user_activity_base::handle_event(activity_type_e activity, const activ { IF_FAIL_VOID_TAG(activity == activity_type, _E, "Invalid activity: %d", activity); - ctx::Json data_read; - data_read.set(NULL, USER_ACT_EVENT, USER_ACT_DETECTED); + ctx::Json dataRead; + dataRead.set(NULL, USER_ACT_EVENT, USER_ACT_DETECTED); activity_accuracy_e accuracy = ACTIVITY_ACCURACY_LOW; activity_get_accuracy(data, &accuracy); switch (accuracy) { case ACTIVITY_ACCURACY_HIGH: - data_read.set(NULL, USER_ACT_ACCURACY, USER_ACT_HIGH); + dataRead.set(NULL, USER_ACT_ACCURACY, USER_ACT_HIGH); break; case ACTIVITY_ACCURACY_MID: - data_read.set(NULL, USER_ACT_ACCURACY, USER_ACT_NORMAL); + dataRead.set(NULL, USER_ACT_ACCURACY, USER_ACT_NORMAL); break; default: - data_read.set(NULL, USER_ACT_ACCURACY, USER_ACT_LOW); + dataRead.set(NULL, USER_ACT_ACCURACY, USER_ACT_LOW); break; } - context_manager::publish(subject.c_str(), NULL, ERR_NONE, data_read); + context_manager::publish(subject.c_str(), NULL, ERR_NONE, dataRead); } int ctx::user_activity_base::subscribe() diff --git a/src/device/activity/activity_base.h b/src/device/activity/activity_base.h index 45fcc8d..05fa503 100644 --- a/src/device/activity/activity_base.h +++ b/src/device/activity/activity_base.h @@ -19,7 +19,7 @@ #include #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/device_context_provider.cpp b/src/device/device_context_provider.cpp index be6d911..39fcf7d 100644 --- a/src/device/device_context_provider.cpp +++ b/src/device/device_context_provider.cpp @@ -15,8 +15,8 @@ */ #include -#include -#include +#include +#include #include #include "system/system_types.h" @@ -65,40 +65,40 @@ #define PRIV_CONTACT "contact.read" template -void register_provider(const char *subject, const char *privilege) +void registerProvider(const char *subject, const char *privilege) { if (!provider::is_supported()) return; - ctx::context_provider_info provider_info(provider::create, provider::destroy, NULL, privilege); - ctx::context_manager::register_provider(subject, provider_info); + ctx::ContextProviderInfo providerInfo(provider::create, provider::destroy, NULL, privilege); + ctx::context_manager::registerProvider(subject, providerInfo); provider::submit_trigger_item(); } EXTAPI bool ctx::init_device_context_provider() { - register_provider(DEVICE_ST_SUBJ_ALARM, NULL); - register_provider(DEVICE_ST_SUBJ_TIME, NULL); + registerProvider(DEVICE_ST_SUBJ_ALARM, NULL); + registerProvider(DEVICE_ST_SUBJ_TIME, NULL); #ifdef _MOBILE_ - register_provider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); - register_provider(DEVICE_ST_SUBJ_HEADPHONE, NULL); + registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); + registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); - register_provider(DEVICE_ST_SUBJ_CHARGER, NULL); - register_provider(DEVICE_ST_SUBJ_GPS, NULL); - register_provider(DEVICE_ST_SUBJ_USB, NULL); - register_provider(DEVICE_ST_SUBJ_BATTERY, NULL); - register_provider(DEVICE_ST_SUBJ_PSMODE, NULL); + registerProvider(DEVICE_ST_SUBJ_CHARGER, NULL); + registerProvider(DEVICE_ST_SUBJ_GPS, NULL); + registerProvider(DEVICE_ST_SUBJ_USB, NULL); + registerProvider(DEVICE_ST_SUBJ_BATTERY, NULL); + registerProvider(DEVICE_ST_SUBJ_PSMODE, NULL); - register_provider(SOCIAL_ST_SUBJ_CALL, PRIV_TELEPHONY); - register_provider(SOCIAL_ST_SUBJ_EMAIL, NULL); - register_provider(SOCIAL_ST_SUBJ_MESSAGE, PRIV_MESSAGE); - register_provider(SOCIAL_ST_SUBJ_CONTACTS, PRIV_CONTACT); + registerProvider(SOCIAL_ST_SUBJ_CALL, PRIV_TELEPHONY); + registerProvider(SOCIAL_ST_SUBJ_EMAIL, NULL); + registerProvider(SOCIAL_ST_SUBJ_MESSAGE, PRIV_MESSAGE); + registerProvider(SOCIAL_ST_SUBJ_CONTACTS, PRIV_CONTACT); - register_provider(USER_ACT_SUBJ_STATIONARY, NULL); - register_provider(USER_ACT_SUBJ_WALKING, NULL); - register_provider(USER_ACT_SUBJ_RUNNING, NULL); - register_provider(USER_ACT_SUBJ_IN_VEHICLE, NULL); + registerProvider(USER_ACT_SUBJ_STATIONARY, NULL); + registerProvider(USER_ACT_SUBJ_WALKING, NULL); + registerProvider(USER_ACT_SUBJ_RUNNING, NULL); + registerProvider(USER_ACT_SUBJ_IN_VEHICLE, NULL); /* Create context providers, which need to be initiated before being subscribed */ if (device_status_wifi::is_supported()) @@ -106,22 +106,22 @@ EXTAPI bool ctx::init_device_context_provider() #endif #ifdef _WEARABLE_ - register_provider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); - register_provider(DEVICE_ST_SUBJ_HEADPHONE, NULL); + registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); + registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); - register_provider(DEVICE_ST_SUBJ_CHARGER, NULL); - register_provider(DEVICE_ST_SUBJ_GPS, NULL); - register_provider(DEVICE_ST_SUBJ_USB, NULL); - register_provider(DEVICE_ST_SUBJ_BATTERY, NULL); - register_provider(DEVICE_ST_SUBJ_PSMODE, NULL); + registerProvider(DEVICE_ST_SUBJ_CHARGER, NULL); + registerProvider(DEVICE_ST_SUBJ_GPS, NULL); + registerProvider(DEVICE_ST_SUBJ_USB, NULL); + registerProvider(DEVICE_ST_SUBJ_BATTERY, NULL); + registerProvider(DEVICE_ST_SUBJ_PSMODE, NULL); - register_provider(SOCIAL_ST_SUBJ_CALL, PRIV_TELEPHONY); - register_provider(SOCIAL_ST_SUBJ_MESSAGE, PRIV_MESSAGE); + registerProvider(SOCIAL_ST_SUBJ_CALL, PRIV_TELEPHONY); + registerProvider(SOCIAL_ST_SUBJ_MESSAGE, PRIV_MESSAGE); - register_provider(USER_ACT_SUBJ_STATIONARY, NULL); - register_provider(USER_ACT_SUBJ_WALKING, NULL); - register_provider(USER_ACT_SUBJ_RUNNING, NULL); - register_provider(USER_ACT_SUBJ_IN_VEHICLE, NULL); + registerProvider(USER_ACT_SUBJ_STATIONARY, NULL); + registerProvider(USER_ACT_SUBJ_WALKING, NULL); + registerProvider(USER_ACT_SUBJ_RUNNING, NULL); + registerProvider(USER_ACT_SUBJ_IN_VEHICLE, NULL); /* Create context providers, which need to be initiated before being subscribed */ if (device_status_wifi::is_supported()) @@ -129,8 +129,8 @@ EXTAPI bool ctx::init_device_context_provider() #endif #ifdef _TV_ - register_provider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); - register_provider(DEVICE_ST_SUBJ_HEADPHONE, NULL); + registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); + registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); /* Create context providers, which need to be initiated before being subscribed */ if (device_status_wifi::is_supported()) diff --git a/src/device/provider_base.cpp b/src/device/device_provider_base.cpp similarity index 93% rename from src/device/provider_base.cpp rename to src/device/device_provider_base.cpp index fefe212..95f3988 100644 --- a/src/device/provider_base.cpp +++ b/src/device/device_provider_base.cpp @@ -15,14 +15,14 @@ */ #include -#include "provider_base.h" +#include "device_provider_base.h" ctx::device_provider_base::device_provider_base() : being_subscribed(false) { } -int ctx::device_provider_base::subscribe(const char *subject, ctx::Json option, ctx::Json *request_result) +int ctx::device_provider_base::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) { IF_FAIL_RETURN(!being_subscribed, ERR_NONE); @@ -47,7 +47,7 @@ int ctx::device_provider_base::unsubscribe(const char *subject, ctx::Json option return ret; } -int ctx::device_provider_base::read(const char *subject, ctx::Json option, ctx::Json *request_result) +int ctx::device_provider_base::read(const char *subject, ctx::Json option, ctx::Json *requestResult) { int ret = read(); @@ -57,7 +57,7 @@ int ctx::device_provider_base::read(const char *subject, ctx::Json option, ctx:: return ret; } -int ctx::device_provider_base::write(const char *subject, ctx::Json data, ctx::Json *request_result) +int ctx::device_provider_base::write(const char *subject, ctx::Json data, ctx::Json *requestResult) { int ret = write(); diff --git a/src/device/provider_base.h b/src/device/device_provider_base.h similarity index 89% rename from src/device/provider_base.h rename to src/device/device_provider_base.h index 39983b1..6b2c1a9 100644 --- a/src/device/provider_base.h +++ b/src/device/device_provider_base.h @@ -19,7 +19,7 @@ #include #include -#include +#include #define CREATE_INSTANCE(prvd) \ do { \ @@ -40,7 +40,7 @@ #define GENERATE_PROVIDER_COMMON_DECL(prvd) \ public: \ - static context_provider_iface *create(void *data); \ + static ContextProviderBase *create(void *data); \ static void destroy(void *data); \ protected: \ void destroy_self(); \ @@ -49,7 +49,7 @@ #define GENERATE_PROVIDER_COMMON_IMPL(prvd) \ ctx::prvd *ctx::prvd::__instance = NULL; \ - ctx::context_provider_iface *ctx::prvd::create(void *data) \ + ctx::ContextProviderBase *ctx::prvd::create(void *data) \ { \ CREATE_INSTANCE(prvd); \ } \ @@ -64,12 +64,12 @@ namespace ctx { - class device_provider_base : public context_provider_iface { + class device_provider_base : public ContextProviderBase { public: - int subscribe(const char *subject, ctx::Json option, ctx::Json *request_result); + int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); - int read(const char *subject, ctx::Json option, ctx::Json *request_result); - int write(const char *subject, ctx::Json data, ctx::Json *request_result); + int read(const char *subject, ctx::Json option, ctx::Json *requestResult); + int write(const char *subject, ctx::Json data, ctx::Json *requestResult); protected: bool being_subscribed; diff --git a/src/device/social/call.cpp b/src/device/social/call.cpp index 745442c..71e3ea8 100644 --- a/src/device/social/call.cpp +++ b/src/device/social/call.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include "social_types.h" #include "call.h" @@ -57,7 +57,7 @@ bool ctx::social_status_call::is_supported() void ctx::social_status_call::submit_trigger_item() { - context_manager::register_trigger_item(SOCIAL_ST_SUBJ_CALL, OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(SOCIAL_ST_SUBJ_CALL, OPS_SUBSCRIBE | OPS_READ, "{" "\"Medium\":{\"type\":\"string\",\"values\":[\"Voice\",\"Video\"]}," "\"State\":{\"type\":\"string\",\"values\":[\"Idle\",\"Connecting\",\"Connected\"]}," @@ -381,7 +381,7 @@ int ctx::social_status_call::read() release_telephony(); if (ret) { - ctx::context_manager::reply_to_read(SOCIAL_ST_SUBJ_CALL, NULL, ERR_NONE, data); + ctx::context_manager::replyToRead(SOCIAL_ST_SUBJ_CALL, NULL, ERR_NONE, data); return ERR_NONE; } diff --git a/src/device/social/call.h b/src/device/social/call.h index cdd906c..f320f5c 100644 --- a/src/device/social/call.h +++ b/src/device/social/call.h @@ -18,7 +18,7 @@ #define _CONTEXT_SOCIAL_STATUS_CALL_H_ #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/social/contacts.cpp b/src/device/social/contacts.cpp index c7ee6e3..f071e78 100644 --- a/src/device/social/contacts.cpp +++ b/src/device/social/contacts.cpp @@ -15,7 +15,7 @@ */ #include -#include +#include #include "social_types.h" #include "contacts.h" @@ -42,7 +42,7 @@ bool ctx::social_status_contacts::is_supported() void ctx::social_status_contacts::submit_trigger_item() { - context_manager::register_trigger_item(SOCIAL_ST_SUBJ_CONTACTS, OPS_SUBSCRIBE, + context_manager::registerTriggerItem(SOCIAL_ST_SUBJ_CONTACTS, OPS_SUBSCRIBE, "{" "\"Event\":{\"type\":\"string\",\"values\":[\"Changed\"]}," "\"Type\":{\"type\":\"string\",\"values\":[\"MyProfile\",\"Person\"]}" diff --git a/src/device/social/contacts.h b/src/device/social/contacts.h index 52adb14..1169412 100644 --- a/src/device/social/contacts.h +++ b/src/device/social/contacts.h @@ -18,7 +18,7 @@ #define _CONTEXT_SOCIAL_STATUS_CONTACTS_H_ #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/social/email.cpp b/src/device/social/email.cpp index 831a963..898cf03 100644 --- a/src/device/social/email.cpp +++ b/src/device/social/email.cpp @@ -17,7 +17,7 @@ #include #include -#include +#include #include "social_types.h" #include "email.h" @@ -40,7 +40,7 @@ bool ctx::social_status_email::is_supported() void ctx::social_status_email::submit_trigger_item() { - context_manager::register_trigger_item(SOCIAL_ST_SUBJ_EMAIL, OPS_SUBSCRIBE, + context_manager::registerTriggerItem(SOCIAL_ST_SUBJ_EMAIL, OPS_SUBSCRIBE, "{" "\"Event\":{\"type\":\"string\",\"values\":[\"Received\",\"Sent\"]}" "}", @@ -60,15 +60,15 @@ void ctx::social_status_email::onSignal(const char* sender, const char* path, co if (sub_type == NOTI_DOWNLOAD_FINISH) { //TODO: Check if this signal actually means that there are new mails _D("sub type: %d, gi1: %d, gc: %s, gi2: %d, gi3: %d", sub_type, gi1, gc, gi2, gi3); - ctx::Json data_updated; - data_updated.set(NULL, SOCIAL_ST_EVENT, SOCIAL_ST_RECEIVED); - context_manager::publish(SOCIAL_ST_SUBJ_EMAIL, NULL, ERR_NONE, data_updated); + ctx::Json dataUpdated; + dataUpdated.set(NULL, SOCIAL_ST_EVENT, SOCIAL_ST_RECEIVED); + context_manager::publish(SOCIAL_ST_SUBJ_EMAIL, NULL, ERR_NONE, dataUpdated); } else if (sub_type == NOTI_SEND_FINISH) { _D("sub type: %d, gi1: %d, gc: %s, gi2: %d, gi3: %d", sub_type, gi1, gc, gi2, gi3); - ctx::Json data_updated; - data_updated.set(NULL, SOCIAL_ST_EVENT, SOCIAL_ST_SENT); - context_manager::publish(SOCIAL_ST_SUBJ_EMAIL, NULL, ERR_NONE, data_updated); + ctx::Json dataUpdated; + dataUpdated.set(NULL, SOCIAL_ST_EVENT, SOCIAL_ST_SENT); + context_manager::publish(SOCIAL_ST_SUBJ_EMAIL, NULL, ERR_NONE, dataUpdated); } } diff --git a/src/device/social/email.h b/src/device/social/email.h index 930da24..9cc7508 100644 --- a/src/device/social/email.h +++ b/src/device/social/email.h @@ -18,7 +18,7 @@ #define _CONTEXT_SOCIAL_STATUS_EMAIL_H_ #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/social/message.cpp b/src/device/social/message.cpp index 4d46fe9..cf75e4f 100644 --- a/src/device/social/message.cpp +++ b/src/device/social/message.cpp @@ -15,7 +15,7 @@ */ #include -#include +#include #include "social_types.h" #include "message.h" @@ -39,7 +39,7 @@ bool ctx::social_status_message::is_supported() void ctx::social_status_message::submit_trigger_item() { - context_manager::register_trigger_item(SOCIAL_ST_SUBJ_MESSAGE, OPS_SUBSCRIBE, + context_manager::registerTriggerItem(SOCIAL_ST_SUBJ_MESSAGE, OPS_SUBSCRIBE, "{" "\"Event\":{\"type\":\"string\",\"values\":[\"Received\"]}," "\"Type\":{\"type\":\"string\",\"values\":[\"SMS\",\"MMS\"]}," diff --git a/src/device/social/message.h b/src/device/social/message.h index 1c1d15b..5239f21 100644 --- a/src/device/social/message.h +++ b/src/device/social/message.h @@ -19,7 +19,7 @@ #include #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/system/alarm.cpp b/src/device/system/alarm.cpp index d1c6f26..d4434a9 100644 --- a/src/device/system/alarm.cpp +++ b/src/device/system/alarm.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "system_types.h" #include "alarm.h" @@ -41,7 +41,7 @@ bool ctx::device_status_alarm::is_supported() void ctx::device_status_alarm::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_ALARM, OPS_SUBSCRIBE, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_ALARM, OPS_SUBSCRIBE, "{" "\"TimeOfDay\":{\"type\":\"integer\",\"min\":0,\"max\":1439}," "\"DayOfWeek\":{\"type\":\"string\",\"values\":[\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\",\"Weekday\",\"Weekend\"]}" @@ -49,7 +49,7 @@ void ctx::device_status_alarm::submit_trigger_item() NULL); } -int ctx::device_status_alarm::subscribe(const char *subject, ctx::Json option, ctx::Json *request_result) +int ctx::device_status_alarm::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) { int ret = subscribe(option); destroy_if_unused(); @@ -63,13 +63,13 @@ int ctx::device_status_alarm::unsubscribe(const char *subject, ctx::Json option) return ret; } -int ctx::device_status_alarm::read(const char *subject, ctx::Json option, ctx::Json *request_result) +int ctx::device_status_alarm::read(const char *subject, ctx::Json option, ctx::Json *requestResult) { destroy_if_unused(); return ERR_NOT_SUPPORTED; } -int ctx::device_status_alarm::write(const char *subject, ctx::Json data, ctx::Json *request_result) +int ctx::device_status_alarm::write(const char *subject, ctx::Json data, ctx::Json *requestResult) { destroy_if_unused(); return ERR_NOT_SUPPORTED; @@ -250,16 +250,16 @@ void ctx::device_status_alarm::on_timer_expired(int hour, int min, int day_of_we { _I("Time: %02d:%02d, Day of Week: %#x", hour, min, day_of_week); - ctx::Json data_read; + ctx::Json dataRead; int result_time = hour * 60 + min; std::string result_day = ctx::TimerManager::dowToStr(day_of_week); - data_read.set(NULL, DEVICE_ST_TIME_OF_DAY, result_time); - data_read.set(NULL, DEVICE_ST_DAY_OF_WEEK, result_day); + dataRead.set(NULL, DEVICE_ST_TIME_OF_DAY, result_time); + dataRead.set(NULL, DEVICE_ST_DAY_OF_WEEK, result_day); for (option_t::iterator it = option_set.begin(); it != option_set.end(); ++it) { ctx::Json option = (**it); if (is_matched(option, result_time, result_day)) { - context_manager::publish(DEVICE_ST_SUBJ_ALARM, option, ERR_NONE, data_read); + context_manager::publish(DEVICE_ST_SUBJ_ALARM, option, ERR_NONE, dataRead); } } } diff --git a/src/device/system/alarm.h b/src/device/system/alarm.h index 8d640e3..ff5271b 100644 --- a/src/device/system/alarm.h +++ b/src/device/system/alarm.h @@ -19,21 +19,21 @@ #include #include -#include +#include #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { - class device_status_alarm : public context_provider_iface, ITimerListener { + class device_status_alarm : public ContextProviderBase, ITimerListener { GENERATE_PROVIDER_COMMON_DECL(device_status_alarm); public: - int subscribe(const char *subject, ctx::Json option, ctx::Json *request_result); + int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); - int read(const char *subject, ctx::Json option, ctx::Json *request_result); - int write(const char *subject, ctx::Json data, ctx::Json *request_result); + int read(const char *subject, ctx::Json option, ctx::Json *requestResult); + int write(const char *subject, ctx::Json data, ctx::Json *requestResult); int subscribe(ctx::Json option); int unsubscribe(ctx::Json option); diff --git a/src/device/system/battery.cpp b/src/device/system/battery.cpp index 5be24b6..6207db9 100644 --- a/src/device/system/battery.cpp +++ b/src/device/system/battery.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "system_types.h" #include "battery.h" @@ -35,7 +35,7 @@ bool ctx::device_status_battery::is_supported() void ctx::device_status_battery::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_BATTERY, OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_BATTERY, OPS_SUBSCRIBE | OPS_READ, "{" "\"Level\":{\"type\":\"string\",\"values\":[\"Empty\",\"Critical\",\"Low\",\"Normal\",\"High\",\"Full\"]}," TRIG_BOOL_ITEM_DEF("IsCharging") @@ -58,15 +58,15 @@ void ctx::device_status_battery::handle_update(device_callback_e device_type, vo const char* level_string = trans_to_string(level); IF_FAIL_VOID(level_string); - ctx::Json data_read; - data_read.set(NULL, DEVICE_ST_LEVEL, level_string); + ctx::Json dataRead; + dataRead.set(NULL, DEVICE_ST_LEVEL, level_string); bool charging_state = false; int ret = device_battery_is_charging(&charging_state); IF_FAIL_VOID_TAG(ret == DEVICE_ERROR_NONE, _E, "Getting state failed"); - data_read.set(NULL, DEVICE_ST_IS_CHARGING, charging_state ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); - ctx::context_manager::publish(DEVICE_ST_SUBJ_BATTERY, NULL, ERR_NONE, data_read); + dataRead.set(NULL, DEVICE_ST_IS_CHARGING, charging_state ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + ctx::context_manager::publish(DEVICE_ST_SUBJ_BATTERY, NULL, ERR_NONE, dataRead); } const char* ctx::device_status_battery::trans_to_string(intptr_t level) @@ -120,7 +120,7 @@ int ctx::device_status_battery::unsubscribe() int ctx::device_status_battery::read() { device_battery_level_e level; - ctx::Json data_read; + ctx::Json dataRead; int ret = device_battery_get_level_status(&level); IF_FAIL_RETURN(ret == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED); @@ -128,14 +128,14 @@ int ctx::device_status_battery::read() const char* level_string = trans_to_string(level); IF_FAIL_RETURN(level_string, ERR_OPERATION_FAILED); - data_read.set(NULL, DEVICE_ST_LEVEL, level_string); + dataRead.set(NULL, DEVICE_ST_LEVEL, level_string); bool charging_state = false; ret = device_battery_is_charging(&charging_state); IF_FAIL_RETURN(ret == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED); - data_read.set(NULL, DEVICE_ST_IS_CHARGING, charging_state ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + dataRead.set(NULL, DEVICE_ST_IS_CHARGING, charging_state ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); - ctx::context_manager::reply_to_read(DEVICE_ST_SUBJ_BATTERY, NULL, ERR_NONE, data_read); + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_BATTERY, NULL, ERR_NONE, dataRead); return ERR_NONE; } diff --git a/src/device/system/battery.h b/src/device/system/battery.h index 6fc3fdf..8f8a723 100644 --- a/src/device/system/battery.h +++ b/src/device/system/battery.h @@ -19,7 +19,7 @@ #include #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/system/headphone.cpp b/src/device/system/headphone.cpp index ac3d5db..91e1708 100644 --- a/src/device/system/headphone.cpp +++ b/src/device/system/headphone.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "system_types.h" #include "headphone.h" @@ -44,7 +44,7 @@ bool ctx::device_status_headphone::is_supported() void ctx::device_status_headphone::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_HEADPHONE, OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_HEADPHONE, OPS_SUBSCRIBE | OPS_READ, "{" TRIG_BOOL_ITEM_DEF("IsConnected") "," "\"Type\":{\"type\":\"string\",\"values\":[\"Normal\",\"Headset\",\"Bluetooth\"]}" @@ -81,7 +81,7 @@ int ctx::device_status_headphone::read() Json data; generate_data_packet(data); - ctx::context_manager::reply_to_read(DEVICE_ST_SUBJ_HEADPHONE, NULL, ERR_NONE, data); + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_HEADPHONE, NULL, ERR_NONE, data); return ERR_NONE; } diff --git a/src/device/system/headphone.h b/src/device/system/headphone.h index f451d52..8922a61 100644 --- a/src/device/system/headphone.h +++ b/src/device/system/headphone.h @@ -20,7 +20,7 @@ #include #include #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/system/psmode.cpp b/src/device/system/psmode.cpp index dcfc359..dc39f98 100644 --- a/src/device/system/psmode.cpp +++ b/src/device/system/psmode.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "system_types.h" #include "psmode.h" @@ -35,7 +35,7 @@ bool ctx::device_status_psmode::is_supported() void ctx::device_status_psmode::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_PSMODE, OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_PSMODE, OPS_SUBSCRIBE | OPS_READ, "{" TRIG_BOOL_ITEM_DEF("IsEnabled") "}", NULL); } @@ -48,14 +48,14 @@ void ctx::device_status_psmode::update_cb(keynode_t *node, void* user_data) void ctx::device_status_psmode::handle_update(keynode_t *node) { int status; - ctx::Json data_read; + ctx::Json dataRead; status = vconf_keynode_get_int(node); IF_FAIL_VOID_TAG(status >= 0, _E, "Getting state failed"); - data_read.set(NULL, DEVICE_ST_IS_ENABLED, status == 0 ? DEVICE_ST_FALSE : DEVICE_ST_TRUE); + dataRead.set(NULL, DEVICE_ST_IS_ENABLED, status == 0 ? DEVICE_ST_FALSE : DEVICE_ST_TRUE); - context_manager::publish(DEVICE_ST_SUBJ_PSMODE, NULL, ERR_NONE, data_read); + context_manager::publish(DEVICE_ST_SUBJ_PSMODE, NULL, ERR_NONE, dataRead); } int ctx::device_status_psmode::subscribe() @@ -78,9 +78,9 @@ int ctx::device_status_psmode::read() int ret = vconf_get_int(VCONFKEY_SETAPPL_PSMODE, &mode); IF_FAIL_RETURN(ret == VCONF_OK, ERR_OPERATION_FAILED); - ctx::Json data_read; - data_read.set(NULL, DEVICE_ST_IS_ENABLED, mode == 0 ? DEVICE_ST_FALSE : DEVICE_ST_TRUE); + ctx::Json dataRead; + dataRead.set(NULL, DEVICE_ST_IS_ENABLED, mode == 0 ? DEVICE_ST_FALSE : DEVICE_ST_TRUE); - ctx::context_manager::reply_to_read(DEVICE_ST_SUBJ_PSMODE, NULL, ERR_NONE, data_read); + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_PSMODE, NULL, ERR_NONE, dataRead); return ERR_NONE; } diff --git a/src/device/system/psmode.h b/src/device/system/psmode.h index 2cc1660..1d4e4f3 100644 --- a/src/device/system/psmode.h +++ b/src/device/system/psmode.h @@ -18,7 +18,7 @@ #define _DEVICE_STATUS_POWER_SAVING_MODE_H_ #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/system/runtime-info/base_rtinfo.h b/src/device/system/runtime-info/base_rtinfo.h index 29480c5..faaaa6a 100644 --- a/src/device/system/runtime-info/base_rtinfo.h +++ b/src/device/system/runtime-info/base_rtinfo.h @@ -18,7 +18,7 @@ #define __CONTEXT_DEVICE_STATUS_RUNTIME_INFO_H__ #include -#include "../../provider_base.h" +#include "../../device_provider_base.h" namespace ctx { diff --git a/src/device/system/runtime-info/charger.cpp b/src/device/system/runtime-info/charger.cpp index ae16d8c..d4cec25 100644 --- a/src/device/system/runtime-info/charger.cpp +++ b/src/device/system/runtime-info/charger.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "../system_types.h" #include "charger.h" @@ -36,7 +36,7 @@ bool ctx::device_status_charger::is_supported() void ctx::device_status_charger::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_CHARGER, OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_CHARGER, OPS_SUBSCRIBE | OPS_READ, "{" TRIG_BOOL_ITEM_DEF("IsConnected") "}", NULL); } @@ -47,22 +47,22 @@ void ctx::device_status_charger::handle_update() int ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_CHARGER_CONNECTED, &charger_status); IF_FAIL_VOID_TAG(ret == RUNTIME_INFO_ERROR_NONE, _E, "Getting runtime info failed"); - ctx::Json data_read; - data_read.set(NULL, DEVICE_ST_IS_CONNECTED, charger_status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + ctx::Json dataRead; + dataRead.set(NULL, DEVICE_ST_IS_CONNECTED, charger_status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); - context_manager::publish(DEVICE_ST_SUBJ_CHARGER, NULL, ERR_NONE, data_read); + context_manager::publish(DEVICE_ST_SUBJ_CHARGER, NULL, ERR_NONE, dataRead); } int ctx::device_status_charger::read() { bool charger_status = false; - ctx::Json data_read; + ctx::Json dataRead; int ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_CHARGER_CONNECTED, &charger_status); IF_FAIL_RETURN_TAG(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Getting runtime info failed"); - data_read.set(NULL, DEVICE_ST_IS_CONNECTED, charger_status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + dataRead.set(NULL, DEVICE_ST_IS_CONNECTED, charger_status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); - ctx::context_manager::reply_to_read(DEVICE_ST_SUBJ_CHARGER, NULL, ERR_NONE, data_read); + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_CHARGER, NULL, ERR_NONE, dataRead); return ERR_NONE; } diff --git a/src/device/system/runtime-info/gps.cpp b/src/device/system/runtime-info/gps.cpp index 80aa16c..9624d38 100644 --- a/src/device/system/runtime-info/gps.cpp +++ b/src/device/system/runtime-info/gps.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "../system_types.h" #include "gps.h" @@ -54,7 +54,7 @@ bool ctx::device_status_gps::is_supported() void ctx::device_status_gps::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_GPS, OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_GPS, OPS_SUBSCRIBE | OPS_READ, "{" "\"State\":{\"type\":\"string\",\"values\":[\"Disabled\",\"Searching\",\"Connected\"]}" "}", @@ -67,20 +67,20 @@ void ctx::device_status_gps::handle_update() int ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_GPS_STATUS, &gps_status); IF_FAIL_VOID_TAG(ret == RUNTIME_INFO_ERROR_NONE, _E, "Getting runtime info failed"); - ctx::Json data_read; + ctx::Json dataRead; const char* state_str = get_state_string(gps_status); IF_FAIL_VOID(state_str); - data_read.set(NULL, DEVICE_ST_STATE, state_str); + dataRead.set(NULL, DEVICE_ST_STATE, state_str); - context_manager::publish(DEVICE_ST_SUBJ_GPS, NULL, ERR_NONE, data_read); + context_manager::publish(DEVICE_ST_SUBJ_GPS, NULL, ERR_NONE, dataRead); } int ctx::device_status_gps::read() { int gps_status; - ctx::Json data_read; + ctx::Json dataRead; int ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_GPS_STATUS, &gps_status); IF_FAIL_RETURN_TAG(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Getting runtime info failed"); @@ -88,8 +88,8 @@ int ctx::device_status_gps::read() const char* state_str = get_state_string(gps_status); IF_FAIL_RETURN(state_str, ERR_OPERATION_FAILED); - data_read.set(NULL, DEVICE_ST_STATE, state_str); + dataRead.set(NULL, DEVICE_ST_STATE, state_str); - ctx::context_manager::reply_to_read(DEVICE_ST_SUBJ_GPS, NULL, ERR_NONE, data_read); + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_GPS, NULL, ERR_NONE, dataRead); return ERR_NONE; } diff --git a/src/device/system/runtime-info/usb.cpp b/src/device/system/runtime-info/usb.cpp index 0ab4d0d..2b7ddbc 100644 --- a/src/device/system/runtime-info/usb.cpp +++ b/src/device/system/runtime-info/usb.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include "../system_types.h" #include "usb.h" @@ -36,7 +36,7 @@ bool ctx::device_status_usb::is_supported() void ctx::device_status_usb::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_USB, OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_USB, OPS_SUBSCRIBE | OPS_READ, "{" TRIG_BOOL_ITEM_DEF("IsConnected") "}", NULL); } @@ -47,22 +47,22 @@ void ctx::device_status_usb::handle_update() int ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_USB_CONNECTED, &status); IF_FAIL_VOID_TAG(ret == RUNTIME_INFO_ERROR_NONE, _E, "Getting runtime info failed"); - ctx::Json data_read; - data_read.set(NULL, DEVICE_ST_IS_CONNECTED, status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + ctx::Json dataRead; + dataRead.set(NULL, DEVICE_ST_IS_CONNECTED, status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); - context_manager::publish(DEVICE_ST_SUBJ_USB, NULL, ERR_NONE, data_read); + context_manager::publish(DEVICE_ST_SUBJ_USB, NULL, ERR_NONE, dataRead); } int ctx::device_status_usb::read() { bool status = false; - ctx::Json data_read; + ctx::Json dataRead; int ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_USB_CONNECTED, &status); IF_FAIL_RETURN_TAG(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Getting runtime info failed"); - data_read.set(NULL, DEVICE_ST_IS_CONNECTED, status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + dataRead.set(NULL, DEVICE_ST_IS_CONNECTED, status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); - ctx::context_manager::reply_to_read(DEVICE_ST_SUBJ_USB, NULL, ERR_NONE, data_read); + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_USB, NULL, ERR_NONE, dataRead); return ERR_NONE; } diff --git a/src/device/system/time.cpp b/src/device/system/time.cpp index 7f5515a..6cd5ea0 100644 --- a/src/device/system/time.cpp +++ b/src/device/system/time.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include #include "system_types.h" #include "time.h" @@ -36,7 +36,7 @@ bool ctx::device_status_time::is_supported() void ctx::device_status_time::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_TIME, OPS_READ, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_TIME, OPS_READ, "{" "\"TimeOfDay\":{\"type\":\"integer\",\"min\":0,\"max\":1439}," "\"DayOfWeek\":{\"type\":\"string\",\"values\":[\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\",\"Weekday\",\"Weekend\"]}," @@ -68,14 +68,14 @@ int ctx::device_status_time::read() int minute_of_day = timeinfo.tm_hour * 60 + timeinfo.tm_min; std::string day_of_week = ctx::TimerManager::dowToStr(0x01 << timeinfo.tm_wday); - ctx::Json data_read; - data_read.set(NULL, DEVICE_ST_DAY_OF_MONTH, day_of_month); - data_read.set(NULL, DEVICE_ST_DAY_OF_WEEK, day_of_week); - data_read.set(NULL, DEVICE_ST_TIME_OF_DAY, minute_of_day); + ctx::Json dataRead; + dataRead.set(NULL, DEVICE_ST_DAY_OF_MONTH, day_of_month); + dataRead.set(NULL, DEVICE_ST_DAY_OF_WEEK, day_of_week); + dataRead.set(NULL, DEVICE_ST_TIME_OF_DAY, minute_of_day); _I("Time: %02d:%02d, Day of Week: %s, Day of Month: %d", timeinfo.tm_hour, timeinfo.tm_min, day_of_week.c_str(), day_of_month); - ctx::context_manager::reply_to_read(DEVICE_ST_SUBJ_TIME, NULL, ERR_NONE, data_read); + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_TIME, NULL, ERR_NONE, dataRead); return ERR_NONE; } diff --git a/src/device/system/time.h b/src/device/system/time.h index 6775d7a..7d44bec 100644 --- a/src/device/system/time.h +++ b/src/device/system/time.h @@ -17,7 +17,7 @@ #ifndef _DEVICE_STATUS_TIME_H_ #define _DEVICE_STATUS_TIME_H_ -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/device/system/wifi.cpp b/src/device/system/wifi.cpp index a40c179..4d237df 100644 --- a/src/device/system/wifi.cpp +++ b/src/device/system/wifi.cpp @@ -15,7 +15,7 @@ */ #include -#include +#include #include "system_types.h" #include "wifi.h" @@ -39,7 +39,7 @@ ctx::device_status_wifi::~device_status_wifi() { } -ctx::context_provider_iface *ctx::device_status_wifi::create(void *data) +ctx::ContextProviderBase *ctx::device_status_wifi::create(void *data) { CREATE_INSTANCE(device_status_wifi); } @@ -62,7 +62,7 @@ bool ctx::device_status_wifi::is_supported() void ctx::device_status_wifi::submit_trigger_item() { - context_manager::register_trigger_item(DEVICE_ST_SUBJ_WIFI, OPS_SUBSCRIBE | OPS_READ, + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_WIFI, OPS_SUBSCRIBE | OPS_READ, "{" "\"State\":{\"type\":\"string\",\"values\":[\"Disabled\",\"Unconnected\",\"Connected\"]}," "\"BSSID\":{\"type\":\"string\"}" @@ -162,10 +162,10 @@ int ctx::device_status_wifi::read() { IF_FAIL_RETURN(get_current_state(), ERR_OPERATION_FAILED); - ctx::Json data_read; + ctx::Json dataRead; - if (get_response_packet(data_read)) { - ctx::context_manager::reply_to_read(DEVICE_ST_SUBJ_WIFI, NULL, ERR_NONE, data_read); + if (get_response_packet(dataRead)) { + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_WIFI, NULL, ERR_NONE, dataRead); return ERR_NONE; } diff --git a/src/device/system/wifi.h b/src/device/system/wifi.h index 6bd81c1..3ed52d5 100644 --- a/src/device/system/wifi.h +++ b/src/device/system/wifi.h @@ -19,7 +19,7 @@ #include #include -#include "../provider_base.h" +#include "../device_provider_base.h" namespace ctx { diff --git a/src/place/geofence/myplace_handle.cpp b/src/place/geofence/myplace_handle.cpp index 8ea7684..d7b8fcc 100644 --- a/src/place/geofence/myplace_handle.cpp +++ b/src/place/geofence/myplace_handle.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include "place_geofence_types.h" #include "myplace_handle.h" diff --git a/src/place/geofence/place_geofence.cpp b/src/place/geofence/place_geofence.cpp index c1525a1..5bcfb7f 100644 --- a/src/place/geofence/place_geofence.cpp +++ b/src/place/geofence/place_geofence.cpp @@ -18,7 +18,7 @@ #include #include -#include +#include #include "place_geofence.h" ctx::place_geofence_provider *ctx::place_geofence_provider::__instance = NULL; @@ -36,7 +36,7 @@ ctx::place_geofence_provider::~place_geofence_provider() __handle_map.clear(); } -ctx::context_provider_iface *ctx::place_geofence_provider::create(void *data) +ctx::ContextProviderBase *ctx::place_geofence_provider::create(void *data) { IF_FAIL_RETURN(!__instance, __instance); __instance = new(std::nothrow) place_geofence_provider(); @@ -63,7 +63,7 @@ bool ctx::place_geofence_provider::is_supported() void ctx::place_geofence_provider::submit_trigger_item() { - context_manager::register_trigger_item(PLACE_SUBJ_GEOFENCE, OPS_SUBSCRIBE, + context_manager::registerTriggerItem(PLACE_SUBJ_GEOFENCE, OPS_SUBSCRIBE, "{" "\"Event\":{\"type\":\"string\",\"values\":[\"In\",\"Out\"]}" "}", @@ -79,7 +79,7 @@ void ctx::place_geofence_provider::__destroy_if_unused() } -int ctx::place_geofence_provider::subscribe(const char *subject, ctx::Json option, ctx::Json *request_result) +int ctx::place_geofence_provider::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) { int ret = __subscribe(option); __destroy_if_unused(); @@ -93,13 +93,13 @@ int ctx::place_geofence_provider::unsubscribe(const char *subject, ctx::Json opt return ret; } -int ctx::place_geofence_provider::read(const char *subject, ctx::Json option, ctx::Json *request_result) +int ctx::place_geofence_provider::read(const char *subject, ctx::Json option, ctx::Json *requestResult) { __destroy_if_unused(); return ERR_NOT_SUPPORTED; } -int ctx::place_geofence_provider::write(const char *subject, ctx::Json data, ctx::Json *request_result) +int ctx::place_geofence_provider::write(const char *subject, ctx::Json data, ctx::Json *requestResult) { __destroy_if_unused(); return ERR_NOT_SUPPORTED; diff --git a/src/place/geofence/place_geofence.h b/src/place/geofence/place_geofence.h index 05de007..739610f 100644 --- a/src/place/geofence/place_geofence.h +++ b/src/place/geofence/place_geofence.h @@ -18,25 +18,25 @@ #define __CONTEXT_PLACE_GEOFENCE_H__ #include -#include +#include #include "myplace_handle.h" #include "place_geofence_types.h" namespace ctx { - class place_geofence_provider : public context_provider_iface { + class place_geofence_provider : public ContextProviderBase { typedef std::map handle_map_t; public: - static context_provider_iface *create(void *data); + static ContextProviderBase *create(void *data); static void destroy(void *data); static bool is_supported(); static void submit_trigger_item(); - int subscribe(const char *subject, ctx::Json option, ctx::Json *request_result); + int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); - int read(const char *subject, ctx::Json option, ctx::Json *request_result); - int write(const char *subject, ctx::Json data, ctx::Json *request_result); + int read(const char *subject, ctx::Json option, ctx::Json *requestResult); + int write(const char *subject, ctx::Json data, ctx::Json *requestResult); private: static place_geofence_provider *__instance; diff --git a/src/place/place_context_provider.cpp b/src/place/place_context_provider.cpp index 934f780..6bcf1c3 100644 --- a/src/place/place_context_provider.cpp +++ b/src/place/place_context_provider.cpp @@ -15,8 +15,8 @@ */ #include -#include -#include +#include +#include #include #ifdef _MOBILE_ @@ -27,24 +27,24 @@ #endif /* _MOBILE_ */ template -void register_provider(const char *subject, const char *privilege) +void registerProvider(const char *subject, const char *privilege) { if (!provider::is_supported()) return; - ctx::context_provider_info provider_info(provider::create, provider::destroy, NULL, privilege); - ctx::context_manager::register_provider(subject, provider_info); + ctx::ContextProviderInfo providerInfo(provider::create, provider::destroy, NULL, privilege); + ctx::context_manager::registerProvider(subject, providerInfo); } EXTAPI bool ctx::init_place_context_provider() { #ifdef _MOBILE_ - register_provider(PLACE_SUBJ_GEOFENCE, PLACE_PRIV_GEOFENCE); + registerProvider(PLACE_SUBJ_GEOFENCE, PLACE_PRIV_GEOFENCE); place_geofence_provider::submit_trigger_item(); #ifndef _DISABLE_RECOG_ENGINE_ place_recognition_provider::create(NULL); - register_provider(PLACE_SUBJ_RECOGNITION, PLACE_PRIV_RECOGNITION); + registerProvider(PLACE_SUBJ_RECOGNITION, PLACE_PRIV_RECOGNITION); #endif /* _DISABLE_RECOG_ENGINE_ */ #endif /* _MOBILE_ */ diff --git a/src/place/recognition/place_recognition.cpp b/src/place/recognition/place_recognition.cpp index 9cdd6f6..0b1b790 100644 --- a/src/place/recognition/place_recognition.cpp +++ b/src/place/recognition/place_recognition.cpp @@ -15,13 +15,13 @@ */ #include -#include +#include #include "place_recognition.h" #include "user_places/user_places.h" ctx::place_recognition_provider *ctx::place_recognition_provider::__instance = NULL; -ctx::context_provider_iface *ctx::place_recognition_provider::create(void *data) +ctx::ContextProviderBase *ctx::place_recognition_provider::create(void *data) { IF_FAIL_RETURN(!__instance, __instance); __instance = new(std::nothrow) place_recognition_provider(); @@ -38,7 +38,7 @@ void ctx::place_recognition_provider::destroy(void *data) _I(BLUE("Destroyed")); } -int ctx::place_recognition_provider::subscribe(const char *subject, ctx::Json option, ctx::Json* request_result) +int ctx::place_recognition_provider::subscribe(const char *subject, ctx::Json option, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } @@ -48,25 +48,25 @@ int ctx::place_recognition_provider::unsubscribe(const char *subject, ctx::Json return ERR_NOT_SUPPORTED; } -int ctx::place_recognition_provider::read(const char *subject, ctx::Json option, ctx::Json* request_result) +int ctx::place_recognition_provider::read(const char *subject, ctx::Json option, ctx::Json* requestResult) { _I(BLUE("Read")); _J("Option", option); std::vector> places = engine.get_places(); - Json data_read = UserPlaces::compose_json(places); + Json dataRead = UserPlaces::compose_json(places); // The below function needs to be called once. // It does not need to be called within this read() function. // In can be called later, in another scope. // Please just be sure that, the 2nd input parameter "option" should be the same to the // "option" parameter received via ctx::place_recognition_provider::read(). - ctx::context_manager::reply_to_read(PLACE_SUBJ_RECOGNITION, option, ERR_NONE, data_read); + ctx::context_manager::replyToRead(PLACE_SUBJ_RECOGNITION, option, ERR_NONE, dataRead); return ERR_NONE; } -int ctx::place_recognition_provider::write(const char *subject, ctx::Json data, ctx::Json* request_result) +int ctx::place_recognition_provider::write(const char *subject, ctx::Json data, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } diff --git a/src/place/recognition/place_recognition.h b/src/place/recognition/place_recognition.h index 8f25424..40a93ec 100644 --- a/src/place/recognition/place_recognition.h +++ b/src/place/recognition/place_recognition.h @@ -17,23 +17,23 @@ #ifndef __CONTEXT_PLACE_RECOGNITION_H__ #define __CONTEXT_PLACE_RECOGNITION_H__ -#include +#include #include "place_recognition_types.h" #include "user_places/user_places.h" namespace ctx { - class place_recognition_provider : public context_provider_iface { + class place_recognition_provider : public ContextProviderBase { public: - static context_provider_iface *create(void *data); + static ContextProviderBase *create(void *data); static void destroy(void *data); static bool is_supported(); - int subscribe(const char *subject, ctx::Json option, ctx::Json *request_result); + int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); - int read(const char *subject, ctx::Json option, ctx::Json *request_result); - int write(const char *subject, ctx::Json data, ctx::Json *request_result); + int read(const char *subject, ctx::Json option, ctx::Json *requestResult); + int write(const char *subject, ctx::Json data, ctx::Json *requestResult); private: static place_recognition_provider *__instance; diff --git a/src/statistics/app/app_stats_provider.cpp b/src/statistics/app/app_stats_provider.cpp index cdb53f4..d924034 100644 --- a/src/statistics/app/app_stats_provider.cpp +++ b/src/statistics/app/app_stats_provider.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include "app_stats_provider.h" #include "db_handle.h" @@ -41,7 +41,7 @@ ctx::app_statistics_provider::~app_statistics_provider() launch_mon = NULL; } -ctx::context_provider_iface *ctx::app_statistics_provider::create(void *data) +ctx::ContextProviderBase *ctx::app_statistics_provider::create(void *data) { IF_FAIL_RETURN(!__instance, __instance); @@ -72,7 +72,7 @@ bool ctx::app_statistics_provider::is_supported(const char* subject) void ctx::app_statistics_provider::submit_trigger_item() { - context_manager::register_trigger_item(APP_SUBJ_FREQUENCY, OPS_READ, + context_manager::registerTriggerItem(APP_SUBJ_FREQUENCY, OPS_READ, "{" TRIG_DEF_RANK "," TRIG_DEF_TOTAL_COUNT "}", "{" "\"AppId\":{\"type\":\"string\"}," @@ -98,7 +98,7 @@ CATCH: return false; } -int ctx::app_statistics_provider::subscribe(const char* subject, ctx::Json option, ctx::Json* request_result) +int ctx::app_statistics_provider::subscribe(const char* subject, ctx::Json option, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } @@ -108,7 +108,7 @@ int ctx::app_statistics_provider::unsubscribe(const char* subject, ctx::Json opt return ERR_NOT_SUPPORTED; } -int ctx::app_statistics_provider::read(const char* subject, ctx::Json option, ctx::Json* request_result) +int ctx::app_statistics_provider::read(const char* subject, ctx::Json option, ctx::Json* requestResult) { ctx::app_db_handle *handle = new(std::nothrow) ctx::app_db_handle(); IF_FAIL_RETURN_TAG(handle, ERR_OPERATION_FAILED, _E, "Memory allocation failed"); @@ -122,7 +122,7 @@ int ctx::app_statistics_provider::read(const char* subject, ctx::Json option, ct return ERR_NONE; } -int ctx::app_statistics_provider::write(const char* subject, ctx::Json data, ctx::Json* request_result) +int ctx::app_statistics_provider::write(const char* subject, ctx::Json data, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } diff --git a/src/statistics/app/app_stats_provider.h b/src/statistics/app/app_stats_provider.h index 7735fd2..b224d77 100644 --- a/src/statistics/app/app_stats_provider.h +++ b/src/statistics/app/app_stats_provider.h @@ -17,22 +17,22 @@ #ifndef __CONTEXT_APP_STATS_PROVIDER_H__ #define __CONTEXT_APP_STATS_PROVIDER_H__ -#include +#include #include "app_stats_types.h" namespace ctx { - class app_statistics_provider : public context_provider_iface { + class app_statistics_provider : public ContextProviderBase { public: - static context_provider_iface *create(void *data); + static ContextProviderBase *create(void *data); static void destroy(void *data); static bool is_supported(const char *subject); static void submit_trigger_item(); - int subscribe(const char *subject, ctx::Json option, ctx::Json *request_result); + int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); - int read(const char *subject, ctx::Json option, ctx::Json *request_result); - int write(const char *subject, ctx::Json data, ctx::Json *request_result); + int read(const char *subject, ctx::Json option, ctx::Json *requestResult); + int write(const char *subject, ctx::Json data, ctx::Json *requestResult); private: static app_statistics_provider *__instance; diff --git a/src/statistics/app/db_handle.cpp b/src/statistics/app/db_handle.cpp index d293ed4..fdabb05 100644 --- a/src/statistics/app/db_handle.cpp +++ b/src/statistics/app/db_handle.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include "app_stats_types.h" #include "db_handle.h" @@ -214,5 +214,5 @@ void ctx::app_db_handle::reply_trigger_item(int error, ctx::Json &json_result) json_result.get(NULL, STATS_RANK, &val); results.set(NULL, STATS_RANK, val); - context_manager::reply_to_read(req_subject.c_str(), req_filter, error, results); + context_manager::replyToRead(req_subject.c_str(), req_filter, error, results); } diff --git a/src/statistics/media/db_handle.cpp b/src/statistics/media/db_handle.cpp index bc74429..81a1d80 100644 --- a/src/statistics/media/db_handle.cpp +++ b/src/statistics/media/db_handle.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include "../shared/system_info.h" #include "media_stats_types.h" @@ -120,5 +120,5 @@ void ctx::media_db_handle::reply_trigger_item(int error, ctx::Json &json_result) json_result.get(NULL, STATS_TOTAL_COUNT, &val); results.set(NULL, STATS_TOTAL_COUNT, val); - context_manager::reply_to_read(req_subject.c_str(), req_filter, error, results); + context_manager::replyToRead(req_subject.c_str(), req_filter, error, results); } diff --git a/src/statistics/media/media_stats_provider.cpp b/src/statistics/media/media_stats_provider.cpp index e68fe6b..feac914 100644 --- a/src/statistics/media/media_stats_provider.cpp +++ b/src/statistics/media/media_stats_provider.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include "media_stats_provider.h" #include "db_handle.h" #include "media_content_monitor.h" @@ -35,7 +35,7 @@ ctx::media_statistics_provider::~media_statistics_provider() content_mon = NULL; } -ctx::context_provider_iface *ctx::media_statistics_provider::create(void *data) +ctx::ContextProviderBase *ctx::media_statistics_provider::create(void *data) { IF_FAIL_RETURN(!__instance, __instance); @@ -67,11 +67,11 @@ bool ctx::media_statistics_provider::is_supported(const char* subject) void ctx::media_statistics_provider::submit_trigger_item() { - context_manager::register_trigger_item(MEDIA_SUBJ_MUSIC_FREQUENCY, OPS_READ, + context_manager::registerTriggerItem(MEDIA_SUBJ_MUSIC_FREQUENCY, OPS_READ, "{" TRIG_DEF_TOTAL_COUNT "}", "{" TRIG_DEF_TIME_OF_DAY "," TRIG_DEF_DAY_OF_WEEK "}"); - context_manager::register_trigger_item(MEDIA_SUBJ_VIDEO_FREQUENCY, OPS_READ, + context_manager::registerTriggerItem(MEDIA_SUBJ_VIDEO_FREQUENCY, OPS_READ, "{" TRIG_DEF_TOTAL_COUNT "}", "{" TRIG_DEF_TIME_OF_DAY "," TRIG_DEF_DAY_OF_WEEK "}"); } @@ -83,7 +83,7 @@ bool ctx::media_statistics_provider::init() return true; } -int ctx::media_statistics_provider::subscribe(const char* subject, ctx::Json option, ctx::Json* request_result) +int ctx::media_statistics_provider::subscribe(const char* subject, ctx::Json option, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } @@ -93,7 +93,7 @@ int ctx::media_statistics_provider::unsubscribe(const char* subject, ctx::Json o return ERR_NOT_SUPPORTED; } -int ctx::media_statistics_provider::read(const char* subject, ctx::Json option, ctx::Json* request_result) +int ctx::media_statistics_provider::read(const char* subject, ctx::Json option, ctx::Json* requestResult) { media_db_handle *handle = new(std::nothrow) media_db_handle(); IF_FAIL_RETURN_TAG(handle, ERR_OPERATION_FAILED, _E, "Memory allocation failed"); @@ -107,7 +107,7 @@ int ctx::media_statistics_provider::read(const char* subject, ctx::Json option, return ERR_NONE; } -int ctx::media_statistics_provider::write(const char* subject, ctx::Json data, ctx::Json* request_result) +int ctx::media_statistics_provider::write(const char* subject, ctx::Json data, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } diff --git a/src/statistics/media/media_stats_provider.h b/src/statistics/media/media_stats_provider.h index 72bb198..ff695c6 100644 --- a/src/statistics/media/media_stats_provider.h +++ b/src/statistics/media/media_stats_provider.h @@ -17,22 +17,22 @@ #ifndef __CONTEXT_MEDIA_STATS_PROVIDER_H__ #define __CONTEXT_MEDIA_STATS_PROVIDER_H__ -#include +#include #include "media_stats_types.h" namespace ctx { - class media_statistics_provider : public context_provider_iface { + class media_statistics_provider : public ContextProviderBase { public: - static context_provider_iface *create(void *data); + static ContextProviderBase *create(void *data); static void destroy(void *data); static bool is_supported(const char *subject); static void submit_trigger_item(); - int subscribe(const char* subject, ctx::Json option, ctx::Json* request_result); + int subscribe(const char* subject, ctx::Json option, ctx::Json* requestResult); int unsubscribe(const char* subject, ctx::Json option); - int read(const char* subject, ctx::Json option, ctx::Json* request_result); - int write(const char* subject, ctx::Json data, ctx::Json* request_result); + int read(const char* subject, ctx::Json option, ctx::Json* requestResult); + int write(const char* subject, ctx::Json data, ctx::Json* requestResult); private: static media_statistics_provider *__instance; diff --git a/src/statistics/shared/db_handle_base.cpp b/src/statistics/shared/db_handle_base.cpp index f525b3d..159c5ca 100644 --- a/src/statistics/shared/db_handle_base.cpp +++ b/src/statistics/shared/db_handle_base.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include #include "common_types.h" #include "db_handle_base.h" @@ -215,12 +215,12 @@ void ctx::stats_db_handle_base::on_query_result_received(unsigned int query_id, } else { _E("Invalid query result"); Json dummy; - context_manager::reply_to_read(req_subject.c_str(), req_filter, ERR_OPERATION_FAILED, dummy); + context_manager::replyToRead(req_subject.c_str(), req_filter, ERR_OPERATION_FAILED, dummy); } } else { Json results = "{\"" STATS_QUERY_RESULT "\":[]}"; json_vector_to_array(records, results); - context_manager::reply_to_read(req_subject.c_str(), req_filter, error, results); + context_manager::replyToRead(req_subject.c_str(), req_filter, error, results); } delete this; diff --git a/src/statistics/social/db_handle.cpp b/src/statistics/social/db_handle.cpp index a42e625..1199a32 100644 --- a/src/statistics/social/db_handle.cpp +++ b/src/statistics/social/db_handle.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include "social_stats_types.h" #include "db_handle.h" @@ -158,5 +158,5 @@ void ctx::social_db_handle::reply_trigger_item(int error, ctx::Json &json_result json_result.get(NULL, STATS_RANK, &val); results.set(NULL, STATS_RANK, val); - context_manager::reply_to_read(req_subject.c_str(), req_filter, error, results); + context_manager::replyToRead(req_subject.c_str(), req_filter, error, results); } diff --git a/src/statistics/social/social_stats_provider.cpp b/src/statistics/social/social_stats_provider.cpp index 90aa35b..196b11e 100644 --- a/src/statistics/social/social_stats_provider.cpp +++ b/src/statistics/social/social_stats_provider.cpp @@ -16,7 +16,7 @@ #include #include -#include +#include #include "social_stats_provider.h" #include "db_handle.h" #include "log_aggregator.h" @@ -34,7 +34,7 @@ ctx::social_statistics_provider::~social_statistics_provider() delete aggregator; } -ctx::context_provider_iface *ctx::social_statistics_provider::create(void *data) +ctx::ContextProviderBase *ctx::social_statistics_provider::create(void *data) { IF_FAIL_RETURN(!__instance, __instance); @@ -66,7 +66,7 @@ bool ctx::social_statistics_provider::is_supported(const char* subject) void ctx::social_statistics_provider::submit_trigger_item() { - context_manager::register_trigger_item(SOCIAL_SUBJ_FREQUENCY, OPS_READ, + context_manager::registerTriggerItem(SOCIAL_SUBJ_FREQUENCY, OPS_READ, "{" TRIG_DEF_RANK "," TRIG_DEF_TOTAL_COUNT "}", "{" "\"Address\":{\"type\":\"string\"}," @@ -81,7 +81,7 @@ bool ctx::social_statistics_provider::init() return true; } -int ctx::social_statistics_provider::subscribe(const char* subject, ctx::Json option, ctx::Json* request_result) +int ctx::social_statistics_provider::subscribe(const char* subject, ctx::Json option, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } @@ -91,7 +91,7 @@ int ctx::social_statistics_provider::unsubscribe(const char* subject, ctx::Json return ERR_NOT_SUPPORTED; } -int ctx::social_statistics_provider::read(const char* subject, ctx::Json option, ctx::Json* request_result) +int ctx::social_statistics_provider::read(const char* subject, ctx::Json option, ctx::Json* requestResult) { ctx::social_db_handle *handle = new(std::nothrow) ctx::social_db_handle(); IF_FAIL_RETURN_TAG(handle, ERR_OPERATION_FAILED, _E, "Memory allocation failed"); @@ -105,7 +105,7 @@ int ctx::social_statistics_provider::read(const char* subject, ctx::Json option, return ERR_NONE; } -int ctx::social_statistics_provider::write(const char* subject, ctx::Json data, ctx::Json* request_result) +int ctx::social_statistics_provider::write(const char* subject, ctx::Json data, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } diff --git a/src/statistics/social/social_stats_provider.h b/src/statistics/social/social_stats_provider.h index 7ba803d..1666b78 100644 --- a/src/statistics/social/social_stats_provider.h +++ b/src/statistics/social/social_stats_provider.h @@ -17,22 +17,22 @@ #ifndef __CONTEXT_SOCIAL_STATS_PROVIDER_H__ #define __CONTEXT_SOCIAL_STATS_PROVIDER_H__ -#include +#include #include "social_stats_types.h" namespace ctx { - class social_statistics_provider : public context_provider_iface { + class social_statistics_provider : public ContextProviderBase { public: - static context_provider_iface *create(void *data); + static ContextProviderBase *create(void *data); static void destroy(void *data); static bool is_supported(const char *subject); static void submit_trigger_item(); - int subscribe(const char* subject, ctx::Json option, ctx::Json* request_result); + int subscribe(const char* subject, ctx::Json option, ctx::Json* requestResult); int unsubscribe(const char* subject, ctx::Json option); - int read(const char* subject, ctx::Json option, ctx::Json* request_result); - int write(const char* subject, ctx::Json data, ctx::Json* request_result); + int read(const char* subject, ctx::Json option, ctx::Json* requestResult); + int write(const char* subject, ctx::Json data, ctx::Json* requestResult); private: static social_statistics_provider *__instance; diff --git a/src/statistics/statistics_context_provider.cpp b/src/statistics/statistics_context_provider.cpp index 13e9c40..2d305eb 100644 --- a/src/statistics/statistics_context_provider.cpp +++ b/src/statistics/statistics_context_provider.cpp @@ -14,8 +14,8 @@ */ #include -#include -#include +#include +#include #include #include "app/app_stats_provider.h" @@ -34,24 +34,24 @@ #endif template -void register_provider(const char *subject, const char *privilege) +void registerProvider(const char *subject, const char *privilege) { if (!provider::is_supported(subject)) return; - ctx::context_provider_info provider_info(provider::create, provider::destroy, NULL, privilege); - ctx::context_manager::register_provider(subject, provider_info); + ctx::ContextProviderInfo providerInfo(provider::create, provider::destroy, NULL, privilege); + ctx::context_manager::registerProvider(subject, providerInfo); } EXTAPI bool ctx::init_statistics_context_provider() { app_statistics_provider::create(NULL); - register_provider(APP_SUBJ_RECENTLY_USED, APP_HISTORY_PRIV); - register_provider(APP_SUBJ_FREQUENTLY_USED, APP_HISTORY_PRIV); - register_provider(APP_SUBJ_RARELY_USED, APP_HISTORY_PRIV); - register_provider(APP_SUBJ_PEAK_TIME, APP_HISTORY_PRIV); - register_provider(APP_SUBJ_COMMON_SETTING, APP_HISTORY_PRIV); - register_provider(APP_SUBJ_FREQUENCY, APP_HISTORY_PRIV); + registerProvider(APP_SUBJ_RECENTLY_USED, APP_HISTORY_PRIV); + registerProvider(APP_SUBJ_FREQUENTLY_USED, APP_HISTORY_PRIV); + registerProvider(APP_SUBJ_RARELY_USED, APP_HISTORY_PRIV); + registerProvider(APP_SUBJ_PEAK_TIME, APP_HISTORY_PRIV); + registerProvider(APP_SUBJ_COMMON_SETTING, APP_HISTORY_PRIV); + registerProvider(APP_SUBJ_FREQUENCY, APP_HISTORY_PRIV); app_statistics_provider::submit_trigger_item(); #ifndef _DISABLE_PREDICTION_ENGINE_ @@ -60,28 +60,28 @@ EXTAPI bool ctx::init_statistics_context_provider() #ifdef _MOBILE_ media_statistics_provider::create(NULL); - register_provider(MEDIA_SUBJ_PEAK_TIME_FOR_MUSIC, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_PEAK_TIME_FOR_VIDEO, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_COMMON_SETTING_FOR_MUSIC, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_COMMON_SETTING_FOR_VIDEO, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_MUSIC_FREQUENCY, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_VIDEO_FREQUENCY, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_PEAK_TIME_FOR_MUSIC, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_PEAK_TIME_FOR_VIDEO, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_COMMON_SETTING_FOR_MUSIC, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_COMMON_SETTING_FOR_VIDEO, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_MUSIC_FREQUENCY, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_VIDEO_FREQUENCY, MEDIA_HISTORY_PRIV); media_statistics_provider::submit_trigger_item(); social_statistics_provider::create(NULL); - register_provider(SOCIAL_SUBJ_FREQ_ADDRESS, SOCIAL_HISTORY_PRIV); - register_provider(SOCIAL_SUBJ_FREQUENCY, SOCIAL_HISTORY_PRIV); + registerProvider(SOCIAL_SUBJ_FREQ_ADDRESS, SOCIAL_HISTORY_PRIV); + registerProvider(SOCIAL_SUBJ_FREQUENCY, SOCIAL_HISTORY_PRIV); social_statistics_provider::submit_trigger_item(); #endif #ifdef _TV_ media_statistics_provider::create(NULL); - register_provider(MEDIA_SUBJ_PEAK_TIME_FOR_MUSIC, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_PEAK_TIME_FOR_VIDEO, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_COMMON_SETTING_FOR_MUSIC, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_COMMON_SETTING_FOR_VIDEO, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_MUSIC_FREQUENCY, MEDIA_HISTORY_PRIV); - register_provider(MEDIA_SUBJ_VIDEO_FREQUENCY, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_PEAK_TIME_FOR_MUSIC, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_PEAK_TIME_FOR_VIDEO, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_COMMON_SETTING_FOR_MUSIC, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_COMMON_SETTING_FOR_VIDEO, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_MUSIC_FREQUENCY, MEDIA_HISTORY_PRIV); + registerProvider(MEDIA_SUBJ_VIDEO_FREQUENCY, MEDIA_HISTORY_PRIV); media_statistics_provider::submit_trigger_item(); #endif -- 2.7.4 From 644deafe405a7b068c9c9709e22ce50e579b8acc Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Mon, 4 Apr 2016 17:25:29 +0900 Subject: [PATCH 05/16] Build a static library, instead of a shared object The library is only being used by contextd, thus it does not need to be a shared object. Change-Id: I0dd3acd582070b946053f87b54f924288c75b8a9 Signed-off-by: Mu-Woong Lee --- CMakeLists.txt | 5 +++-- packaging/context-provider.spec | 7 ++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ff1cbd9..42e2659 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,8 @@ SET(compile_defs "LOG_TAG=\"CONTEXT\"") INCLUDE_DIRECTORIES( ${CMAKE_CURRENT_SOURCE_DIR}/include ) -ADD_DEFINITIONS(-O2 -Wall -fPIC -fvisibility=hidden -Wl,--as-needed) +ADD_DEFINITIONS(-O2 -Wall -fPIC -fdata-sections -ffunction-sections -fvisibility=hidden) +SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fPIC -Wl,--as-needed -Wl,--gc-section -Wl,--print-gc-section") # Base Dependency SET(dependencies libcontext-shared libcontext-server) @@ -38,7 +39,7 @@ FOREACH(flag ${DEPS_CFLAGS}) SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}") ENDFOREACH(flag) -ADD_LIBRARY(${target} SHARED ${sources}) +ADD_LIBRARY(${target} STATIC ${sources}) TARGET_LINK_LIBRARIES(${target} ${DEPS_LDFLAGS}) SET_TARGET_PROPERTIES(${target} PROPERTIES COMPILE_FLAGS ${EXTRA_CFLAGS}) SET_TARGET_PROPERTIES(${target} PROPERTIES COMPILE_DEFINITIONS "${compile_defs}") diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index cb86c92..3ddb5eb 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -7,6 +7,7 @@ License: Apache-2.0 Source0: %{name}-%{version}.tar.gz %define BUILD_PROFILE %{?profile}%{!?profile:%{?tizen_profile_name}} +%define keepstatic 1 BuildRequires: cmake @@ -64,8 +65,8 @@ MAJORVER=`echo %{version} | awk 'BEGIN {FS="."}{print $1}'` export CFLAGS+=" -Wextra -Wcast-align -Wshadow -Wwrite-strings -Wswitch-default -Wno-unused-parameter" export CXXFLAGS+=" -Wextra -Wcast-align -Wshadow -Wwrite-strings -Wswitch-default -Wno-unused-parameter" -export CFLAGS+=" -Wno-empty-body -fno-omit-frame-pointer -fno-optimize-sibling-calls" -export CXXFLAGS+=" -Wno-empty-body -fno-omit-frame-pointer -fno-optimize-sibling-calls" +export CFLAGS+=" -Wno-empty-body -fomit-frame-pointer -fno-optimize-sibling-calls" +export CXXFLAGS+=" -Wno-empty-body -fomit-frame-pointer -fno-optimize-sibling-calls" export CFLAGS+=" -fno-strict-aliasing -fno-unroll-loops -fsigned-char -fstrict-overflow" export CXXFLAGS+=" -fno-strict-aliasing -fno-unroll-loops -fsigned-char -fstrict-overflow" @@ -100,7 +101,6 @@ cp LICENSE %{buildroot}/usr/share/license/%{name} %files %manifest packaging/%{name}.manifest %defattr(-,root,root,-) -%{_libdir}/*.so* /usr/share/license/%{name} %package devel @@ -115,3 +115,4 @@ Context Provider (Development) %defattr(-,root,root,-) %{_includedir}/context-service/internal/*.h %{_libdir}/pkgconfig/%{name}.pc +%{_libdir}/*.a -- 2.7.4 From 25989911010af46f8f943ed765cffca412ab4afd Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Wed, 6 Apr 2016 11:17:31 +0900 Subject: [PATCH 06/16] Applying Tizen C++ coding style to provider initialization Change-Id: Icb44282ca2adf5309471e11ef93198ed6220a082 Signed-off-by: Somin Kim --- ..._context_provider.h => CustomContextProvider.h} | 26 +++++++++++++--------- ..._context_provider.h => DeviceContextProvider.h} | 12 +++++----- ...e_context_provider.h => PlaceContextProvider.h} | 12 +++++----- ...text_provider.h => StatisticsContextProvider.h} | 12 +++++----- src/custom/custom_context_provider.cpp | 4 ++-- src/device/device_context_provider.cpp | 4 ++-- src/place/place_context_provider.cpp | 4 ++-- src/statistics/statistics_context_provider.cpp | 4 ++-- 8 files changed, 44 insertions(+), 34 deletions(-) rename include/{custom_context_provider.h => CustomContextProvider.h} (56%) rename include/{place_context_provider.h => DeviceContextProvider.h} (75%) rename include/{device_context_provider.h => PlaceContextProvider.h} (76%) rename include/{statistics_context_provider.h => StatisticsContextProvider.h} (74%) diff --git a/include/custom_context_provider.h b/include/CustomContextProvider.h similarity index 56% rename from include/custom_context_provider.h rename to include/CustomContextProvider.h index 918dfa6..c75d63e 100644 --- a/include/custom_context_provider.h +++ b/include/CustomContextProvider.h @@ -14,20 +14,24 @@ * limitations under the License. */ -#ifndef __CONTEXT_CUSTOM_CONTEXT_PROVIDER_H__ -#define __CONTEXT_CUSTOM_CONTEXT_PROVIDER_H__ +#ifndef _CONTEXT_CUSTOM_CONTEXT_PROVIDER_H_ +#define _CONTEXT_CUSTOM_CONTEXT_PROVIDER_H_ namespace ctx { - bool init_custom_context_provider(); + + bool initCustomContextProvider(); namespace custom_context_provider { - int addItem(std::string subject, std::string name, ctx::Json tmpl, const char* owner, bool is_init = false); - int removeItem(std::string subject); - int publishData(std::string subject, ctx::Json fact); - ContextProviderBase* create(void* data); - void destroy(void* data); - } -} + int addItem(std::string subject, std::string name, ctx::Json tmpl, const char* owner, bool isInit = false); + int removeItem(std::string subject); + int publishData(std::string subject, ctx::Json fact); + + ContextProviderBase* create(void* data); + void destroy(void* data); + + } /* namespace custom_context_provider */ + +} /* namespace ctx */ -#endif //__CONTEXT_CUSTOM_CONTEXT_PROVIDER_H__ +#endif /* End of _CONTEXT_CUSTOM_CONTEXT_PROVIDER_H_ */ diff --git a/include/place_context_provider.h b/include/DeviceContextProvider.h similarity index 75% rename from include/place_context_provider.h rename to include/DeviceContextProvider.h index 407838b..1e47323 100644 --- a/include/place_context_provider.h +++ b/include/DeviceContextProvider.h @@ -14,11 +14,13 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_CONTEXT_PROVIDER_H__ -#define __CONTEXT_PLACE_CONTEXT_PROVIDER_H__ +#ifndef _CONTEXT_DEVICE_CONTEXT_PROVIDER_H_ +#define _CONTEXT_DEVICE_CONTEXT_PROVIDER_H_ namespace ctx { - bool init_place_context_provider(); -} -#endif /* __CONTEXT_PLACE_CONTEXT_PROVIDER_H__ */ + bool initDeviceContextProvider(); + +} /* namespace ctx */ + +#endif /* End of _CONTEXT_DEVICE_CONTEXT_PROVIDER_H_ */ diff --git a/include/device_context_provider.h b/include/PlaceContextProvider.h similarity index 76% rename from include/device_context_provider.h rename to include/PlaceContextProvider.h index 09ef1e7..e7585b0 100644 --- a/include/device_context_provider.h +++ b/include/PlaceContextProvider.h @@ -14,11 +14,13 @@ * limitations under the License. */ -#ifndef __CONTEXT_DEVICE_CONTEXT_PROVIDER_H__ -#define __CONTEXT_DEVICE_CONTEXT_PROVIDER_H__ +#ifndef _CONTEXT_PLACE_CONTEXT_PROVIDER_H_ +#define _CONTEXT_PLACE_CONTEXT_PROVIDER_H_ namespace ctx { - bool init_device_context_provider(); -} -#endif //__CONTEXT_DEVICE_CONTEXT_PROVIDER_H__ + bool initPlaceContextProvider(); + +} /* namespace ctx */ + +#endif /* End of _CONTEXT_PLACE_CONTEXT_PROVIDER_H_ */ diff --git a/include/statistics_context_provider.h b/include/StatisticsContextProvider.h similarity index 74% rename from include/statistics_context_provider.h rename to include/StatisticsContextProvider.h index b45c3fd..f356719 100644 --- a/include/statistics_context_provider.h +++ b/include/StatisticsContextProvider.h @@ -14,11 +14,13 @@ * limitations under the License. */ -#ifndef __CONTEXT_STATISTICS_CONTEXT_PROVIDER_H__ -#define __CONTEXT_STATISTICS_CONTEXT_PROVIDER_H__ +#ifndef _CONTEXT_STATISTICS_CONTEXT_PROVIDER_H_ +#define _CONTEXT_STATISTICS_CONTEXT_PROVIDER_H_ namespace ctx { - bool init_statistics_context_provider(); -} -#endif /* __CONTEXT_STATISTICS_CONTEXT_PROVIDER_H__ */ + bool initStatisticsContextProvider(); + +} /* namespace ctx */ + +#endif /* End of _CONTEXT_STATISTICS_CONTEXT_PROVIDER_H_ */ diff --git a/src/custom/custom_context_provider.cpp b/src/custom/custom_context_provider.cpp index 88aca00..5bec97e 100644 --- a/src/custom/custom_context_provider.cpp +++ b/src/custom/custom_context_provider.cpp @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include "custom_base.h" std::map custom_map; @@ -59,7 +59,7 @@ EXTAPI void ctx::custom_context_provider::destroy(void *data) } } -EXTAPI bool ctx::init_custom_context_provider() +EXTAPI bool ctx::initCustomContextProvider() { // Create custom template db std::string q = std::string("CREATE TABLE IF NOT EXISTS context_trigger_custom_template ") diff --git a/src/device/device_context_provider.cpp b/src/device/device_context_provider.cpp index 39fcf7d..1e42e20 100644 --- a/src/device/device_context_provider.cpp +++ b/src/device/device_context_provider.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include "system/system_types.h" #include "social/social_types.h" @@ -75,7 +75,7 @@ void registerProvider(const char *subject, const char *privilege) provider::submit_trigger_item(); } -EXTAPI bool ctx::init_device_context_provider() +EXTAPI bool ctx::initDeviceContextProvider() { registerProvider(DEVICE_ST_SUBJ_ALARM, NULL); registerProvider(DEVICE_ST_SUBJ_TIME, NULL); diff --git a/src/place/place_context_provider.cpp b/src/place/place_context_provider.cpp index 6bcf1c3..c3efaef 100644 --- a/src/place/place_context_provider.cpp +++ b/src/place/place_context_provider.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #ifdef _MOBILE_ #include "geofence/place_geofence.h" @@ -36,7 +36,7 @@ void registerProvider(const char *subject, const char *privilege) ctx::context_manager::registerProvider(subject, providerInfo); } -EXTAPI bool ctx::init_place_context_provider() +EXTAPI bool ctx::initPlaceContextProvider() { #ifdef _MOBILE_ registerProvider(PLACE_SUBJ_GEOFENCE, PLACE_PRIV_GEOFENCE); diff --git a/src/statistics/statistics_context_provider.cpp b/src/statistics/statistics_context_provider.cpp index 2d305eb..1fa29ee 100644 --- a/src/statistics/statistics_context_provider.cpp +++ b/src/statistics/statistics_context_provider.cpp @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include "app/app_stats_provider.h" @@ -43,7 +43,7 @@ void registerProvider(const char *subject, const char *privilege) ctx::context_manager::registerProvider(subject, providerInfo); } -EXTAPI bool ctx::init_statistics_context_provider() +EXTAPI bool ctx::initStatisticsContextProvider() { app_statistics_provider::create(NULL); registerProvider(APP_SUBJ_RECENTLY_USED, APP_HISTORY_PRIV); -- 2.7.4 From ea563a7c8f713d6d8739c2437fe7ba873af3cfd7 Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Tue, 5 Apr 2016 17:55:55 +0900 Subject: [PATCH 07/16] Applying Tizen C++ coding style to device context provider Change-Id: I1d3b75c1192f58facb200dee7f92062b9dbe7ba8 Signed-off-by: Somin Kim --- src/device/CMakeLists.txt | 6 +- src/device/DeviceContextProvider.cpp | 141 ++++++++++ ...ce_provider_base.cpp => DeviceProviderBase.cpp} | 42 +-- ...device_provider_base.h => DeviceProviderBase.h} | 22 +- src/device/activity/{activity.h => Activity.h} | 38 +-- .../{activity_base.cpp => ActivityBase.cpp} | 58 ++-- .../activity/{activity_base.h => ActivityBase.h} | 24 +- .../activity/{activity_types.h => ActivityTypes.h} | 6 +- src/device/device_context_provider.cpp | 141 ---------- src/device/social/{call.cpp => Call.cpp} | 155 ++++++----- src/device/social/Call.h | 58 ++++ src/device/social/{contacts.cpp => Contacts.cpp} | 70 ++--- src/device/social/{contacts.h => Contacts.h} | 28 +- src/device/social/{email.cpp => Email.cpp} | 44 +-- src/device/social/{email.h => Email.h} | 16 +- src/device/social/{message.cpp => Message.cpp} | 52 ++-- src/device/social/{message.h => Message.h} | 26 +- .../social/{social_types.h => SocialTypes.h} | 6 +- src/device/social/call.h | 58 ---- src/device/system/Alarm.cpp | 302 +++++++++++++++++++++ src/device/system/Alarm.h | 87 ++++++ src/device/system/{battery.cpp => Battery.cpp} | 78 +++--- src/device/system/{battery.h => Battery.h} | 26 +- src/device/system/Headphone.cpp | 238 ++++++++++++++++ src/device/system/Headphone.h | 65 +++++ src/device/system/{psmode.cpp => Psmode.cpp} | 32 +-- src/device/system/{psmode.h => Psmode.h} | 24 +- .../system/{system_types.h => SystemTypes.h} | 6 +- src/device/system/{time.cpp => Time.cpp} | 38 +-- src/device/system/{time.h => Time.h} | 20 +- src/device/system/Wifi.cpp | 266 ++++++++++++++++++ src/device/system/Wifi.h | 66 +++++ src/device/system/alarm.cpp | 302 --------------------- src/device/system/alarm.h | 88 ------ src/device/system/headphone.cpp | 238 ---------------- src/device/system/headphone.h | 65 ----- .../charger.cpp => runtime_info/Charger.cpp} | 32 +-- .../charger.h => runtime_info/Charger.h} | 24 +- .../{runtime-info/gps.cpp => runtime_info/Gps.cpp} | 48 ++-- .../{runtime-info/usb.h => runtime_info/Gps.h} | 24 +- .../RuntimeInfoBase.cpp} | 26 +- .../RuntimeInfoBase.h} | 22 +- .../{runtime-info/usb.cpp => runtime_info/Usb.cpp} | 22 +- .../{runtime-info/gps.h => runtime_info/Usb.h} | 24 +- src/device/system/wifi.cpp | 267 ------------------ src/device/system/wifi.h | 66 ----- 46 files changed, 1745 insertions(+), 1742 deletions(-) create mode 100644 src/device/DeviceContextProvider.cpp rename src/device/{device_provider_base.cpp => DeviceProviderBase.cpp} (55%) rename src/device/{device_provider_base.h => DeviceProviderBase.h} (83%) rename src/device/activity/{activity.h => Activity.h} (50%) rename src/device/activity/{activity_base.cpp => ActivityBase.cpp} (51%) rename src/device/activity/{activity_base.h => ActivityBase.h} (54%) rename src/device/activity/{activity_types.h => ActivityTypes.h} (89%) delete mode 100644 src/device/device_context_provider.cpp rename src/device/social/{call.cpp => Call.cpp} (64%) create mode 100644 src/device/social/Call.h rename src/device/social/{contacts.cpp => Contacts.cpp} (51%) rename src/device/social/{contacts.h => Contacts.h} (61%) rename src/device/social/{email.cpp => Email.cpp} (56%) rename src/device/social/{email.h => Email.h} (75%) rename src/device/social/{message.cpp => Message.cpp} (64%) rename src/device/social/{message.h => Message.h} (62%) rename src/device/social/{social_types.h => SocialTypes.h} (93%) delete mode 100644 src/device/social/call.h create mode 100644 src/device/system/Alarm.cpp create mode 100644 src/device/system/Alarm.h rename src/device/system/{battery.cpp => Battery.cpp} (54%) rename src/device/system/{battery.h => Battery.h} (56%) create mode 100644 src/device/system/Headphone.cpp create mode 100644 src/device/system/Headphone.h rename src/device/system/{psmode.cpp => Psmode.cpp} (66%) rename src/device/system/{psmode.h => Psmode.h} (58%) rename src/device/system/{system_types.h => SystemTypes.h} (94%) rename src/device/system/{time.cpp => Time.cpp} (57%) rename src/device/system/{time.h => Time.h} (66%) create mode 100644 src/device/system/Wifi.cpp create mode 100644 src/device/system/Wifi.h delete mode 100644 src/device/system/alarm.cpp delete mode 100644 src/device/system/alarm.h delete mode 100644 src/device/system/headphone.cpp delete mode 100644 src/device/system/headphone.h rename src/device/system/{runtime-info/charger.cpp => runtime_info/Charger.cpp} (64%) rename src/device/system/{runtime-info/charger.h => runtime_info/Charger.h} (61%) rename src/device/system/{runtime-info/gps.cpp => runtime_info/Gps.cpp} (63%) rename src/device/system/{runtime-info/usb.h => runtime_info/Gps.h} (63%) rename src/device/system/{runtime-info/base_rtinfo.cpp => runtime_info/RuntimeInfoBase.cpp} (53%) rename src/device/system/{runtime-info/base_rtinfo.h => runtime_info/RuntimeInfoBase.h} (59%) rename src/device/system/{runtime-info/usb.cpp => runtime_info/Usb.cpp} (76%) rename src/device/system/{runtime-info/gps.h => runtime_info/Usb.h} (63%) delete mode 100644 src/device/system/wifi.cpp delete mode 100644 src/device/system/wifi.h diff --git a/src/device/CMakeLists.txt b/src/device/CMakeLists.txt index 22f35bc..20276e3 100644 --- a/src/device/CMakeLists.txt +++ b/src/device/CMakeLists.txt @@ -2,7 +2,7 @@ CMAKE_MINIMUM_REQUIRED(VERSION 2.6) # prvd_cdef, prvd_deps, and prvd_srcs need to be set properly # Common Profile -FILE(GLOB prvd_srcs ./*.cpp system/alarm.cpp system/time.cpp) +FILE(GLOB prvd_srcs ./*.cpp system/Alarm.cpp system/Time.cpp) SET(prvd_deps vconf capi-system-info capi-system-device capi-system-runtime-info) # Mobile Profile @@ -20,11 +20,11 @@ IF("${PROFILE}" STREQUAL "wearable") SET(prvd_deps ${prvd_deps} capi-telephony tapi msg-service motion) FILE(GLOB_RECURSE prvd_srcs ${prvd_srcs} activity/*.cpp) FILE(GLOB_RECURSE prvd_srcs ${prvd_srcs} system/*.cpp) - FILE(GLOB prvd_srcs ${prvd_srcs} social/call.cpp social/message.cpp) + FILE(GLOB prvd_srcs ${prvd_srcs} social/Call.cpp social/Message.cpp) ENDIF("${PROFILE}" STREQUAL "wearable") # TV Profile IF("${PROFILE}" STREQUAL "tv") SET(prvd_deps ${prvd_deps} capi-network-bluetooth capi-network-wifi) - FILE(GLOB prvd_srcs ${prvd_srcs} system/headphone.cpp system/wifi.cpp) + FILE(GLOB prvd_srcs ${prvd_srcs} system/Headphone.cpp system/Wifi.cpp) ENDIF("${PROFILE}" STREQUAL "tv") diff --git a/src/device/DeviceContextProvider.cpp b/src/device/DeviceContextProvider.cpp new file mode 100644 index 0000000..b4c657e --- /dev/null +++ b/src/device/DeviceContextProvider.cpp @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "system/SystemTypes.h" +#include "social/SocialTypes.h" +#include "activity/ActivityTypes.h" + +#include "system/Alarm.h" +#include "system/Time.h" + +#ifdef _MOBILE_ +#include "system/runtime_info/Charger.h" +#include "system/runtime_info/Gps.h" +#include "system/runtime_info/Usb.h" +#include "system/Wifi.h" +#include "system/Headphone.h" +#include "system/Battery.h" +#include "system/Psmode.h" +#include "social/Call.h" +#include "social/Email.h" +#include "social/Message.h" +#include "social/Contacts.h" +#include "activity/Activity.h" +#endif + +#ifdef _WEARABLE_ +#include "system/runtime_info/Charger.h" +#include "system/runtime_info/Gps.h" +#include "system/runtime_info/Usb.h" +#include "system/Wifi.h" +#include "system/Headphone.h" +#include "system/Battery.h" +#include "system/Psmode.h" +#include "social/Call.h" +#include "social/Message.h" +#include "activity/Activity.h" +#endif + +#ifdef _TV_ +#include "system/Wifi.h" +#include "system/Headphone.h" +#endif + +#define PRIV_NETWORK "network.get" +#define PRIV_TELEPHONY "telephony" +#define PRIV_MESSAGE "message.read" +#define PRIV_CONTACT "contact.read" + +template +void registerProvider(const char *subject, const char *privilege) +{ + if (!Provider::isSupported()) + return; + + ctx::ContextProviderInfo providerInfo(Provider::create, Provider::destroy, NULL, privilege); + ctx::context_manager::registerProvider(subject, providerInfo); + Provider::submitTriggerItem(); +} + +EXTAPI bool ctx::initDeviceContextProvider() +{ + registerProvider(DEVICE_ST_SUBJ_ALARM, NULL); + registerProvider(DEVICE_ST_SUBJ_TIME, NULL); + +#ifdef _MOBILE_ + registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); + registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); + + registerProvider(DEVICE_ST_SUBJ_CHARGER, NULL); + registerProvider(DEVICE_ST_SUBJ_GPS, NULL); + registerProvider(DEVICE_ST_SUBJ_USB, NULL); + registerProvider(DEVICE_ST_SUBJ_BATTERY, NULL); + registerProvider(DEVICE_ST_SUBJ_PSMODE, NULL); + + registerProvider(SOCIAL_ST_SUBJ_CALL, PRIV_TELEPHONY); + registerProvider(SOCIAL_ST_SUBJ_EMAIL, NULL); + registerProvider(SOCIAL_ST_SUBJ_MESSAGE, PRIV_MESSAGE); + registerProvider(SOCIAL_ST_SUBJ_CONTACTS, PRIV_CONTACT); + + registerProvider(USER_ACT_SUBJ_STATIONARY, NULL); + registerProvider(USER_ACT_SUBJ_WALKING, NULL); + registerProvider(USER_ACT_SUBJ_RUNNING, NULL); + registerProvider(USER_ACT_SUBJ_IN_VEHICLE, NULL); + + /* Create context providers, which need to be initiated before being subscribed */ + if (DeviceStatusWifi::isSupported()) + DeviceStatusWifi::create(NULL); +#endif + +#ifdef _WEARABLE_ + registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); + registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); + + registerProvider(DEVICE_ST_SUBJ_CHARGER, NULL); + registerProvider(DEVICE_ST_SUBJ_GPS, NULL); + registerProvider(DEVICE_ST_SUBJ_USB, NULL); + registerProvider(DEVICE_ST_SUBJ_BATTERY, NULL); + registerProvider(DEVICE_ST_SUBJ_PSMODE, NULL); + + registerProvider(SOCIAL_ST_SUBJ_CALL, PRIV_TELEPHONY); + registerProvider(SOCIAL_ST_SUBJ_MESSAGE, PRIV_MESSAGE); + + registerProvider(USER_ACT_SUBJ_STATIONARY, NULL); + registerProvider(USER_ACT_SUBJ_WALKING, NULL); + registerProvider(USER_ACT_SUBJ_RUNNING, NULL); + registerProvider(USER_ACT_SUBJ_IN_VEHICLE, NULL); + + /* Create context providers, which need to be initiated before being subscribed */ + if (DeviceStatusWifi::isSupported()) + DeviceStatusWifi::create(NULL); +#endif + +#ifdef _TV_ + registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); + registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); + + /* Create context providers, which need to be initiated before being subscribed */ + if (DeviceStatusWifi::isSupported()) + DeviceStatusWifi::create(NULL); +#endif + + return true; +} diff --git a/src/device/device_provider_base.cpp b/src/device/DeviceProviderBase.cpp similarity index 55% rename from src/device/device_provider_base.cpp rename to src/device/DeviceProviderBase.cpp index 95f3988..b3aab6e 100644 --- a/src/device/device_provider_base.cpp +++ b/src/device/DeviceProviderBase.cpp @@ -15,79 +15,79 @@ */ #include -#include "device_provider_base.h" +#include "DeviceProviderBase.h" -ctx::device_provider_base::device_provider_base() - : being_subscribed(false) +ctx::DeviceProviderBase::DeviceProviderBase() + : __beingSubscribed(false) { } -int ctx::device_provider_base::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) +int ctx::DeviceProviderBase::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) { - IF_FAIL_RETURN(!being_subscribed, ERR_NONE); + IF_FAIL_RETURN(!__beingSubscribed, ERR_NONE); int ret = subscribe(); if (ret == ERR_NONE) - being_subscribed = true; + __beingSubscribed = true; else - destroy_self(); + destroySelf(); return ret; } -int ctx::device_provider_base::unsubscribe(const char *subject, ctx::Json option) +int ctx::DeviceProviderBase::unsubscribe(const char *subject, ctx::Json option) { int ret = ERR_NONE; - if (being_subscribed) + if (__beingSubscribed) ret = unsubscribe(); - destroy_self(); + destroySelf(); return ret; } -int ctx::device_provider_base::read(const char *subject, ctx::Json option, ctx::Json *requestResult) +int ctx::DeviceProviderBase::read(const char *subject, ctx::Json option, ctx::Json *requestResult) { int ret = read(); - if (!being_subscribed) - destroy_self(); + if (!__beingSubscribed) + destroySelf(); return ret; } -int ctx::device_provider_base::write(const char *subject, ctx::Json data, ctx::Json *requestResult) +int ctx::DeviceProviderBase::write(const char *subject, ctx::Json data, ctx::Json *requestResult) { int ret = write(); - if (!being_subscribed) - destroy_self(); + if (!__beingSubscribed) + destroySelf(); return ret; } -int ctx::device_provider_base::subscribe() +int ctx::DeviceProviderBase::subscribe() { return ERR_NOT_SUPPORTED; } -int ctx::device_provider_base::unsubscribe() +int ctx::DeviceProviderBase::unsubscribe() { return ERR_NOT_SUPPORTED; } -int ctx::device_provider_base::read() +int ctx::DeviceProviderBase::read() { return ERR_NOT_SUPPORTED; } -int ctx::device_provider_base::write() +int ctx::DeviceProviderBase::write() { return ERR_NOT_SUPPORTED; } -bool ctx::device_provider_base::get_system_info_bool(const char *key) +bool ctx::DeviceProviderBase::getSystemInfoBool(const char *key) { bool supported = false; int ret = system_info_get_platform_bool(key, &supported); diff --git a/src/device/device_provider_base.h b/src/device/DeviceProviderBase.h similarity index 83% rename from src/device/device_provider_base.h rename to src/device/DeviceProviderBase.h index 6b2c1a9..3d81233 100644 --- a/src/device/device_provider_base.h +++ b/src/device/DeviceProviderBase.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_DEVICE_PROVIDER_BASE_H__ -#define __CONTEXT_DEVICE_PROVIDER_BASE_H__ +#ifndef _CONTEXT_DEVICE_PROVIDER_BASE_H_ +#define _CONTEXT_DEVICE_PROVIDER_BASE_H_ #include #include @@ -43,7 +43,7 @@ static ContextProviderBase *create(void *data); \ static void destroy(void *data); \ protected: \ - void destroy_self(); \ + void destroySelf(); \ private: \ static prvd *__instance; \ @@ -57,14 +57,14 @@ { \ DESTROY_INSTANCE(); \ } \ - void ctx::prvd::destroy_self() \ + void ctx::prvd::destroySelf() \ { \ destroy(NULL); \ } \ namespace ctx { - class device_provider_base : public ContextProviderBase { + class DeviceProviderBase : public ContextProviderBase { public: int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); @@ -72,19 +72,19 @@ namespace ctx { int write(const char *subject, ctx::Json data, ctx::Json *requestResult); protected: - bool being_subscribed; + bool __beingSubscribed; - device_provider_base(); - virtual ~device_provider_base() {} + DeviceProviderBase(); + virtual ~DeviceProviderBase() {} virtual int subscribe(); virtual int unsubscribe(); virtual int read(); virtual int write(); - virtual void destroy_self() = 0; + virtual void destroySelf() = 0; - static bool get_system_info_bool(const char *key); + static bool getSystemInfoBool(const char *key); }; } -#endif +#endif // _CONTEXT_DEVICE_PROVIDER_BASE_H_ diff --git a/src/device/activity/activity.h b/src/device/activity/Activity.h similarity index 50% rename from src/device/activity/activity.h rename to src/device/activity/Activity.h index 2f44267..b7bf49e 100644 --- a/src/device/activity/activity.h +++ b/src/device/activity/Activity.h @@ -14,50 +14,50 @@ * limitations under the License. */ -#ifndef _DEVICE_STATUS_ACTIVITY_H_ -#define _DEVICE_STATUS_ACTIVITY_H_ +#ifndef _DEVICE_ACTIVITY_STATUS_H_ +#define _DEVICE_ACTIVITY_STATUS_H_ #include -#include "activity_base.h" +#include "ActivityBase.h" -#define GENERATE_ACTIVITY_PROVIDER(act_prvd, act_subj, act_type) \ - class act_prvd : public user_activity_base { \ +#define GENERATE_ACTIVITY_PROVIDER(actPrvd, actSubj, actType) \ + class actPrvd : public UserActivityBase { \ public: \ static ContextProviderBase *create(void *data) \ { \ - CREATE_INSTANCE(ctx::act_prvd); \ + CREATE_INSTANCE(ctx::actPrvd); \ } \ static void destroy(void *data) \ { \ DESTROY_INSTANCE(); \ } \ - static bool is_supported() \ + static bool isSupported() \ { \ - return get_system_info_bool("tizen.org/feature/sensor.activity_recognition"); \ + return getSystemInfoBool("tizen.org/feature/sensor.activity_recognition"); \ } \ - static void submit_trigger_item() \ + static void submitTriggerItem() \ { \ - context_manager::registerTriggerItem((act_subj), OPS_SUBSCRIBE, \ + context_manager::registerTriggerItem((actSubj), OPS_SUBSCRIBE, \ "{\"Event\":{\"type\":\"string\", \"values\":[\"Detected\"]}}", \ "{\"Accuracy\":{\"type\":\"string\", \"values\":[\"Low\", \"Normal\", \"High\"]}}" \ ); \ } \ protected: \ - void destroy_self() \ + void destroySelf() \ { \ destroy(NULL); \ } \ private: \ - static act_prvd *__instance; \ - act_prvd() : user_activity_base((act_subj), (act_type)) {} \ + static actPrvd *__instance; \ + actPrvd() : UserActivityBase((actSubj), (actType)) {} \ }; \ - ctx::act_prvd *ctx::act_prvd::__instance = NULL; \ + ctx::actPrvd *ctx::actPrvd::__instance = NULL; \ namespace ctx { - GENERATE_ACTIVITY_PROVIDER(user_activity_stationary, USER_ACT_SUBJ_STATIONARY, ACTIVITY_STATIONARY); - GENERATE_ACTIVITY_PROVIDER(user_activity_walking, USER_ACT_SUBJ_WALKING, ACTIVITY_WALK); - GENERATE_ACTIVITY_PROVIDER(user_activity_running, USER_ACT_SUBJ_RUNNING, ACTIVITY_RUN); - GENERATE_ACTIVITY_PROVIDER(user_activity_in_vehicle, USER_ACT_SUBJ_IN_VEHICLE, ACTIVITY_IN_VEHICLE); + GENERATE_ACTIVITY_PROVIDER(UserActivityStationary, USER_ACT_SUBJ_STATIONARY, ACTIVITY_STATIONARY); + GENERATE_ACTIVITY_PROVIDER(UserActivityWalking, USER_ACT_SUBJ_WALKING, ACTIVITY_WALK); + GENERATE_ACTIVITY_PROVIDER(UserActivityRunning, USER_ACT_SUBJ_RUNNING, ACTIVITY_RUN); + GENERATE_ACTIVITY_PROVIDER(UserActivityInVehicle, USER_ACT_SUBJ_IN_VEHICLE, ACTIVITY_IN_VEHICLE); } -#endif // _DEVICE_STATUS_ACTIVITY_H_ +#endif // _DEVICE_ACTIVITY_STATUS_H_ diff --git a/src/device/activity/activity_base.cpp b/src/device/activity/ActivityBase.cpp similarity index 51% rename from src/device/activity/activity_base.cpp rename to src/device/activity/ActivityBase.cpp index 30201ca..67cd4e3 100644 --- a/src/device/activity/activity_base.cpp +++ b/src/device/activity/ActivityBase.cpp @@ -16,33 +16,33 @@ #include #include -#include "activity_types.h" -#include "activity_base.h" +#include "ActivityTypes.h" +#include "ActivityBase.h" -ctx::user_activity_base::user_activity_base(const char *subj, activity_type_e type) - : activity_type(type) - , activity_handle(NULL) - , subject(subj) +ctx::UserActivityBase::UserActivityBase(const char *subj, activity_type_e type) : + __activityType(type), + __activityHandle(NULL), + __subject(subj) { } -ctx::user_activity_base::~user_activity_base() +ctx::UserActivityBase::~UserActivityBase() { - if (activity_handle) - activity_release(activity_handle); + if (__activityHandle) + activity_release(__activityHandle); } -void ctx::user_activity_base::event_cb(activity_type_e activity, const activity_data_h data, double timestamp, activity_error_e error, void* user_data) +void ctx::UserActivityBase::__updateCb(activity_type_e activity, const activity_data_h data, double timestamp, activity_error_e error, void* userData) { IF_FAIL_VOID_TAG(error == ACTIVITY_ERROR_NONE, _E, "Error: %d", error); - user_activity_base *instance = static_cast(user_data); - instance->handle_event(activity, data, timestamp); + UserActivityBase *instance = static_cast(userData); + instance->__handleUpdate(activity, data, timestamp); } -void ctx::user_activity_base::handle_event(activity_type_e activity, const activity_data_h data, double timestamp) +void ctx::UserActivityBase::__handleUpdate(activity_type_e activity, const activity_data_h data, double timestamp) { - IF_FAIL_VOID_TAG(activity == activity_type, _E, "Invalid activity: %d", activity); + IF_FAIL_VOID_TAG(activity == __activityType, _E, "Invalid activity: %d", activity); ctx::Json dataRead; dataRead.set(NULL, USER_ACT_EVENT, USER_ACT_DETECTED); @@ -62,38 +62,38 @@ void ctx::user_activity_base::handle_event(activity_type_e activity, const activ break; } - context_manager::publish(subject.c_str(), NULL, ERR_NONE, dataRead); + context_manager::publish(__subject.c_str(), NULL, ERR_NONE, dataRead); } -int ctx::user_activity_base::subscribe() +int ctx::UserActivityBase::subscribe() { - IF_FAIL_RETURN(activity_handle == NULL, ERR_NONE); + IF_FAIL_RETURN(__activityHandle == NULL, ERR_NONE); - _D("Starting to monitor %s", subject.c_str()); + _D("Starting to monitor %s", __subject.c_str()); - activity_create(&activity_handle); - IF_FAIL_RETURN_TAG(activity_handle, ERR_OPERATION_FAILED, _E, "Memory allocation failed"); + activity_create(&__activityHandle); + IF_FAIL_RETURN_TAG(__activityHandle, ERR_OPERATION_FAILED, _E, "Memory allocation failed"); - int ret = activity_start_recognition(activity_handle, activity_type, event_cb, this); + int ret = activity_start_recognition(__activityHandle, __activityType, __updateCb, this); if (ret != ACTIVITY_ERROR_NONE) { _E("Recognition starting failed"); - activity_release(activity_handle); - activity_handle = NULL; + activity_release(__activityHandle); + __activityHandle = NULL; return ERR_OPERATION_FAILED; } return ERR_NONE; } -int ctx::user_activity_base::unsubscribe() +int ctx::UserActivityBase::unsubscribe() { - IF_FAIL_RETURN(activity_handle, ERR_NONE); + IF_FAIL_RETURN(__activityHandle, ERR_NONE); - _D("Stop monitoring %s", subject.c_str()); + _D("Stop monitoring %s", __subject.c_str()); - activity_stop_recognition(activity_handle); - activity_release(activity_handle); - activity_handle = NULL; + activity_stop_recognition(__activityHandle); + activity_release(__activityHandle); + __activityHandle = NULL; return ERR_NONE; } diff --git a/src/device/activity/activity_base.h b/src/device/activity/ActivityBase.h similarity index 54% rename from src/device/activity/activity_base.h rename to src/device/activity/ActivityBase.h index 05fa503..c7ce566 100644 --- a/src/device/activity/activity_base.h +++ b/src/device/activity/ActivityBase.h @@ -14,33 +14,33 @@ * limitations under the License. */ -#ifndef _DEVICE_STATUS_ACTIVITY_BASE_H_ -#define _DEVICE_STATUS_ACTIVITY_BASE_H_ +#ifndef _DEVICE_ACTIVITY_STATUS_BASE_H_ +#define _DEVICE_ACTIVITY_STATUS_BASE_H_ #include #include -#include "../device_provider_base.h" +#include "../DeviceProviderBase.h" namespace ctx { - class user_activity_base : public device_provider_base { + class UserActivityBase : public DeviceProviderBase { public: int subscribe(); int unsubscribe(); protected: - activity_type_e activity_type; - activity_h activity_handle; - std::string subject; + activity_type_e __activityType; + activity_h __activityHandle; + std::string __subject; - user_activity_base(const char *subj, activity_type_e type); - virtual ~user_activity_base(); + UserActivityBase(const char *subj, activity_type_e type); + virtual ~UserActivityBase(); private: - void handle_event(activity_type_e activity, const activity_data_h data, double timestamp); - static void event_cb(activity_type_e activity, const activity_data_h data, double timestamp, activity_error_e error, void* user_data); + void __handleUpdate(activity_type_e activity, const activity_data_h data, double timestamp); + static void __updateCb(activity_type_e activity, const activity_data_h data, double timestamp, activity_error_e error, void* userData); }; } -#endif // _DEVICE_STATUS_ACTIVITY_BASE_H_ +#endif // _DEVICE_ACTIVITY_STATUS_BASE_H_ diff --git a/src/device/activity/activity_types.h b/src/device/activity/ActivityTypes.h similarity index 89% rename from src/device/activity/activity_types.h rename to src/device/activity/ActivityTypes.h index c15bbb4..4562b7b 100644 --- a/src/device/activity/activity_types.h +++ b/src/device/activity/ActivityTypes.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_USER_ACTIVITY_TYPES_H__ -#define __CONTEXT_USER_ACTIVITY_TYPES_H__ +#ifndef _DEVICE_ACTIVITY_STATUS_TYPES_H_ +#define _DEVICE_ACTIVITY_STATUS_TYPES_H_ // Subject #define USER_ACT_SUBJ_IN_VEHICLE "activity/in_vehicle" @@ -33,4 +33,4 @@ #define USER_ACT_NORMAL "Normal" #define USER_ACT_HIGH "High" -#endif //__CONTEXT_USER_ACTIVITY_TYPES_H__ +#endif // _DEVICE_ACTIVITY_STATUS_TYPES_H_ diff --git a/src/device/device_context_provider.cpp b/src/device/device_context_provider.cpp deleted file mode 100644 index 1e42e20..0000000 --- a/src/device/device_context_provider.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include - -#include "system/system_types.h" -#include "social/social_types.h" -#include "activity/activity_types.h" - -#include "system/alarm.h" -#include "system/time.h" - -#ifdef _MOBILE_ -#include "system/runtime-info/charger.h" -#include "system/runtime-info/gps.h" -#include "system/runtime-info/usb.h" -#include "system/wifi.h" -#include "system/headphone.h" -#include "system/battery.h" -#include "system/psmode.h" -#include "social/call.h" -#include "social/email.h" -#include "social/message.h" -#include "social/contacts.h" -#include "activity/activity.h" -#endif - -#ifdef _WEARABLE_ -#include "system/runtime-info/charger.h" -#include "system/runtime-info/gps.h" -#include "system/runtime-info/usb.h" -#include "system/wifi.h" -#include "system/headphone.h" -#include "system/battery.h" -#include "system/psmode.h" -#include "social/call.h" -#include "social/message.h" -#include "activity/activity.h" -#endif - -#ifdef _TV_ -#include "system/wifi.h" -#include "system/headphone.h" -#endif - -#define PRIV_NETWORK "network.get" -#define PRIV_TELEPHONY "telephony" -#define PRIV_MESSAGE "message.read" -#define PRIV_CONTACT "contact.read" - -template -void registerProvider(const char *subject, const char *privilege) -{ - if (!provider::is_supported()) - return; - - ctx::ContextProviderInfo providerInfo(provider::create, provider::destroy, NULL, privilege); - ctx::context_manager::registerProvider(subject, providerInfo); - provider::submit_trigger_item(); -} - -EXTAPI bool ctx::initDeviceContextProvider() -{ - registerProvider(DEVICE_ST_SUBJ_ALARM, NULL); - registerProvider(DEVICE_ST_SUBJ_TIME, NULL); - -#ifdef _MOBILE_ - registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); - registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); - - registerProvider(DEVICE_ST_SUBJ_CHARGER, NULL); - registerProvider(DEVICE_ST_SUBJ_GPS, NULL); - registerProvider(DEVICE_ST_SUBJ_USB, NULL); - registerProvider(DEVICE_ST_SUBJ_BATTERY, NULL); - registerProvider(DEVICE_ST_SUBJ_PSMODE, NULL); - - registerProvider(SOCIAL_ST_SUBJ_CALL, PRIV_TELEPHONY); - registerProvider(SOCIAL_ST_SUBJ_EMAIL, NULL); - registerProvider(SOCIAL_ST_SUBJ_MESSAGE, PRIV_MESSAGE); - registerProvider(SOCIAL_ST_SUBJ_CONTACTS, PRIV_CONTACT); - - registerProvider(USER_ACT_SUBJ_STATIONARY, NULL); - registerProvider(USER_ACT_SUBJ_WALKING, NULL); - registerProvider(USER_ACT_SUBJ_RUNNING, NULL); - registerProvider(USER_ACT_SUBJ_IN_VEHICLE, NULL); - - /* Create context providers, which need to be initiated before being subscribed */ - if (device_status_wifi::is_supported()) - device_status_wifi::create(NULL); -#endif - -#ifdef _WEARABLE_ - registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); - registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); - - registerProvider(DEVICE_ST_SUBJ_CHARGER, NULL); - registerProvider(DEVICE_ST_SUBJ_GPS, NULL); - registerProvider(DEVICE_ST_SUBJ_USB, NULL); - registerProvider(DEVICE_ST_SUBJ_BATTERY, NULL); - registerProvider(DEVICE_ST_SUBJ_PSMODE, NULL); - - registerProvider(SOCIAL_ST_SUBJ_CALL, PRIV_TELEPHONY); - registerProvider(SOCIAL_ST_SUBJ_MESSAGE, PRIV_MESSAGE); - - registerProvider(USER_ACT_SUBJ_STATIONARY, NULL); - registerProvider(USER_ACT_SUBJ_WALKING, NULL); - registerProvider(USER_ACT_SUBJ_RUNNING, NULL); - registerProvider(USER_ACT_SUBJ_IN_VEHICLE, NULL); - - /* Create context providers, which need to be initiated before being subscribed */ - if (device_status_wifi::is_supported()) - device_status_wifi::create(NULL); -#endif - -#ifdef _TV_ - registerProvider(DEVICE_ST_SUBJ_WIFI, PRIV_NETWORK); - registerProvider(DEVICE_ST_SUBJ_HEADPHONE, NULL); - - /* Create context providers, which need to be initiated before being subscribed */ - if (device_status_wifi::is_supported()) - device_status_wifi::create(NULL); -#endif - - return true; -} diff --git a/src/device/social/call.cpp b/src/device/social/Call.cpp similarity index 64% rename from src/device/social/call.cpp rename to src/device/social/Call.cpp index 71e3ea8..d8bbebe 100644 --- a/src/device/social/call.cpp +++ b/src/device/social/Call.cpp @@ -17,14 +17,14 @@ #include #include #include -#include "social_types.h" -#include "call.h" +#include "SocialTypes.h" +#include "Call.h" #define TELEPHONY_NOTI_ID_CNT 8 -GENERATE_PROVIDER_COMMON_IMPL(social_status_call); +GENERATE_PROVIDER_COMMON_IMPL(SocialStatusCall); -static bool telephony_initialized = false; -static telephony_noti_e call_noti_ids[] = +static bool __telephonyInitialized = false; +static telephony_noti_e __callNotiIds[] = { TELEPHONY_NOTI_VOICE_CALL_STATUS_IDLE, TELEPHONY_NOTI_VOICE_CALL_STATUS_ACTIVE, @@ -38,24 +38,24 @@ static telephony_noti_e call_noti_ids[] = TELEPHONY_NOTI_VIDEO_CALL_STATUS_ALERTING, TELEPHONY_NOTI_VIDEO_CALL_STATUS_INCOMING, }; -static ctx::Json latest; +static ctx::Json __latest; -ctx::social_status_call::social_status_call() +ctx::SocialStatusCall::SocialStatusCall() { - handle_list.count = 0; - handle_list.handle = NULL; + __handleList.count = 0; + __handleList.handle = NULL; } -ctx::social_status_call::~social_status_call() +ctx::SocialStatusCall::~SocialStatusCall() { } -bool ctx::social_status_call::is_supported() +bool ctx::SocialStatusCall::isSupported() { - return get_system_info_bool("tizen.org/feature/network.telephony"); + return getSystemInfoBool("tizen.org/feature/network.telephony"); } -void ctx::social_status_call::submit_trigger_item() +void ctx::SocialStatusCall::submitTriggerItem() { context_manager::registerTriggerItem(SOCIAL_ST_SUBJ_CALL, OPS_SUBSCRIBE | OPS_READ, "{" @@ -67,21 +67,20 @@ void ctx::social_status_call::submit_trigger_item() //TODO remove Connecting, Connected } -void ctx::social_status_call::call_event_cb(telephony_h handle, telephony_noti_e noti_id, void *data, void *user_data) +void ctx::SocialStatusCall::__updateCb(telephony_h handle, telephony_noti_e notiId, void *data, void *userData) { - social_status_call *instance = static_cast(user_data); - instance->handle_call_event(handle, noti_id, data); + SocialStatusCall *instance = static_cast(userData); + instance->__handleUpdate(handle, notiId, data); } -void ctx::social_status_call::handle_call_event(telephony_h handle, telephony_noti_e noti_id, void* id) +void ctx::SocialStatusCall::__handleUpdate(telephony_h handle, telephony_noti_e notiId, void* id) { - Json data; unsigned int count; - telephony_call_h *call_list; + telephony_call_h *callList; // Call state - switch (noti_id) { + switch (notiId) { case TELEPHONY_NOTI_VOICE_CALL_STATUS_IDLE: case TELEPHONY_NOTI_VIDEO_CALL_STATUS_IDLE: data.set(NULL, SOCIAL_ST_STATE, SOCIAL_ST_IDLE); @@ -103,12 +102,12 @@ void ctx::social_status_call::handle_call_event(telephony_h handle, telephony_no case TELEPHONY_NOTI_VOICE_CALL_STATUS_DIALING: case TELEPHONY_NOTI_VIDEO_CALL_STATUS_DIALING:*/ default: - _E("Unkown noti id: %d", noti_id); + _E("Unkown noti id: %d", notiId); return; } // Call type - switch (noti_id) { + switch (notiId) { case TELEPHONY_NOTI_VOICE_CALL_STATUS_IDLE: case TELEPHONY_NOTI_VOICE_CALL_STATUS_ACTIVE: case TELEPHONY_NOTI_VOICE_CALL_STATUS_ALERTING: @@ -126,70 +125,70 @@ void ctx::social_status_call::handle_call_event(telephony_h handle, telephony_no case TELEPHONY_NOTI_VOICE_CALL_STATUS_DIALING: case TELEPHONY_NOTI_VIDEO_CALL_STATUS_DIALING:*/ default: - _E("Unkown noti id: %d", noti_id); + _E("Unkown noti id: %d", notiId); return; } - int err = telephony_call_get_call_list(handle, &count, &call_list); + int err = telephony_call_get_call_list(handle, &count, &callList); IF_FAIL_VOID_TAG(err == TELEPHONY_ERROR_NONE, _E, "Getting call list failed"); - unsigned int call_id = *static_cast(id); + unsigned int callId = *static_cast(id); for (unsigned int i = 0; i < count; i++) { - unsigned int tmp_id; + unsigned int tempId; // Handle id - if (!get_call_handle_id(call_list[i], tmp_id)) { + if (!__getCallHandleId(callList[i], tempId)) { continue; } - if (call_id != tmp_id) { + if (callId != tempId) { continue; } // Address std::string address; - if (get_call_address(call_list[i], address)) { + if (__getCallAddress(callList[i], address)) { data.set(NULL, SOCIAL_ST_ADDRESS, address); break; } } - if (latest != data) { + if (__latest != data) { context_manager::publish(SOCIAL_ST_SUBJ_CALL, NULL, ERR_NONE, data); - latest = data.str(); + __latest = data.str(); } - telephony_call_release_call_list(count, &call_list); + telephony_call_release_call_list(count, &callList); } -bool ctx::social_status_call::init_telephony() +bool ctx::SocialStatusCall::__initTelephony() { - IF_FAIL_RETURN(!telephony_initialized, true); + IF_FAIL_RETURN(!__telephonyInitialized, true); - int err = telephony_init(&handle_list); + int err = telephony_init(&__handleList); IF_FAIL_RETURN_TAG(err == TELEPHONY_ERROR_NONE, false, _E, "Initialization failed"); - telephony_initialized = true; + __telephonyInitialized = true; return true; } -void ctx::social_status_call::release_telephony() +void ctx::SocialStatusCall::__releaseTelephony() { - IF_FAIL_VOID(telephony_initialized); + IF_FAIL_VOID(__telephonyInitialized); - telephony_deinit(&handle_list); + telephony_deinit(&__handleList); - telephony_initialized = false; + __telephonyInitialized = false; } -bool ctx::social_status_call::set_callback() +bool ctx::SocialStatusCall::__setCallback() { //TODO: Consider dual-sim devices - IF_FAIL_RETURN_TAG(init_telephony(), false, _E, "Initialization failed"); + IF_FAIL_RETURN_TAG(__initTelephony(), false, _E, "Initialization failed"); int err; - for (unsigned int i = 0; i < handle_list.count; i++) { + for (unsigned int i = 0; i < __handleList.count; i++) { for (unsigned int j = 0; j < TELEPHONY_NOTI_ID_CNT; j++) { - err = telephony_set_noti_cb(handle_list.handle[i], call_noti_ids[j], call_event_cb, this); + err = telephony_set_noti_cb(__handleList.handle[i], __callNotiIds[j], __updateCb, this); IF_FAIL_CATCH(err == TELEPHONY_ERROR_NONE); } } @@ -198,22 +197,22 @@ bool ctx::social_status_call::set_callback() CATCH: _E("Initialization failed"); - release_telephony(); + __releaseTelephony(); return false; } -void ctx::social_status_call::unset_callback() +void ctx::SocialStatusCall::__unsetCallback() { - for (unsigned int i = 0; i < handle_list.count; i++) { + for (unsigned int i = 0; i < __handleList.count; i++) { for (unsigned int j = 0; j < TELEPHONY_NOTI_ID_CNT; j++) { - telephony_unset_noti_cb(handle_list.handle[i], call_noti_ids[j]); + telephony_unset_noti_cb(__handleList.handle[i], __callNotiIds[j]); } } - release_telephony(); + __releaseTelephony(); } -bool ctx::social_status_call::get_call_state(telephony_call_h& handle, std::string& state) +bool ctx::SocialStatusCall::__getCallState(telephony_call_h& handle, std::string& state) { state.clear(); @@ -246,7 +245,7 @@ bool ctx::social_status_call::get_call_state(telephony_call_h& handle, std::stri return true; } -bool ctx::social_status_call::get_call_type(telephony_call_h& handle, std::string& type) +bool ctx::SocialStatusCall::__getCallType(telephony_call_h& handle, std::string& type) { type.clear(); @@ -271,7 +270,7 @@ bool ctx::social_status_call::get_call_type(telephony_call_h& handle, std::strin return true; } -bool ctx::social_status_call::get_call_address(telephony_call_h& handle, std::string& address) +bool ctx::SocialStatusCall::__getCallAddress(telephony_call_h& handle, std::string& address) { address.clear(); @@ -290,7 +289,7 @@ bool ctx::social_status_call::get_call_address(telephony_call_h& handle, std::st return true; } -bool ctx::social_status_call::get_call_handle_id(telephony_call_h& handle, unsigned int& id) +bool ctx::SocialStatusCall::__getCallHandleId(telephony_call_h& handle, unsigned int& id) { int err = telephony_call_get_handle_id(handle, &id); IF_FAIL_RETURN_TAG(err == TELEPHONY_ERROR_NONE, false, _E, "Getting handle id failed"); @@ -298,50 +297,50 @@ bool ctx::social_status_call::get_call_handle_id(telephony_call_h& handle, unsig return true; } -int ctx::social_status_call::subscribe() +int ctx::SocialStatusCall::subscribe() { - bool ret = set_callback(); + bool ret = __setCallback(); IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); return ERR_NONE; } -int ctx::social_status_call::unsubscribe() +int ctx::SocialStatusCall::unsubscribe() { - unset_callback(); + __unsetCallback(); return ERR_NONE; } -bool ctx::social_status_call::read_current_status(telephony_h& handle, ctx::Json& data) +bool ctx::SocialStatusCall::__readCurrentStatus(telephony_h& handle, ctx::Json* data) { unsigned int count = 0; - telephony_call_h *call_list = NULL; - telephony_call_get_call_list(handle, &count, &call_list); + telephony_call_h *callList = NULL; + telephony_call_get_call_list(handle, &count, &callList); // Default data - data.set(NULL, SOCIAL_ST_STATE, SOCIAL_ST_IDLE); + data->set(NULL, SOCIAL_ST_STATE, SOCIAL_ST_IDLE); // Held & Dialing are ignored for (unsigned int i = 0; i < count; i++) { // Call state std::string state; - if (get_call_state(call_list[i], state)) { + if (__getCallState(callList[i], state)) { // Skip Held & Dialing if (state.compare(SOCIAL_ST_HELD) == 0 || state.compare(SOCIAL_ST_DIALING) == 0) continue; - data.set(NULL, SOCIAL_ST_STATE, state); + data->set(NULL, SOCIAL_ST_STATE, state); } // Call type std::string type; - if (get_call_type(call_list[i], type)) { - data.set(NULL, SOCIAL_ST_MEDIUM, type); + if (__getCallType(callList[i], type)) { + data->set(NULL, SOCIAL_ST_MEDIUM, type); } // Address std::string address; - if (get_call_address(call_list[i], address)) { - data.set(NULL, SOCIAL_ST_ADDRESS, address); + if (__getCallAddress(callList[i], address)) { + data->set(NULL, SOCIAL_ST_ADDRESS, address); } if (state == SOCIAL_ST_ACTIVE) { @@ -349,36 +348,36 @@ bool ctx::social_status_call::read_current_status(telephony_h& handle, ctx::Json } } - telephony_call_release_call_list(count, &call_list); + telephony_call_release_call_list(count, &callList); return true; } -int ctx::social_status_call::read() +int ctx::SocialStatusCall::read() { - bool temporary_handle = false; - if (!telephony_initialized) { - IF_FAIL_RETURN(init_telephony(), ERR_OPERATION_FAILED); - temporary_handle = true; + bool temporaryHandle = false; + if (!__telephonyInitialized) { + IF_FAIL_RETURN(__initTelephony(), ERR_OPERATION_FAILED); + temporaryHandle = true; } bool ret = true; Json data; data.set(NULL, SOCIAL_ST_STATE, SOCIAL_ST_IDLE); - for (unsigned int i = 0; i < handle_list.count; i++) { + for (unsigned int i = 0; i < __handleList.count; i++) { telephony_sim_state_e state; - int err = telephony_sim_get_state(handle_list.handle[i], &state); + int err = telephony_sim_get_state(__handleList.handle[i], &state); IF_FAIL_RETURN_TAG(err == TELEPHONY_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Getting SIM status failed"); if (state != TELEPHONY_SIM_STATE_AVAILABLE) continue; - ret = read_current_status(handle_list.handle[i], data); + ret = __readCurrentStatus(__handleList.handle[i], &data); break; } - if (temporary_handle) - release_telephony(); + if (temporaryHandle) + __releaseTelephony(); if (ret) { ctx::context_manager::replyToRead(SOCIAL_ST_SUBJ_CALL, NULL, ERR_NONE, data); diff --git a/src/device/social/Call.h b/src/device/social/Call.h new file mode 100644 index 0000000..38fdab9 --- /dev/null +++ b/src/device/social/Call.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _CONTEXT_SOCIAL_STATUS_CALL_H_ +#define _CONTEXT_SOCIAL_STATUS_CALL_H_ + +#include +#include "../DeviceProviderBase.h" + +namespace ctx { + + class SocialStatusCall : public DeviceProviderBase { + + GENERATE_PROVIDER_COMMON_DECL(SocialStatusCall); + + public: + int subscribe(); + int unsubscribe(); + int read(); + static bool isSupported(); + static void submitTriggerItem(); + + private: + telephony_handle_list_s __handleList; + + SocialStatusCall(); + ~SocialStatusCall(); + + bool __initTelephony(); + void __releaseTelephony(); + bool __setCallback(); + void __unsetCallback(); + bool __readCurrentStatus(telephony_h& handle, ctx::Json* data); + + bool __getCallState(telephony_call_h& handle, std::string& state); + bool __getCallType(telephony_call_h& handle, std::string& type); + bool __getCallAddress(telephony_call_h& handle, std::string& address); + bool __getCallHandleId(telephony_call_h& handle, unsigned int& id); + + void __handleUpdate(telephony_h handle, telephony_noti_e notiId, void* id); + static void __updateCb(telephony_h handle, telephony_noti_e notiId, void *data, void *userData); + }; +} + +#endif // _CONTEXT_SOCIAL_STATUS_CALL_H_ diff --git a/src/device/social/contacts.cpp b/src/device/social/Contacts.cpp similarity index 51% rename from src/device/social/contacts.cpp rename to src/device/social/Contacts.cpp index f071e78..4604c37 100644 --- a/src/device/social/contacts.cpp +++ b/src/device/social/Contacts.cpp @@ -16,31 +16,31 @@ #include #include -#include "social_types.h" -#include "contacts.h" +#include "SocialTypes.h" +#include "Contacts.h" #define MY_PROFILE_VIEW _contacts_my_profile._uri #define PERSON_VIEW _contacts_person._uri #define TIME_INTERVAL 1 -GENERATE_PROVIDER_COMMON_IMPL(social_status_contacts); +GENERATE_PROVIDER_COMMON_IMPL(SocialStatusContacts); -ctx::social_status_contacts::social_status_contacts() - : latest_my_profile(0) - , latest_person(0) +ctx::SocialStatusContacts::SocialStatusContacts() : + __latestMyProfile(0), + __latestPerson(0) { } -ctx::social_status_contacts::~social_status_contacts() +ctx::SocialStatusContacts::~SocialStatusContacts() { } -bool ctx::social_status_contacts::is_supported() +bool ctx::SocialStatusContacts::isSupported() { return true; } -void ctx::social_status_contacts::submit_trigger_item() +void ctx::SocialStatusContacts::submitTriggerItem() { context_manager::registerTriggerItem(SOCIAL_ST_SUBJ_CONTACTS, OPS_SUBSCRIBE, "{" @@ -50,21 +50,21 @@ void ctx::social_status_contacts::submit_trigger_item() NULL); } -void ctx::social_status_contacts::db_change_cb(const char* view_uri, void* user_data) +void ctx::SocialStatusContacts::__updateCb(const char* viewUri, void* userData) { - social_status_contacts *instance = static_cast(user_data); - instance->handle_db_change(view_uri); + SocialStatusContacts *instance = static_cast(userData); + instance->__handleUpdate(viewUri); } -void ctx::social_status_contacts::handle_db_change(const char* view_uri) +void ctx::SocialStatusContacts::__handleUpdate(const char* viewUri) { - if (!STR_EQ(view_uri, _contacts_my_profile._uri) && !STR_EQ(view_uri, _contacts_person._uri)) { + if (!STR_EQ(viewUri, _contacts_my_profile._uri) && !STR_EQ(viewUri, _contacts_person._uri)) { _W("Unknown view uri"); return; } - std::string view = (STR_EQ(view_uri, _contacts_my_profile._uri)? SOCIAL_ST_MY_PROFILE : SOCIAL_ST_PERSON); - IF_FAIL_VOID_TAG(!is_consecutive_change(view_uri), _D, "Ignore consecutive db change: %s", view.c_str()); + std::string view = (STR_EQ(viewUri, _contacts_my_profile._uri)? SOCIAL_ST_MY_PROFILE : SOCIAL_ST_PERSON); + IF_FAIL_VOID_TAG(!__isConsecutiveChange(viewUri), _D, "Ignore consecutive db change: %s", view.c_str()); ctx::Json data; data.set(NULL, SOCIAL_ST_EVENT, SOCIAL_ST_CHANGED); @@ -72,17 +72,17 @@ void ctx::social_status_contacts::handle_db_change(const char* view_uri) context_manager::publish(SOCIAL_ST_SUBJ_CONTACTS, NULL, ERR_NONE, data); } -bool ctx::social_status_contacts::is_consecutive_change(const char* view_uri) +bool ctx::SocialStatusContacts::__isConsecutiveChange(const char* viewUri) { time_t now = time(NULL); double diff = 0; - if (STR_EQ(view_uri, MY_PROFILE_VIEW)) { - diff = difftime(now, latest_my_profile); - latest_my_profile = now; - } else if (STR_EQ(view_uri, PERSON_VIEW)) { - diff = difftime(now, latest_person); - latest_person = now; + if (STR_EQ(viewUri, MY_PROFILE_VIEW)) { + diff = difftime(now, __latestMyProfile); + __latestMyProfile = now; + } else if (STR_EQ(viewUri, PERSON_VIEW)) { + diff = difftime(now, __latestPerson); + __latestPerson = now; } if (diff < TIME_INTERVAL) @@ -91,17 +91,17 @@ bool ctx::social_status_contacts::is_consecutive_change(const char* view_uri) return false; } -bool ctx::social_status_contacts::set_callback() +bool ctx::SocialStatusContacts::__setCallback() { int err; err = contacts_connect(); IF_FAIL_RETURN_TAG(err == CONTACTS_ERROR_NONE, false, _E, "Connecting contacts failed"); - err = contacts_db_add_changed_cb(MY_PROFILE_VIEW, db_change_cb, this); + err = contacts_db_add_changed_cb(MY_PROFILE_VIEW, __updateCb, this); IF_FAIL_CATCH_TAG(err == CONTACTS_ERROR_NONE, _E, "Setting my profile view changed callback failed"); - err = contacts_db_add_changed_cb(PERSON_VIEW, db_change_cb, this); + err = contacts_db_add_changed_cb(PERSON_VIEW, __updateCb, this); IF_FAIL_CATCH_TAG(err == CONTACTS_ERROR_NONE, _E, "Setting person view changed callback failed"); return true; @@ -111,26 +111,26 @@ CATCH: return false; } -void ctx::social_status_contacts::unset_callback() +void ctx::SocialStatusContacts::__unsetCallback() { - contacts_db_remove_changed_cb(MY_PROFILE_VIEW, db_change_cb, this); - contacts_db_remove_changed_cb(PERSON_VIEW, db_change_cb, this); + contacts_db_remove_changed_cb(MY_PROFILE_VIEW, __updateCb, this); + contacts_db_remove_changed_cb(PERSON_VIEW, __updateCb, this); contacts_disconnect(); - latest_my_profile = 0; - latest_person = 0; + __latestMyProfile = 0; + __latestPerson = 0; } -int ctx::social_status_contacts::subscribe() +int ctx::SocialStatusContacts::subscribe() { - bool ret = set_callback(); + bool ret = __setCallback(); IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); return ERR_NONE; } -int ctx::social_status_contacts::unsubscribe() +int ctx::SocialStatusContacts::unsubscribe() { - unset_callback(); + __unsetCallback(); return ERR_NONE; } diff --git a/src/device/social/contacts.h b/src/device/social/Contacts.h similarity index 61% rename from src/device/social/contacts.h rename to src/device/social/Contacts.h index 1169412..b99929b 100644 --- a/src/device/social/contacts.h +++ b/src/device/social/Contacts.h @@ -18,32 +18,32 @@ #define _CONTEXT_SOCIAL_STATUS_CONTACTS_H_ #include -#include "../device_provider_base.h" +#include "../DeviceProviderBase.h" namespace ctx { - class social_status_contacts : public device_provider_base { + class SocialStatusContacts : public DeviceProviderBase { - GENERATE_PROVIDER_COMMON_DECL(social_status_contacts); + GENERATE_PROVIDER_COMMON_DECL(SocialStatusContacts); public: int subscribe(); int unsubscribe(); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); private: - time_t latest_my_profile; - time_t latest_person; + time_t __latestMyProfile; + time_t __latestPerson; - social_status_contacts(); - ~social_status_contacts(); + SocialStatusContacts(); + ~SocialStatusContacts(); - bool set_callback(); - void unset_callback(); - void handle_db_change(const char* view_uri); - static void db_change_cb(const char* view_uri, void* user_data); - bool is_consecutive_change(const char* view_uri); + bool __setCallback(); + void __unsetCallback(); + void __handleUpdate(const char* viewUri); + static void __updateCb(const char* viewUri, void* userData); + bool __isConsecutiveChange(const char* viewUri); }; } diff --git a/src/device/social/email.cpp b/src/device/social/Email.cpp similarity index 56% rename from src/device/social/email.cpp rename to src/device/social/Email.cpp index 898cf03..c49f185 100644 --- a/src/device/social/email.cpp +++ b/src/device/social/Email.cpp @@ -18,27 +18,27 @@ #include #include -#include "social_types.h" -#include "email.h" +#include "SocialTypes.h" +#include "Email.h" -GENERATE_PROVIDER_COMMON_IMPL(social_status_email); +GENERATE_PROVIDER_COMMON_IMPL(SocialStatusEmail); -ctx::social_status_email::social_status_email() - : dbus_signal_id(-1) - , __dbusWatcher(DBusType::SESSION) +ctx::SocialStatusEmail::SocialStatusEmail() : + __dbusSignalId(-1), + __dbusWatcher(DBusType::SESSION) { } -ctx::social_status_email::~social_status_email() +ctx::SocialStatusEmail::~SocialStatusEmail() { } -bool ctx::social_status_email::is_supported() +bool ctx::SocialStatusEmail::isSupported() { - return get_system_info_bool("tizen.org/feature/network.telephony"); + return getSystemInfoBool("tizen.org/feature/network.telephony"); } -void ctx::social_status_email::submit_trigger_item() +void ctx::SocialStatusEmail::submitTriggerItem() { context_manager::registerTriggerItem(SOCIAL_ST_SUBJ_EMAIL, OPS_SUBSCRIBE, "{" @@ -47,25 +47,25 @@ void ctx::social_status_email::submit_trigger_item() NULL); } -void ctx::social_status_email::onSignal(const char* sender, const char* path, const char* iface, const char* name, GVariant* param) +void ctx::SocialStatusEmail::onSignal(const char* sender, const char* path, const char* iface, const char* name, GVariant* param) { - gint sub_type = 0; + gint subType = 0; gint gi1 = 0; const gchar *gc = NULL; gint gi2 = 0; gint gi3 = 0; - g_variant_get(param, "(ii&sii)", &sub_type, &gi1, &gc, &gi2, &gi3); + g_variant_get(param, "(ii&sii)", &subType, &gi1, &gc, &gi2, &gi3); - if (sub_type == NOTI_DOWNLOAD_FINISH) { + if (subType == NOTI_DOWNLOAD_FINISH) { //TODO: Check if this signal actually means that there are new mails - _D("sub type: %d, gi1: %d, gc: %s, gi2: %d, gi3: %d", sub_type, gi1, gc, gi2, gi3); + _D("sub type: %d, gi1: %d, gc: %s, gi2: %d, gi3: %d", subType, gi1, gc, gi2, gi3); ctx::Json dataUpdated; dataUpdated.set(NULL, SOCIAL_ST_EVENT, SOCIAL_ST_RECEIVED); context_manager::publish(SOCIAL_ST_SUBJ_EMAIL, NULL, ERR_NONE, dataUpdated); - } else if (sub_type == NOTI_SEND_FINISH) { - _D("sub type: %d, gi1: %d, gc: %s, gi2: %d, gi3: %d", sub_type, gi1, gc, gi2, gi3); + } else if (subType == NOTI_SEND_FINISH) { + _D("sub type: %d, gi1: %d, gc: %s, gi2: %d, gi3: %d", subType, gi1, gc, gi2, gi3); ctx::Json dataUpdated; dataUpdated.set(NULL, SOCIAL_ST_EVENT, SOCIAL_ST_SENT); context_manager::publish(SOCIAL_ST_SUBJ_EMAIL, NULL, ERR_NONE, dataUpdated); @@ -73,16 +73,16 @@ void ctx::social_status_email::onSignal(const char* sender, const char* path, co } -int ctx::social_status_email::subscribe() +int ctx::SocialStatusEmail::subscribe() { - dbus_signal_id = __dbusWatcher.watch(NULL, NULL, "User.Email.NetworkStatus", "email", this); - IF_FAIL_RETURN_TAG(dbus_signal_id >= 0, ERR_OPERATION_FAILED, _E, "Email dbus signal subscription failed"); + __dbusSignalId = __dbusWatcher.watch(NULL, NULL, "User.Email.NetworkStatus", "email", this); + IF_FAIL_RETURN_TAG(__dbusSignalId >= 0, ERR_OPERATION_FAILED, _E, "Email dbus signal subscription failed"); return ERR_NONE; } -int ctx::social_status_email::unsubscribe() +int ctx::SocialStatusEmail::unsubscribe() { - __dbusWatcher.unwatch(dbus_signal_id); + __dbusWatcher.unwatch(__dbusSignalId); return ERR_NONE; } diff --git a/src/device/social/email.h b/src/device/social/Email.h similarity index 75% rename from src/device/social/email.h rename to src/device/social/Email.h index 9cc7508..4daaea0 100644 --- a/src/device/social/email.h +++ b/src/device/social/Email.h @@ -18,27 +18,27 @@ #define _CONTEXT_SOCIAL_STATUS_EMAIL_H_ #include -#include "../device_provider_base.h" +#include "../DeviceProviderBase.h" namespace ctx { - class social_status_email : public device_provider_base, public IDBusSignalListener { + class SocialStatusEmail : public DeviceProviderBase, public IDBusSignalListener { - GENERATE_PROVIDER_COMMON_DECL(social_status_email); + GENERATE_PROVIDER_COMMON_DECL(SocialStatusEmail); public: int subscribe(); int unsubscribe(); void onSignal(const char *sender, const char *path, const char *iface, const char *name, GVariant *param); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); private: - int64_t dbus_signal_id; + int64_t __dbusSignalId; DBusSignalWatcher __dbusWatcher; - social_status_email(); - ~social_status_email(); + SocialStatusEmail(); + ~SocialStatusEmail(); }; } diff --git a/src/device/social/message.cpp b/src/device/social/Message.cpp similarity index 64% rename from src/device/social/message.cpp rename to src/device/social/Message.cpp index cf75e4f..7643175 100644 --- a/src/device/social/message.cpp +++ b/src/device/social/Message.cpp @@ -16,28 +16,28 @@ #include #include -#include "social_types.h" -#include "message.h" +#include "SocialTypes.h" +#include "Message.h" #define MAX_ADDR_SIZE 20 -GENERATE_PROVIDER_COMMON_IMPL(social_status_message); +GENERATE_PROVIDER_COMMON_IMPL(SocialStatusMessage); -ctx::social_status_message::social_status_message() - : message_handle(NULL) +ctx::SocialStatusMessage::SocialStatusMessage() : + __messageHandle(NULL) { } -ctx::social_status_message::~social_status_message() +ctx::SocialStatusMessage::~SocialStatusMessage() { } -bool ctx::social_status_message::is_supported() +bool ctx::SocialStatusMessage::isSupported() { - return get_system_info_bool("tizen.org/feature/network.telephony"); + return getSystemInfoBool("tizen.org/feature/network.telephony"); } -void ctx::social_status_message::submit_trigger_item() +void ctx::SocialStatusMessage::submitTriggerItem() { context_manager::registerTriggerItem(SOCIAL_ST_SUBJ_MESSAGE, OPS_SUBSCRIBE, "{" @@ -48,13 +48,13 @@ void ctx::social_status_message::submit_trigger_item() NULL); } -void ctx::social_status_message::state_change_cb(msg_handle_t handle, msg_struct_t msg, void* user_data) +void ctx::SocialStatusMessage::__updateCb(msg_handle_t handle, msg_struct_t msg, void* userData) { - social_status_message *instance = static_cast(user_data); - instance->handle_state_change(msg); + SocialStatusMessage *instance = static_cast(userData); + instance->__handleUpdate(msg); } -void ctx::social_status_message::handle_state_change(msg_struct_t msg) +void ctx::SocialStatusMessage::__handleUpdate(msg_struct_t msg) { int err; int type; @@ -94,41 +94,41 @@ void ctx::social_status_message::handle_state_change(msg_struct_t msg) context_manager::publish(SOCIAL_ST_SUBJ_MESSAGE, NULL, ERR_NONE, data); } -bool ctx::social_status_message::set_callback() +bool ctx::SocialStatusMessage::__setCallback() { int err; - err = msg_open_msg_handle(&message_handle); + err = msg_open_msg_handle(&__messageHandle); IF_FAIL_RETURN_TAG(err == MSG_SUCCESS, false, _E, "Handle creation failed"); - err = msg_reg_sms_message_callback(message_handle, state_change_cb, 0, this); + err = msg_reg_sms_message_callback(__messageHandle, __updateCb, 0, this); if (err != MSG_SUCCESS) { - msg_close_msg_handle(&message_handle); + msg_close_msg_handle(&__messageHandle); _E("Setting SMS event callback failed"); return false; } - msg_reg_mms_conf_message_callback(message_handle, state_change_cb, NULL, this); + msg_reg_mms_conf_message_callback(__messageHandle, __updateCb, NULL, this); return true; } -void ctx::social_status_message::unset_callback() +void ctx::SocialStatusMessage::__unsetCallback() { - if (message_handle) - msg_close_msg_handle(&message_handle); + if (__messageHandle) + msg_close_msg_handle(&__messageHandle); - message_handle = NULL; + __messageHandle = NULL; } -int ctx::social_status_message::subscribe() +int ctx::SocialStatusMessage::subscribe() { - bool ret = set_callback(); + bool ret = __setCallback(); IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); return ERR_NONE; } -int ctx::social_status_message::unsubscribe() +int ctx::SocialStatusMessage::unsubscribe() { - unset_callback(); + __unsetCallback(); return ERR_NONE; } diff --git a/src/device/social/message.h b/src/device/social/Message.h similarity index 62% rename from src/device/social/message.h rename to src/device/social/Message.h index 5239f21..91c33b3 100644 --- a/src/device/social/message.h +++ b/src/device/social/Message.h @@ -19,31 +19,31 @@ #include #include -#include "../device_provider_base.h" +#include "../DeviceProviderBase.h" namespace ctx { - class social_status_message : public device_provider_base { + class SocialStatusMessage : public DeviceProviderBase { - GENERATE_PROVIDER_COMMON_DECL(social_status_message); + GENERATE_PROVIDER_COMMON_DECL(SocialStatusMessage); public: int subscribe(); int unsubscribe(); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); private: - msg_handle_t message_handle; - bool being_subscribed; + msg_handle_t __messageHandle; + bool __beingSubscribed; - social_status_message(); - ~social_status_message(); + SocialStatusMessage(); + ~SocialStatusMessage(); - bool set_callback(); - void unset_callback(); - void handle_state_change(msg_struct_t msg); - static void state_change_cb(msg_handle_t handle, msg_struct_t msg, void* user_data); + bool __setCallback(); + void __unsetCallback(); + void __handleUpdate(msg_struct_t msg); + static void __updateCb(msg_handle_t handle, msg_struct_t msg, void* userData); }; } diff --git a/src/device/social/social_types.h b/src/device/social/SocialTypes.h similarity index 93% rename from src/device/social/social_types.h rename to src/device/social/SocialTypes.h index 1af5fb7..82dccff 100644 --- a/src/device/social/social_types.h +++ b/src/device/social/SocialTypes.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_SOCIAL_STATUS_TYPES_INTERNAL_H__ -#define __CONTEXT_SOCIAL_STATUS_TYPES_INTERNAL_H__ +#ifndef _CONTEXT_SOCIAL_STATUS_TYPES_H_ +#define _CONTEXT_SOCIAL_STATUS_TYPES_H_ // Subject #define SOCIAL_ST_SUBJ_CALL "social/call" @@ -49,4 +49,4 @@ #define SOCIAL_ST_PERSON "Person" #define SOCIAL_ST_CHANGED "Changed" -#endif +#endif //_CONTEXT_SOCIAL_STATUS_TYPES_H diff --git a/src/device/social/call.h b/src/device/social/call.h deleted file mode 100644 index f320f5c..0000000 --- a/src/device/social/call.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _CONTEXT_SOCIAL_STATUS_CALL_H_ -#define _CONTEXT_SOCIAL_STATUS_CALL_H_ - -#include -#include "../device_provider_base.h" - -namespace ctx { - - class social_status_call : public device_provider_base { - - GENERATE_PROVIDER_COMMON_DECL(social_status_call); - - public: - int subscribe(); - int unsubscribe(); - int read(); - static bool is_supported(); - static void submit_trigger_item(); - - private: - telephony_handle_list_s handle_list; - - social_status_call(); - ~social_status_call(); - - bool init_telephony(); - void release_telephony(); - bool set_callback(); - void unset_callback(); - bool read_current_status(telephony_h& handle, ctx::Json& data); - - bool get_call_state(telephony_call_h& handle, std::string& state); - bool get_call_type(telephony_call_h& handle, std::string& type); - bool get_call_address(telephony_call_h& handle, std::string& address); - bool get_call_handle_id(telephony_call_h& handle, unsigned int& id); - - void handle_call_event(telephony_h handle, telephony_noti_e noti_id, void* id); - static void call_event_cb(telephony_h handle, telephony_noti_e noti_id, void *data, void *user_data); - }; -} - -#endif // _CONTEXT_SOCIAL_STATUS_CALL_H_ diff --git a/src/device/system/Alarm.cpp b/src/device/system/Alarm.cpp new file mode 100644 index 0000000..fc7aa10 --- /dev/null +++ b/src/device/system/Alarm.cpp @@ -0,0 +1,302 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "SystemTypes.h" +#include "Alarm.h" + +GENERATE_PROVIDER_COMMON_IMPL(DeviceStatusAlarm); + +ctx::DeviceStatusAlarm::DeviceStatusAlarm() +{ +} + +ctx::DeviceStatusAlarm::~DeviceStatusAlarm() +{ + __clear(); + + for (auto it = __optionSet.begin(); it != __optionSet.end(); ++it) { + delete *it; + } + __optionSet.clear(); +} + +bool ctx::DeviceStatusAlarm::isSupported() +{ + return true; +} + +void ctx::DeviceStatusAlarm::submitTriggerItem() +{ + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_ALARM, OPS_SUBSCRIBE, + "{" + "\"TimeOfDay\":{\"type\":\"integer\",\"min\":0,\"max\":1439}," + "\"DayOfWeek\":{\"type\":\"string\",\"values\":[\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\",\"Weekday\",\"Weekend\"]}" + "}", + NULL); +} + +int ctx::DeviceStatusAlarm::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) +{ + int ret = subscribe(option); + __destroyIfUnused(); + return ret; +} + +int ctx::DeviceStatusAlarm::unsubscribe(const char *subject, ctx::Json option) +{ + int ret = unsubscribe(option); + __destroyIfUnused(); + return ret; +} + +int ctx::DeviceStatusAlarm::read(const char *subject, ctx::Json option, ctx::Json *requestResult) +{ + __destroyIfUnused(); + return ERR_NOT_SUPPORTED; +} + +int ctx::DeviceStatusAlarm::write(const char *subject, ctx::Json data, ctx::Json *requestResult) +{ + __destroyIfUnused(); + return ERR_NOT_SUPPORTED; +} + +int ctx::DeviceStatusAlarm::subscribe(ctx::Json option) +{ + int dow = __getArrangedDayOfWeek(option); + + int time; + for (int i = 0; option.getAt(NULL, DEVICE_ST_TIME_OF_DAY, i, &time); i++) { + __add(time, dow); + } + + ctx::Json* elem = new(std::nothrow) ctx::Json(option); + if (elem) { + __optionSet.insert(elem); + } else { + unsubscribe(option); + _E("Memory allocation failed"); + return ERR_OUT_OF_MEMORY; + } + + return ERR_NONE; +} + +int ctx::DeviceStatusAlarm::unsubscribe(ctx::Json option) +{ + int dow = __getArrangedDayOfWeek(option); + + int time; + for (int i = 0; option.getAt(NULL, DEVICE_ST_TIME_OF_DAY, i, &time); i++) { + __remove(time, dow); + } + + OptionSet::iterator target = __findOption(option); + if (target != __optionSet.end()) { + delete (*target); + __optionSet.erase(target); + } + + return ERR_NONE; +} + +int ctx::DeviceStatusAlarm::__getArrangedDayOfWeek(ctx::Json& option) +{ + int dow = 0; + + std::string tempDay; + for (int i = 0; option.getAt(NULL, DEVICE_ST_DAY_OF_WEEK, i, &tempDay); i++) { + dow |= ctx::TimerManager::dowToInt(tempDay); + } + _D("Requested day of week (%#x)", dow); + + return dow; +} + +ctx::DeviceStatusAlarm::RefCountArray::RefCountArray() +{ + memset(count, 0, sizeof(int) * DAYS_PER_WEEK); +} + +int ctx::DeviceStatusAlarm::__mergeDayOfWeek(int* refCnt) +{ + int dayOfWeek = 0; + + for (int d = 0; d < DAYS_PER_WEEK; ++d) { + if (refCnt[d] > 0) { + dayOfWeek |= (0x01 << d); + } + } + + return dayOfWeek; +} + +bool ctx::DeviceStatusAlarm::__add(int minute, int dayOfWeek) +{ + IF_FAIL_RETURN_TAG(minute >=0 && minute < 1440 && + dayOfWeek > 0 && dayOfWeek <= static_cast(DayOfWeek::EVERYDAY), + false, _E, "Invalid parameter"); + + RefCountArray &ref = __refCountMap[minute]; + + for (int d = 0; d < DAYS_PER_WEEK; ++d) { + if ((dayOfWeek & (0x01 << d)) != 0) { + ref.count[d] += 1; + } + } + + return __resetTimer(minute); +} + +bool ctx::DeviceStatusAlarm::__remove(int minute, int dayOfWeek) +{ + IF_FAIL_RETURN_TAG(minute >= 0 && minute < 1440 && + dayOfWeek > 0 && dayOfWeek <= static_cast(DayOfWeek::EVERYDAY), + false, _E, "Invalid parameter"); + + RefCountArray &ref = __refCountMap[minute]; + + for (int d = 0; d < DAYS_PER_WEEK; ++d) { + if ((dayOfWeek & (0x01 << d)) != 0 && ref.count[d] > 0) { + ref.count[d] -= 1; + } + } + + return __resetTimer(minute); +} + +bool ctx::DeviceStatusAlarm::__resetTimer(int minute) +{ + int dayOfWeek = __mergeDayOfWeek(__refCountMap[minute].count); + TimerState &timer = __timerStateMap[minute]; + + if (dayOfWeek == timer.dayOfWeek) { + /* Necessary timers are already running... */ + return true; + } + + if (dayOfWeek == 0 && timer.timerId > 0) { + /* Turn off the timer at hour, if it is not necessray anymore. */ + __timerManager.remove(timer.timerId); + __timerStateMap.erase(minute); + __refCountMap.erase(minute); + return true; + } + + if (timer.timerId > 0) { + /* Turn off the current timer, to set a new one. */ + __timerManager.remove(timer.timerId); + timer.timerId = -1; + timer.dayOfWeek = 0; + } + + /* Create a new timer, w.r.t. the new dayOfWeek value. */ + int h = minute / 60; + int m = minute - h * 60; + int tid = __timerManager.setAt(h, m, static_cast(dayOfWeek), this); + IF_FAIL_RETURN_TAG(tid > 0, false, _E, "Timer setting failed"); + + timer.timerId = tid; + timer.dayOfWeek = dayOfWeek; + + return true; +} + +void ctx::DeviceStatusAlarm::__clear() +{ + for (auto it = __timerStateMap.begin(); it != __timerStateMap.end(); ++it) { + if (it->second.timerId > 0) { + __timerManager.remove(it->second.timerId); + } + } + + __timerStateMap.clear(); + __refCountMap.clear(); +} + +bool ctx::DeviceStatusAlarm::onTimerExpired(int timerId) +{ + time_t rawTime; + struct tm timeInfo; + + time(&rawTime); + tzset(); + localtime_r(&rawTime, &timeInfo); + + int hour = timeInfo.tm_hour; + int min = timeInfo.tm_min; + int dayOfWeek = (0x01 << timeInfo.tm_wday); + + __handleUpdate(hour, min, dayOfWeek); + + return true; +} + +void ctx::DeviceStatusAlarm::__handleUpdate(int hour, int min, int dayOfWeek) +{ + _I("Time: %02d:%02d, Day of Week: %#x", hour, min, dayOfWeek); + + ctx::Json dataRead; + int resultTime = hour * 60 + min; + std::string resultDay = ctx::TimerManager::dowToStr(dayOfWeek); + dataRead.set(NULL, DEVICE_ST_TIME_OF_DAY, resultTime); + dataRead.set(NULL, DEVICE_ST_DAY_OF_WEEK, resultDay); + + for (auto it = __optionSet.begin(); it != __optionSet.end(); ++it) { + ctx::Json option = (**it); + if (__isMatched(option, resultTime, resultDay)) { + context_manager::publish(DEVICE_ST_SUBJ_ALARM, option, ERR_NONE, dataRead); + } + } +} + +bool ctx::DeviceStatusAlarm::__isMatched(ctx::Json& option, int time, std::string day) +{ + bool ret = false; + int optionTime; + for (int i = 0; option.getAt(NULL, DEVICE_ST_TIME_OF_DAY, i, &optionTime); i++){ + if (time == optionTime) { + ret = true; + break; + } + } + IF_FAIL_RETURN(ret, false); + + std::string optionDay; + for (int i = 0; option.getAt(NULL, DEVICE_ST_DAY_OF_WEEK, i, &optionDay); i++){ + if (day == optionDay) { + return true; + } + } + + return false; +} + +ctx::DeviceStatusAlarm::OptionSet::iterator ctx::DeviceStatusAlarm::__findOption(ctx::Json& option) +{ + for (auto it = __optionSet.begin(); it != __optionSet.end(); ++it) { + if (option == (**it)) + return it; + } + return __optionSet.end(); +} + +void ctx::DeviceStatusAlarm::__destroyIfUnused() +{ + IF_FAIL_VOID(__optionSet.empty()); + destroy(NULL); +} diff --git a/src/device/system/Alarm.h b/src/device/system/Alarm.h new file mode 100644 index 0000000..0ae4fce --- /dev/null +++ b/src/device/system/Alarm.h @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _DEVICE_SYSTEM_STATUS_ALARM_H_ +#define _DEVICE_SYSTEM_STATUS_ALARM_H_ + +#include +#include +#include +#include +#include "../DeviceProviderBase.h" + +namespace ctx { + + class DeviceStatusAlarm : public ContextProviderBase, ITimerListener { + + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusAlarm); + + public: + int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); + int unsubscribe(const char *subject, ctx::Json option); + int read(const char *subject, ctx::Json option, ctx::Json *requestResult); + int write(const char *subject, ctx::Json data, ctx::Json *requestResult); + + int subscribe(ctx::Json option); + int unsubscribe(ctx::Json option); + static bool isSupported(); + static void submitTriggerItem(); + + protected: + bool onTimerExpired(int timerId); + + private: + DeviceStatusAlarm(); + ~DeviceStatusAlarm(); + + struct RefCountArray { + int count[7]; /* reference counts for days of week*/ + RefCountArray(); + }; + + struct TimerState { + int timerId; + int dayOfWeek; /* day of week, merged into one integer */ + TimerState() : timerId(-1), dayOfWeek(0) {} + }; + + typedef std::map RefCountMap; + typedef std::map TimerStateMap; + typedef std::set OptionSet; + + RefCountMap __refCountMap; + TimerStateMap __timerStateMap; + OptionSet __optionSet; + TimerManager __timerManager; + + bool __add(int minute, int dayOfWeek); + bool __remove(int minute, int dayOfWeek); + bool __resetTimer(int hour); + void __clear(); + void __handleUpdate(int hour, int min, int dayOfWeek); + + int __getArrangedDayOfWeek(ctx::Json& option); + int __mergeDayOfWeek(int *refCnt); + + bool __isMatched(ctx::Json& option, int time, std::string day); + OptionSet::iterator __findOption(ctx::Json& option); + + void __destroyIfUnused(); + + }; +} + +#endif // _DEVICE_SYSTEM_STATUS_ALARM_H_ diff --git a/src/device/system/battery.cpp b/src/device/system/Battery.cpp similarity index 54% rename from src/device/system/battery.cpp rename to src/device/system/Battery.cpp index 6207db9..8313333 100644 --- a/src/device/system/battery.cpp +++ b/src/device/system/Battery.cpp @@ -15,25 +15,25 @@ */ #include -#include "system_types.h" -#include "battery.h" +#include "SystemTypes.h" +#include "Battery.h" -GENERATE_PROVIDER_COMMON_IMPL(device_status_battery); +GENERATE_PROVIDER_COMMON_IMPL(DeviceStatusBattery); -ctx::device_status_battery::device_status_battery() +ctx::DeviceStatusBattery::DeviceStatusBattery() { } -ctx::device_status_battery::~device_status_battery() +ctx::DeviceStatusBattery::~DeviceStatusBattery() { } -bool ctx::device_status_battery::is_supported() +bool ctx::DeviceStatusBattery::isSupported() { return true; } -void ctx::device_status_battery::submit_trigger_item() +void ctx::DeviceStatusBattery::submitTriggerItem() { context_manager::registerTriggerItem(DEVICE_ST_SUBJ_BATTERY, OPS_SUBSCRIBE | OPS_READ, "{" @@ -43,33 +43,33 @@ void ctx::device_status_battery::submit_trigger_item() NULL); } -void ctx::device_status_battery::update_cb(device_callback_e device_type, void* value, void* user_data) +void ctx::DeviceStatusBattery::__updateCb(device_callback_e deviceType, void* value, void* userData) { - IF_FAIL_VOID(device_type == DEVICE_CALLBACK_BATTERY_LEVEL); + IF_FAIL_VOID(deviceType == DEVICE_CALLBACK_BATTERY_LEVEL); - device_status_battery *instance = static_cast(user_data); - instance->handle_update(device_type, value); + DeviceStatusBattery *instance = static_cast(userData); + instance->__handleUpdate(deviceType, value); } -void ctx::device_status_battery::handle_update(device_callback_e device_type, void* value) +void ctx::DeviceStatusBattery::__handleUpdate(device_callback_e deviceType, void* value) { intptr_t level = (intptr_t)value; - const char* level_string = trans_to_string(level); - IF_FAIL_VOID(level_string); + const char* levelString = __transToString(level); + IF_FAIL_VOID(levelString); ctx::Json dataRead; - dataRead.set(NULL, DEVICE_ST_LEVEL, level_string); + dataRead.set(NULL, DEVICE_ST_LEVEL, levelString); - bool charging_state = false; - int ret = device_battery_is_charging(&charging_state); + bool chargingState = false; + int ret = device_battery_is_charging(&chargingState); IF_FAIL_VOID_TAG(ret == DEVICE_ERROR_NONE, _E, "Getting state failed"); - dataRead.set(NULL, DEVICE_ST_IS_CHARGING, charging_state ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + dataRead.set(NULL, DEVICE_ST_IS_CHARGING, chargingState ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); ctx::context_manager::publish(DEVICE_ST_SUBJ_BATTERY, NULL, ERR_NONE, dataRead); } -const char* ctx::device_status_battery::trans_to_string(intptr_t level) +const char* ctx::DeviceStatusBattery::__transToString(intptr_t level) { switch (level) { case DEVICE_BATTERY_LEVEL_EMPTY: @@ -85,17 +85,17 @@ const char* ctx::device_status_battery::trans_to_string(intptr_t level) return DEVICE_ST_NORMAL; case DEVICE_BATTERY_LEVEL_FULL: - { - int percent; - device_battery_get_percent(&percent); - - if (percent == 100) { - return DEVICE_ST_FULL; - } else { - return DEVICE_ST_HIGH; - } + { + int percent; + device_battery_get_percent(&percent); + + if (percent == 100) { + return DEVICE_ST_FULL; + } else { + return DEVICE_ST_HIGH; } break; + } default: _E("Invalid battery level"); @@ -103,21 +103,21 @@ const char* ctx::device_status_battery::trans_to_string(intptr_t level) } } -int ctx::device_status_battery::subscribe() +int ctx::DeviceStatusBattery::subscribe() { - int ret = device_add_callback(DEVICE_CALLBACK_BATTERY_LEVEL, update_cb, this); + int ret = device_add_callback(DEVICE_CALLBACK_BATTERY_LEVEL, __updateCb, this); IF_FAIL_RETURN(ret == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED); return ERR_NONE; } -int ctx::device_status_battery::unsubscribe() +int ctx::DeviceStatusBattery::unsubscribe() { - int ret = device_remove_callback(DEVICE_CALLBACK_BATTERY_LEVEL, update_cb); + int ret = device_remove_callback(DEVICE_CALLBACK_BATTERY_LEVEL, __updateCb); IF_FAIL_RETURN(ret == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED); return ERR_NONE; } -int ctx::device_status_battery::read() +int ctx::DeviceStatusBattery::read() { device_battery_level_e level; ctx::Json dataRead; @@ -125,16 +125,16 @@ int ctx::device_status_battery::read() int ret = device_battery_get_level_status(&level); IF_FAIL_RETURN(ret == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED); - const char* level_string = trans_to_string(level); - IF_FAIL_RETURN(level_string, ERR_OPERATION_FAILED); + const char* levelString = __transToString(level); + IF_FAIL_RETURN(levelString, ERR_OPERATION_FAILED); - dataRead.set(NULL, DEVICE_ST_LEVEL, level_string); + dataRead.set(NULL, DEVICE_ST_LEVEL, levelString); - bool charging_state = false; - ret = device_battery_is_charging(&charging_state); + bool chargingState = false; + ret = device_battery_is_charging(&chargingState); IF_FAIL_RETURN(ret == DEVICE_ERROR_NONE, ERR_OPERATION_FAILED); - dataRead.set(NULL, DEVICE_ST_IS_CHARGING, charging_state ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + dataRead.set(NULL, DEVICE_ST_IS_CHARGING, chargingState ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_BATTERY, NULL, ERR_NONE, dataRead); return ERR_NONE; diff --git a/src/device/system/battery.h b/src/device/system/Battery.h similarity index 56% rename from src/device/system/battery.h rename to src/device/system/Battery.h index 8f8a723..cbc11ba 100644 --- a/src/device/system/battery.h +++ b/src/device/system/Battery.h @@ -14,33 +14,33 @@ * limitations under the License. */ -#ifndef _DEVICE_STATUS_BATTERY_LEVEL_H_ -#define _DEVICE_STATUS_BATTERY_LEVEL_H_ +#ifndef _DEVICE_SYSTEM_STATUS_BATTERY_H_ +#define _DEVICE_SYSTEM_STATUS_BATTERY_H_ #include #include -#include "../device_provider_base.h" +#include "../DeviceProviderBase.h" namespace ctx { - class device_status_battery : public device_provider_base { + class DeviceStatusBattery : public DeviceProviderBase { - GENERATE_PROVIDER_COMMON_DECL(device_status_battery); + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusBattery); public: int subscribe(); int unsubscribe(); int read(); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); private: - device_status_battery(); - ~device_status_battery(); - const char* trans_to_string(intptr_t level); - void handle_update(device_callback_e device_type, void* value); - static void update_cb(device_callback_e device_type, void* value, void* user_data); + DeviceStatusBattery(); + ~DeviceStatusBattery(); + const char* __transToString(intptr_t level); + void __handleUpdate(device_callback_e deviceType, void* value); + static void __updateCb(device_callback_e deviceType, void* value, void* userData); }; } -#endif // _DEVICE_STATUS_BATTERY_LEVEL_H_ +#endif // _DEVICE_SYSTEM_STATUS_BATTERY_H_ diff --git a/src/device/system/Headphone.cpp b/src/device/system/Headphone.cpp new file mode 100644 index 0000000..3ec1281 --- /dev/null +++ b/src/device/system/Headphone.cpp @@ -0,0 +1,238 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "SystemTypes.h" +#include "Headphone.h" + +#define HANDLING_DELAY 2000 +#define MAX_HANDLING_COUNT 3 + +GENERATE_PROVIDER_COMMON_IMPL(DeviceStatusHeadphone); + +ctx::DeviceStatusHeadphone::DeviceStatusHeadphone() : + __connected(false), + __audioJackState(RUNTIME_INFO_AUDIO_JACK_STATUS_UNCONNECTED), + __btAudioState(false), + __btAudioCallbackOn(false), + __btEventHandlerAdded(false), + __btEventHandlingCount(0) +{ +} + +ctx::DeviceStatusHeadphone::~DeviceStatusHeadphone() +{ +} + +bool ctx::DeviceStatusHeadphone::isSupported() +{ + return true; +} + +void ctx::DeviceStatusHeadphone::submitTriggerItem() +{ + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_HEADPHONE, OPS_SUBSCRIBE | OPS_READ, + "{" + TRIG_BOOL_ITEM_DEF("IsConnected") "," + "\"Type\":{\"type\":\"string\",\"values\":[\"Normal\",\"Headset\",\"Bluetooth\"]}" + "}", + NULL); +} + +int ctx::DeviceStatusHeadphone::subscribe() +{ + __connected = __getCurrentStatus(); + + // Wired headphone + int ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, __onAudioJackStateChanged, this); + IF_FAIL_RETURN(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED); + + // Bluetooth headphone + __setBtAudioCallback(); + + return ERR_NONE; +} + +int ctx::DeviceStatusHeadphone::unsubscribe() +{ + runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS); + __unsetBtAudioCallback(); + + return ERR_NONE; +} + +int ctx::DeviceStatusHeadphone::read() +{ + if (!__beingSubscribed) + __connected = __getCurrentStatus(); + + Json data; + __generateDataPacket(&data); + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_HEADPHONE, NULL, ERR_NONE, data); + + return ERR_NONE; +} + +void ctx::DeviceStatusHeadphone::__setBtAudioCallback() +{ + IF_FAIL_VOID(!__btAudioCallbackOn); + int ret; + + ret = bt_initialize(); + if (ret != BT_ERROR_NONE) { + _W("Bluetooth initialization failed"); + return; + } + + ret = bt_device_set_connection_state_changed_cb(__onBtConnectionChanged, this); + if (ret != BT_ERROR_NONE) { + bt_deinitialize(); + return; + } + + __btAudioCallbackOn = true; +} + +void ctx::DeviceStatusHeadphone::__unsetBtAudioCallback() +{ + IF_FAIL_VOID(__btAudioCallbackOn); + + bt_device_unset_connection_state_changed_cb(); + bt_deinitialize(); + + __btAudioCallbackOn = false; +} + +void ctx::DeviceStatusHeadphone::__setBtAudioState(bool state) +{ + __btAudioState = state; +} + +bool ctx::DeviceStatusHeadphone::__getCurrentStatus() +{ + int ret; + + // Wired audio + ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, &__audioJackState); + IF_FAIL_RETURN(ret == ERR_NONE, __connected); + + // Bluetooth audio + __btAudioState = false; + ret = bt_initialize(); + if (ret == BT_ERROR_NONE) { + bt_adapter_foreach_bonded_device(__onBtBond, this); + bt_deinitialize(); + } + + return ((__audioJackState != RUNTIME_INFO_AUDIO_JACK_STATUS_UNCONNECTED) || __btAudioState); +} + +void ctx::DeviceStatusHeadphone::__generateDataPacket(ctx::Json* data) +{ + data->set(NULL, DEVICE_ST_IS_CONNECTED, __connected ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + + switch (__audioJackState) { + case RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_3WIRE: + data->set(NULL, DEVICE_ST_TYPE, DEVICE_ST_NORMAL); + break; + case RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_4WIRE: + data->set(NULL, DEVICE_ST_TYPE, DEVICE_ST_HEADSET); + break; + default: + if (__btAudioState) + data->set(NULL, DEVICE_ST_TYPE, DEVICE_ST_BLUETOOTH); + break; + } +} + +bool ctx::DeviceStatusHeadphone::__handleUpdate() +{ + bool prevState = __connected; + __connected = ((__audioJackState != RUNTIME_INFO_AUDIO_JACK_STATUS_UNCONNECTED) || __btAudioState); + + IF_FAIL_RETURN(prevState != __connected, false); + + ctx::Json data; + __generateDataPacket(&data); + ctx::context_manager::publish(DEVICE_ST_SUBJ_HEADPHONE, NULL, ERR_NONE, data); + return true; +} + +void ctx::DeviceStatusHeadphone::__handleAudioJackEvent() +{ + int ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, &__audioJackState); + IF_FAIL_VOID_TAG(ret == ERR_NONE, _E, "Getting runtime info failed"); + __handleUpdate(); +} + +void ctx::DeviceStatusHeadphone::__onAudioJackStateChanged(runtime_info_key_e runtimeKey, void* userData) +{ + _D("EarJack"); + ctx::DeviceStatusHeadphone *instance = static_cast(userData); + instance->__handleAudioJackEvent(); +} + +void ctx::DeviceStatusHeadphone::__onBtConnectionChanged(bool connected, bt_device_connection_info_s *connInfo, void *userData) +{ + ctx::DeviceStatusHeadphone *instance = static_cast(userData); + IF_FAIL_VOID(connected != instance->__btAudioState); + IF_FAIL_VOID(!instance->__btEventHandlerAdded); + + if (connected) { + _D("BT state checking scheduled"); + instance->__btEventHandlerAdded = true; + instance->__btEventHandlingCount = 0; + g_timeout_add(HANDLING_DELAY, __handleBtEvent, userData); + } else { + __handleBtEvent(userData); + } +} + +gboolean ctx::DeviceStatusHeadphone::__handleBtEvent(gpointer data) +{ + _D("BT state checking started"); + ctx::DeviceStatusHeadphone *instance = static_cast(data); + instance->__btEventHandlerAdded = false; + + instance->__setBtAudioState(false); + int err = bt_adapter_foreach_bonded_device(__onBtBond, data); + IF_FAIL_RETURN_TAG(err == BT_ERROR_NONE, FALSE, _E, "bt_adapter_foreach_bonded_device() failed"); + + instance->__btEventHandlingCount++; + + if (instance->__handleUpdate() || instance->__btEventHandlingCount >= MAX_HANDLING_COUNT) + return FALSE; + + return TRUE; +} + +bool ctx::DeviceStatusHeadphone::__onBtBond(bt_device_info_s *deviceInfo, void* userData) +{ + if (deviceInfo->bt_class.major_device_class != BT_MAJOR_DEVICE_CLASS_AUDIO_VIDEO) + return true; + + bool st = false; + int err = bt_device_is_profile_connected(deviceInfo->remote_address, BT_PROFILE_A2DP, &st); + IF_FAIL_RETURN_TAG(err == BT_ERROR_NONE, false, _E, "bt_device_is_profile_connected() failed"); + + if (st) { + ctx::DeviceStatusHeadphone *instance = static_cast(userData); + instance->__setBtAudioState(true); + return false; + } + + return true; +} diff --git a/src/device/system/Headphone.h b/src/device/system/Headphone.h new file mode 100644 index 0000000..394a6d9 --- /dev/null +++ b/src/device/system/Headphone.h @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _DEVICE_SYSTEM_STATUS_HEADPHONE_H_ +#define _DEVICE_STATUS_HEADPNOHE_H_ + +#include +#include +#include +#include "../DeviceProviderBase.h" + +namespace ctx { + + class DeviceStatusHeadphone : public DeviceProviderBase { + + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusHeadphone); + + public: + int subscribe(); + int unsubscribe(); + int read(); + static bool isSupported(); + static void submitTriggerItem(); + + private: + bool __connected; + int __audioJackState; + bool __btAudioState; + bool __btAudioCallbackOn; + bool __btEventHandlerAdded; + int __btEventHandlingCount; + + DeviceStatusHeadphone(); + ~DeviceStatusHeadphone(); + + bool __getCurrentStatus(); + void __setBtAudioCallback(); + void __unsetBtAudioCallback(); + void __setBtAudioState(bool state); + + void __generateDataPacket(Json* data); + bool __handleUpdate(); + void __handleAudioJackEvent(); + static gboolean __handleBtEvent(gpointer data); + + static void __onAudioJackStateChanged(runtime_info_key_e runtimeKey, void* userData); + static void __onBtConnectionChanged(bool connected, bt_device_connection_info_s *connInfo, void *userData); + static bool __onBtBond(bt_device_info_s *deviceInfo, void* userData); + }; +} + +#endif // _DEVICE_SYSTEM_STATUS_HEADPHONE_H_ diff --git a/src/device/system/psmode.cpp b/src/device/system/Psmode.cpp similarity index 66% rename from src/device/system/psmode.cpp rename to src/device/system/Psmode.cpp index dc39f98..894faf0 100644 --- a/src/device/system/psmode.cpp +++ b/src/device/system/Psmode.cpp @@ -15,37 +15,37 @@ */ #include -#include "system_types.h" -#include "psmode.h" +#include "SystemTypes.h" +#include "Psmode.h" -GENERATE_PROVIDER_COMMON_IMPL(device_status_psmode); +GENERATE_PROVIDER_COMMON_IMPL(DeviceStatusPsmode); -ctx::device_status_psmode::device_status_psmode() +ctx::DeviceStatusPsmode::DeviceStatusPsmode() { } -ctx::device_status_psmode::~device_status_psmode() +ctx::DeviceStatusPsmode::~DeviceStatusPsmode() { } -bool ctx::device_status_psmode::is_supported() +bool ctx::DeviceStatusPsmode::isSupported() { return true; } -void ctx::device_status_psmode::submit_trigger_item() +void ctx::DeviceStatusPsmode::submitTriggerItem() { context_manager::registerTriggerItem(DEVICE_ST_SUBJ_PSMODE, OPS_SUBSCRIBE | OPS_READ, "{" TRIG_BOOL_ITEM_DEF("IsEnabled") "}", NULL); } -void ctx::device_status_psmode::update_cb(keynode_t *node, void* user_data) +void ctx::DeviceStatusPsmode::__updateCb(keynode_t *node, void* userData) { - device_status_psmode *instance = static_cast(user_data); - instance->handle_update(node); + DeviceStatusPsmode *instance = static_cast(userData); + instance->__handleUpdate(node); } -void ctx::device_status_psmode::handle_update(keynode_t *node) +void ctx::DeviceStatusPsmode::__handleUpdate(keynode_t *node) { int status; ctx::Json dataRead; @@ -58,21 +58,21 @@ void ctx::device_status_psmode::handle_update(keynode_t *node) context_manager::publish(DEVICE_ST_SUBJ_PSMODE, NULL, ERR_NONE, dataRead); } -int ctx::device_status_psmode::subscribe() +int ctx::DeviceStatusPsmode::subscribe() { - int ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_PSMODE, update_cb, this); + int ret = vconf_notify_key_changed(VCONFKEY_SETAPPL_PSMODE, __updateCb, this); IF_FAIL_RETURN(ret == VCONF_OK, ERR_OPERATION_FAILED); return ERR_NONE; } -int ctx::device_status_psmode::unsubscribe() +int ctx::DeviceStatusPsmode::unsubscribe() { - int ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_PSMODE, update_cb); + int ret = vconf_ignore_key_changed(VCONFKEY_SETAPPL_PSMODE, __updateCb); IF_FAIL_RETURN(ret == VCONF_OK, ERR_OPERATION_FAILED); return ERR_NONE; } -int ctx::device_status_psmode::read() +int ctx::DeviceStatusPsmode::read() { int mode; int ret = vconf_get_int(VCONFKEY_SETAPPL_PSMODE, &mode); diff --git a/src/device/system/psmode.h b/src/device/system/Psmode.h similarity index 58% rename from src/device/system/psmode.h rename to src/device/system/Psmode.h index 1d4e4f3..d18201e 100644 --- a/src/device/system/psmode.h +++ b/src/device/system/Psmode.h @@ -14,31 +14,31 @@ * limitations under the License. */ -#ifndef _DEVICE_STATUS_POWER_SAVING_MODE_H_ -#define _DEVICE_STATUS_POWER_SAVING_MODE_H_ +#ifndef _DEVICE_SYSTEM_STATUS_POWER_SAVING_MODE_H_ +#define _DEVICE_SYSTEM_STATUS_POWER_SAVING_MODE_H_ #include -#include "../device_provider_base.h" +#include "../DeviceProviderBase.h" namespace ctx { - class device_status_psmode : public device_provider_base { + class DeviceStatusPsmode : public DeviceProviderBase { - GENERATE_PROVIDER_COMMON_DECL(device_status_psmode); + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusPsmode); public: int subscribe(); int unsubscribe(); int read(); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); private: - device_status_psmode(); - ~device_status_psmode(); - void handle_update(keynode_t *node); - static void update_cb(keynode_t *node, void* user_data); + DeviceStatusPsmode(); + ~DeviceStatusPsmode(); + void __handleUpdate(keynode_t *node); + static void __updateCb(keynode_t *node, void* userData); }; } -#endif // _DEVICE_STATUS_POWER_SAVING_H_ +#endif // _DEVICE_SYSTEM_STATUS_POWER_SAVING_MODE_H_ diff --git a/src/device/system/system_types.h b/src/device/system/SystemTypes.h similarity index 94% rename from src/device/system/system_types.h rename to src/device/system/SystemTypes.h index 2faa361..3129a36 100644 --- a/src/device/system/system_types.h +++ b/src/device/system/SystemTypes.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_DEVICESTATUS_TYPES_H__ -#define __CONTEXT_DEVICESTATUS_TYPES_H__ +#ifndef _DEVICE_SYSTEM_STATUS_TYPES_H_ +#define _DEVICE_SYSTEM_STATUS_TYPES_H_ // Subject #define DEVICE_ST_SUBJ_BATTERY "system/battery" @@ -62,4 +62,4 @@ #define TRIG_BOOL_ITEM_DEF(sbj) "\"" sbj "\":{\"type\":\"integer\",\"min\":0,\"max\":1}" -#endif //__CONTEXT_DEVICESTATUS_TYPES_H__ +#endif //_DEVICE_SYSTEM_STATUS_TYPES_H_ diff --git a/src/device/system/time.cpp b/src/device/system/Time.cpp similarity index 57% rename from src/device/system/time.cpp rename to src/device/system/Time.cpp index 6cd5ea0..af3ded1 100644 --- a/src/device/system/time.cpp +++ b/src/device/system/Time.cpp @@ -16,25 +16,25 @@ #include #include -#include "system_types.h" -#include "time.h" +#include "SystemTypes.h" +#include "Time.h" -GENERATE_PROVIDER_COMMON_IMPL(device_status_time); +GENERATE_PROVIDER_COMMON_IMPL(DeviceStatusTime); -ctx::device_status_time::device_status_time() +ctx::DeviceStatusTime::DeviceStatusTime() { } -ctx::device_status_time::~device_status_time() +ctx::DeviceStatusTime::~DeviceStatusTime() { } -bool ctx::device_status_time::is_supported() +bool ctx::DeviceStatusTime::isSupported() { return true; } -void ctx::device_status_time::submit_trigger_item() +void ctx::DeviceStatusTime::submitTriggerItem() { context_manager::registerTriggerItem(DEVICE_ST_SUBJ_TIME, OPS_READ, "{" @@ -45,35 +45,35 @@ void ctx::device_status_time::submit_trigger_item() NULL); } -int ctx::device_status_time::subscribe() +int ctx::DeviceStatusTime::subscribe() { return ERR_NOT_SUPPORTED; } -int ctx::device_status_time::unsubscribe() +int ctx::DeviceStatusTime::unsubscribe() { return ERR_NOT_SUPPORTED; } -int ctx::device_status_time::read() +int ctx::DeviceStatusTime::read() { time_t rawtime; - struct tm timeinfo; + struct tm timeInfo; time(&rawtime); tzset(); - localtime_r(&rawtime, &timeinfo); + localtime_r(&rawtime, &timeInfo); - int day_of_month = timeinfo.tm_mday; - int minute_of_day = timeinfo.tm_hour * 60 + timeinfo.tm_min; - std::string day_of_week = ctx::TimerManager::dowToStr(0x01 << timeinfo.tm_wday); + int dayOfMonth = timeInfo.tm_mday; + int minuteOfDay = timeInfo.tm_hour * 60 + timeInfo.tm_min; + std::string dayOfWeek = ctx::TimerManager::dowToStr(0x01 << timeInfo.tm_wday); ctx::Json dataRead; - dataRead.set(NULL, DEVICE_ST_DAY_OF_MONTH, day_of_month); - dataRead.set(NULL, DEVICE_ST_DAY_OF_WEEK, day_of_week); - dataRead.set(NULL, DEVICE_ST_TIME_OF_DAY, minute_of_day); + dataRead.set(NULL, DEVICE_ST_DAY_OF_MONTH, dayOfMonth); + dataRead.set(NULL, DEVICE_ST_DAY_OF_WEEK, dayOfWeek); + dataRead.set(NULL, DEVICE_ST_TIME_OF_DAY, minuteOfDay); - _I("Time: %02d:%02d, Day of Week: %s, Day of Month: %d", timeinfo.tm_hour, timeinfo.tm_min, day_of_week.c_str(), day_of_month); + _I("Time: %02d:%02d, Day of Week: %s, Day of Month: %d", timeInfo.tm_hour, timeInfo.tm_min, dayOfWeek.c_str(), dayOfMonth); ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_TIME, NULL, ERR_NONE, dataRead); diff --git a/src/device/system/time.h b/src/device/system/Time.h similarity index 66% rename from src/device/system/time.h rename to src/device/system/Time.h index 7d44bec..2a97993 100644 --- a/src/device/system/time.h +++ b/src/device/system/Time.h @@ -14,28 +14,28 @@ * limitations under the License. */ -#ifndef _DEVICE_STATUS_TIME_H_ -#define _DEVICE_STATUS_TIME_H_ +#ifndef _DEVICE_SYSTEM_STATUS_TIME_H_ +#define _DEVICE_SYSTEM_STATUS_TIME_H_ -#include "../device_provider_base.h" +#include "../DeviceProviderBase.h" namespace ctx { - class device_status_time : public device_provider_base { + class DeviceStatusTime : public DeviceProviderBase { - GENERATE_PROVIDER_COMMON_DECL(device_status_time); + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusTime); public: int subscribe(); int unsubscribe(); int read(); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); private: - device_status_time(); - ~device_status_time(); + DeviceStatusTime(); + ~DeviceStatusTime(); }; } -#endif // _DEVICE_STATUS_TIME_H_ +#endif // _DEVICE_SYSTEM_STATUS_TIME_H_ diff --git a/src/device/system/Wifi.cpp b/src/device/system/Wifi.cpp new file mode 100644 index 0000000..e3a8a3a --- /dev/null +++ b/src/device/system/Wifi.cpp @@ -0,0 +1,266 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "SystemTypes.h" +#include "Wifi.h" + +ctx::DeviceStatusWifi *ctx::DeviceStatusWifi::__instance = NULL; + +ctx::DeviceStatusWifi::DeviceStatusWifi() : + __lastState(UNKNOWN), + __isInitialized(false), + __isActivated(false), + __connState(WIFI_CONNECTION_STATE_FAILURE) +{ + IF_FAIL_VOID_TAG(__startMonitor(), _W, "WiFi monitor initialization failed"); + + if (!__getCurrentState()) { + __stopMonitor(); + _W("Getting current WiFi status failed"); + } +} + +ctx::DeviceStatusWifi::~DeviceStatusWifi() +{ +} + +ctx::ContextProviderBase *ctx::DeviceStatusWifi::create(void *data) +{ + CREATE_INSTANCE(DeviceStatusWifi); +} + +void ctx::DeviceStatusWifi::destroy(void *data) +{ + __instance->__stopMonitor(); + DESTROY_INSTANCE(); +} + +void ctx::DeviceStatusWifi::destroySelf() +{ + /* WiFi status will be monitored continuously, even if no client is subscribing it */ +} + +bool ctx::DeviceStatusWifi::isSupported() +{ + return getSystemInfoBool("tizen.org/feature/network.wifi"); +} + +void ctx::DeviceStatusWifi::submitTriggerItem() +{ + context_manager::registerTriggerItem(DEVICE_ST_SUBJ_WIFI, OPS_SUBSCRIBE | OPS_READ, + "{" + "\"State\":{\"type\":\"string\",\"values\":[\"Disabled\",\"Unconnected\",\"Connected\"]}," + "\"BSSID\":{\"type\":\"string\"}" + "}", + NULL); +} + +bool ctx::DeviceStatusWifi::__getCurrentState() +{ + int err; + + if (!__isInitialized) { + err = wifi_initialize(); + IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_initialize() failed"); + } + + err = wifi_is_activated(&__isActivated); + IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_is_activated() failed"); + + err = wifi_get_connection_state(&__connState); + IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_get_connection_state() failed"); + + if (__isActivated) { + if (__connState == WIFI_CONNECTION_STATE_CONNECTED) { + __lastState = CONNECTED; + __getBssid(); + } else { + __lastState = UNCONNECTED; + __clearBssid(); + } + } else { + __lastState = DISABLED; + __clearBssid(); + } + + if (!__isInitialized) + wifi_deinitialize(); + + return true; +} + +bool ctx::DeviceStatusWifi::__getBssid() +{ + int err; + char *strBuf = NULL; + wifi_ap_h ap = NULL; + + err = wifi_get_connected_ap(&ap); + IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_get_connected_ap() failed"); + + wifi_ap_get_bssid(ap, &strBuf); + __bssid = (strBuf != NULL ? strBuf : ""); + g_free(strBuf); + + wifi_ap_destroy(ap); + + if (__bssid.empty()) + _W("Failed to get BSSID"); + + SharedVars().set(ctx::SharedVars::WIFI_BSSID, __bssid); + _D("BSSID: %s", __bssid.c_str()); + + return !__bssid.empty(); +} + +void ctx::DeviceStatusWifi::__clearBssid() +{ + __bssid.clear(); + SharedVars().clear(ctx::SharedVars::WIFI_BSSID); + _D("No WiFi connection"); +} + +bool ctx::DeviceStatusWifi::__getResponsePacket(ctx::Json* data) +{ + switch (__lastState) { + case DISABLED: + data->set(NULL, DEVICE_ST_STATE, DEVICE_ST_DISABLED); + break; + + case UNCONNECTED: + data->set(NULL, DEVICE_ST_STATE, DEVICE_ST_UNCONNECTED); + break; + + case CONNECTED: + data->set(NULL, DEVICE_ST_STATE, DEVICE_ST_CONNECTED); + data->set(NULL, DEVICE_ST_BSSID, __bssid); + break; + + default: + return false; + } + + return true; +} + +int ctx::DeviceStatusWifi::read() +{ + IF_FAIL_RETURN(__getCurrentState(), ERR_OPERATION_FAILED); + + ctx::Json dataRead; + if (__getResponsePacket(&dataRead)) { + ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_WIFI, NULL, ERR_NONE, dataRead); + return ERR_NONE; + } + + return ERR_OPERATION_FAILED; +} + +bool ctx::DeviceStatusWifi::__startMonitor() +{ + IF_FAIL_RETURN(!__isInitialized, true); + + int err; + err = wifi_initialize(); + IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_initialize() failed"); + + err = wifi_set_device_state_changed_cb(__deviceStateChangedCb, this); + IF_FAIL_CATCH_TAG(err == WIFI_ERROR_NONE, _E, "wifi_set_device_state_changed_cb() failed"); + + err = wifi_set_connection_state_changed_cb(__connectionStateChangedCb, this); + IF_FAIL_CATCH_TAG(err == WIFI_ERROR_NONE, _E, "wifi_set_connection_state_changed_cb() failed"); + + __isInitialized = true; + return true; + +CATCH: + wifi_deinitialize(); + return false; +} + +void ctx::DeviceStatusWifi::__stopMonitor() +{ + IF_FAIL_VOID(__isInitialized); + + wifi_unset_device_state_changed_cb(); + wifi_unset_connection_state_changed_cb(); + wifi_deinitialize(); + __isInitialized = false; +} + +int ctx::DeviceStatusWifi::subscribe() +{ +#if 0 + IF_FAIL_RETURN(__startMonitor(), ERR_OPERATION_FAILED); + if (!__getCurrentState()) { + __stopMonitor(); + return ERR_OPERATION_FAILED; + } +#endif + + return ERR_NONE; +} + +int ctx::DeviceStatusWifi::unsubscribe() +{ +#if 0 + __stopMonitor(); +#endif + return ERR_NONE; +} + +void ctx::DeviceStatusWifi::__handleUpdate() +{ + int prevState = __lastState; + + if (__isActivated) { + if (__connState == WIFI_CONNECTION_STATE_CONNECTED) { + __lastState = CONNECTED; + } else { + __lastState = UNCONNECTED; + } + } else { + __lastState = DISABLED; + } + + if (__lastState != prevState) { + if (__lastState == CONNECTED) { + __getBssid(); + } else { + __clearBssid(); + } + + ctx::Json data; + if (__beingSubscribed && __getResponsePacket(&data)) + context_manager::publish(DEVICE_ST_SUBJ_WIFI, NULL, ERR_NONE, data); + } +} + +void ctx::DeviceStatusWifi::__deviceStateChangedCb(wifi_device_state_e state, void *userData) +{ + DeviceStatusWifi *instance = static_cast(userData); + instance->__isActivated = (state == WIFI_DEVICE_STATE_ACTIVATED); + instance->__handleUpdate(); +} + +void ctx::DeviceStatusWifi::__connectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *userData) +{ + DeviceStatusWifi *instance = static_cast(userData); + instance->__connState = state; + instance->__handleUpdate(); +} diff --git a/src/device/system/Wifi.h b/src/device/system/Wifi.h new file mode 100644 index 0000000..59b721d --- /dev/null +++ b/src/device/system/Wifi.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _DEVICE_SYSTEM_STATUS_WIFI_H_ +#define _DEVICE_SYSTEM_STATUS_WIFI_H_ + +#include +#include +#include "../DeviceProviderBase.h" + +namespace ctx { + + class DeviceStatusWifi : public DeviceProviderBase { + + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusWifi); + + public: + int subscribe(); + int unsubscribe(); + int read(); + static bool isSupported(); + static void submitTriggerItem(); + + private: + enum InternalState { + UNKNOWN = -1, + DISABLED = 0, + UNCONNECTED, + CONNECTED, + }; + + int __lastState; + bool __isInitialized; + bool __isActivated; + wifi_connection_state_e __connState; + std::string __bssid; + + DeviceStatusWifi(); + ~DeviceStatusWifi(); + + bool __getCurrentState(); + bool __getBssid(); + void __clearBssid(); + bool __getResponsePacket(Json* data); + void __handleUpdate(); + bool __startMonitor(); + void __stopMonitor(); + static void __deviceStateChangedCb(wifi_device_state_e state, void *userData); + static void __connectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *userData); + }; +} + +#endif // _CONTEXT_SYSTEM_STATUS_WIFI_H_ diff --git a/src/device/system/alarm.cpp b/src/device/system/alarm.cpp deleted file mode 100644 index d4434a9..0000000 --- a/src/device/system/alarm.cpp +++ /dev/null @@ -1,302 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "system_types.h" -#include "alarm.h" - -GENERATE_PROVIDER_COMMON_IMPL(device_status_alarm); - -ctx::device_status_alarm::device_status_alarm() -{ -} - -ctx::device_status_alarm::~device_status_alarm() -{ - clear(); - - for (ctx::device_status_alarm::option_t::iterator it = option_set.begin(); it != option_set.end(); ++it) { - delete *it; - } - option_set.clear(); -} - -bool ctx::device_status_alarm::is_supported() -{ - return true; -} - -void ctx::device_status_alarm::submit_trigger_item() -{ - context_manager::registerTriggerItem(DEVICE_ST_SUBJ_ALARM, OPS_SUBSCRIBE, - "{" - "\"TimeOfDay\":{\"type\":\"integer\",\"min\":0,\"max\":1439}," - "\"DayOfWeek\":{\"type\":\"string\",\"values\":[\"Mon\",\"Tue\",\"Wed\",\"Thu\",\"Fri\",\"Sat\",\"Sun\",\"Weekday\",\"Weekend\"]}" - "}", - NULL); -} - -int ctx::device_status_alarm::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) -{ - int ret = subscribe(option); - destroy_if_unused(); - return ret; -} - -int ctx::device_status_alarm::unsubscribe(const char *subject, ctx::Json option) -{ - int ret = unsubscribe(option); - destroy_if_unused(); - return ret; -} - -int ctx::device_status_alarm::read(const char *subject, ctx::Json option, ctx::Json *requestResult) -{ - destroy_if_unused(); - return ERR_NOT_SUPPORTED; -} - -int ctx::device_status_alarm::write(const char *subject, ctx::Json data, ctx::Json *requestResult) -{ - destroy_if_unused(); - return ERR_NOT_SUPPORTED; -} - -int ctx::device_status_alarm::subscribe(ctx::Json option) -{ - int dow = get_arranged_day_of_week(option); - - int time; - for (int i = 0; option.getAt(NULL, DEVICE_ST_TIME_OF_DAY, i, &time); i++) { - add(time, dow); - } - - ctx::Json* elem = new(std::nothrow) ctx::Json(option); - if (elem) { - option_set.insert(elem); - } else { - unsubscribe(option); - _E("Memory allocation failed"); - return ERR_OUT_OF_MEMORY; - } - - return ERR_NONE; -} - -int ctx::device_status_alarm::unsubscribe(ctx::Json option) -{ - int dow = get_arranged_day_of_week(option); - - int time; - for (int i = 0; option.getAt(NULL, DEVICE_ST_TIME_OF_DAY, i, &time); i++) { - remove(time, dow); - } - - option_t::iterator target = find_option(option); - if (target != option_set.end()) { - delete (*target); - option_set.erase(target); - } - - return ERR_NONE; -} - -int ctx::device_status_alarm::get_arranged_day_of_week(ctx::Json& option) -{ - int dow = 0; - - std::string tmp_d; - for (int i = 0; option.getAt(NULL, DEVICE_ST_DAY_OF_WEEK, i, &tmp_d); i++) { - dow |= ctx::TimerManager::dowToInt(tmp_d); - } - _D("Requested day of week (%#x)", dow); - - return dow; -} - -ctx::device_status_alarm::ref_count_array_s::ref_count_array_s() -{ - memset(count, 0, sizeof(int) * DAYS_PER_WEEK); -} - -int ctx::device_status_alarm::merge_day_of_week(int* ref_cnt) -{ - int day_of_week = 0; - - for (int d = 0; d < DAYS_PER_WEEK; ++d) { - if (ref_cnt[d] > 0) { - day_of_week |= (0x01 << d); - } - } - - return day_of_week; -} - -bool ctx::device_status_alarm::add(int minute, int day_of_week) -{ - IF_FAIL_RETURN_TAG(minute >=0 && minute < 1440 && - day_of_week > 0 && day_of_week <= static_cast(DayOfWeek::EVERYDAY), - false, _E, "Invalid parameter"); - - ref_count_array_s &ref = ref_count_map[minute]; - - for (int d = 0; d < DAYS_PER_WEEK; ++d) { - if ((day_of_week & (0x01 << d)) != 0) { - ref.count[d] += 1; - } - } - - return reset_timer(minute); -} - -bool ctx::device_status_alarm::remove(int minute, int day_of_week) -{ - IF_FAIL_RETURN_TAG(minute >=0 && minute < 1440 && - day_of_week > 0 && day_of_week <= static_cast(DayOfWeek::EVERYDAY), - false, _E, "Invalid parameter"); - - ref_count_array_s &ref = ref_count_map[minute]; - - for (int d = 0; d < DAYS_PER_WEEK; ++d) { - if ((day_of_week & (0x01 << d)) != 0 && ref.count[d] > 0) { - ref.count[d] -= 1; - } - } - - return reset_timer(minute); -} - -bool ctx::device_status_alarm::reset_timer(int minute) -{ - int day_of_week = merge_day_of_week(ref_count_map[minute].count); - timer_state_s &timer = timer_state_map[minute]; - - if (day_of_week == timer.day_of_week) { - /* Necessary timers are already running... */ - return true; - } - - if (day_of_week == 0 && timer.timer_id > 0) { - /* Turn off the timer at hour, if it is not necessray anymore. */ - __timerManager.remove(timer.timer_id); - timer_state_map.erase(minute); - ref_count_map.erase(minute); - return true; - } - - if (timer.timer_id > 0) { - /* Turn off the current timer, to set a new one. */ - __timerManager.remove(timer.timer_id); - timer.timer_id = -1; - timer.day_of_week = 0; - } - - /* Create a new timer, w.r.t. the new day_of_week value. */ - int h = minute / 60; - int m = minute - h * 60; - int tid = __timerManager.setAt(h, m, static_cast(day_of_week), this); - IF_FAIL_RETURN_TAG(tid > 0, false, _E, "Timer setting failed"); - - timer.timer_id = tid; - timer.day_of_week = day_of_week; - - return true; -} - -void ctx::device_status_alarm::clear() -{ - for (timer_state_map_t::iterator it = timer_state_map.begin(); it != timer_state_map.end(); ++it) { - if (it->second.timer_id > 0) { - __timerManager.remove(it->second.timer_id); - } - } - - timer_state_map.clear(); - ref_count_map.clear(); -} - -bool ctx::device_status_alarm::onTimerExpired(int timer_id) -{ - time_t rawtime; - struct tm timeinfo; - - time(&rawtime); - tzset(); - localtime_r(&rawtime, &timeinfo); - - int hour = timeinfo.tm_hour; - int min = timeinfo.tm_min; - int day_of_week = (0x01 << timeinfo.tm_wday); - - on_timer_expired(hour, min, day_of_week); - - return true; -} - -void ctx::device_status_alarm::on_timer_expired(int hour, int min, int day_of_week) -{ - _I("Time: %02d:%02d, Day of Week: %#x", hour, min, day_of_week); - - ctx::Json dataRead; - int result_time = hour * 60 + min; - std::string result_day = ctx::TimerManager::dowToStr(day_of_week); - dataRead.set(NULL, DEVICE_ST_TIME_OF_DAY, result_time); - dataRead.set(NULL, DEVICE_ST_DAY_OF_WEEK, result_day); - - for (option_t::iterator it = option_set.begin(); it != option_set.end(); ++it) { - ctx::Json option = (**it); - if (is_matched(option, result_time, result_day)) { - context_manager::publish(DEVICE_ST_SUBJ_ALARM, option, ERR_NONE, dataRead); - } - } -} - -bool ctx::device_status_alarm::is_matched(ctx::Json& option, int time, std::string day) -{ - bool ret = false; - int opt_time; - for (int i = 0; option.getAt(NULL, DEVICE_ST_TIME_OF_DAY, i, &opt_time); i++){ - if (time == opt_time) { - ret = true; - break; - } - } - IF_FAIL_RETURN(ret, false); - - std::string opt_day; - for (int i = 0; option.getAt(NULL, DEVICE_ST_DAY_OF_WEEK, i, &opt_day); i++){ - if (day == opt_day) { - return true; - } - } - - return false; -} - -ctx::device_status_alarm::option_t::iterator ctx::device_status_alarm::find_option(ctx::Json& option) -{ - for (ctx::device_status_alarm::option_t::iterator it = option_set.begin(); it != option_set.end(); ++it) { - if (option == (**it)) - return it; - } - return option_set.end(); -} - -void ctx::device_status_alarm::destroy_if_unused() -{ - IF_FAIL_VOID(option_set.empty()); - destroy(NULL); -} diff --git a/src/device/system/alarm.h b/src/device/system/alarm.h deleted file mode 100644 index ff5271b..0000000 --- a/src/device/system/alarm.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _DEVICE_STATUS_ALARM_H_ -#define _DEVICE_STATUS_ALARM_H_ - -#include -#include -#include -#include -#include "../device_provider_base.h" - -namespace ctx { - - class device_status_alarm : public ContextProviderBase, ITimerListener { - - GENERATE_PROVIDER_COMMON_DECL(device_status_alarm); - - public: - int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); - int unsubscribe(const char *subject, ctx::Json option); - int read(const char *subject, ctx::Json option, ctx::Json *requestResult); - int write(const char *subject, ctx::Json data, ctx::Json *requestResult); - - int subscribe(ctx::Json option); - int unsubscribe(ctx::Json option); - static bool is_supported(); - static void submit_trigger_item(); - - private: - device_status_alarm(); - ~device_status_alarm(); - void handle_update(); - static void update_cb(void* user_data); - int get_arranged_day_of_week(ctx::Json& option); - - struct ref_count_array_s { - int count[7]; /* reference counts for days of week*/ - ref_count_array_s(); - }; - - struct timer_state_s { - int timer_id; - int day_of_week; /* day of week, merged into one integer */ - timer_state_s() : timer_id(-1), day_of_week(0) {} - }; - - typedef std::map ref_count_map_t; - typedef std::map timer_state_map_t; - typedef std::set option_t; - - ref_count_map_t ref_count_map; - timer_state_map_t timer_state_map; - option_t option_set; - TimerManager __timerManager; - - bool add(int minute, int day_of_week); - bool remove(int minute, int day_of_week); - void clear(); - bool empty(); - - int merge_day_of_week(int *ref_cnt); - bool reset_timer(int hour); - void on_timer_expired(int hour, int min, int day_of_week); - bool onTimerExpired(int timer_id); - - bool is_matched(ctx::Json& option, int time, std::string day); - option_t::iterator find_option(ctx::Json& option); - - void destroy_if_unused(); - - }; -} - -#endif // _DEVICE_STATUS_ALARM_H_ diff --git a/src/device/system/headphone.cpp b/src/device/system/headphone.cpp deleted file mode 100644 index 91e1708..0000000 --- a/src/device/system/headphone.cpp +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "system_types.h" -#include "headphone.h" - -#define HANDLING_DELAY 2000 -#define MAX_HANDLING_COUNT 3 - -GENERATE_PROVIDER_COMMON_IMPL(device_status_headphone); - -ctx::device_status_headphone::device_status_headphone() - : connected(false) - , audio_jack_state(RUNTIME_INFO_AUDIO_JACK_STATUS_UNCONNECTED) - , bt_audio_state(false) - , bt_audio_callback_on(false) - , bt_event_handler_added(false) - , bt_event_handling_count(0) -{ -} - -ctx::device_status_headphone::~device_status_headphone() -{ -} - -bool ctx::device_status_headphone::is_supported() -{ - return true; -} - -void ctx::device_status_headphone::submit_trigger_item() -{ - context_manager::registerTriggerItem(DEVICE_ST_SUBJ_HEADPHONE, OPS_SUBSCRIBE | OPS_READ, - "{" - TRIG_BOOL_ITEM_DEF("IsConnected") "," - "\"Type\":{\"type\":\"string\",\"values\":[\"Normal\",\"Headset\",\"Bluetooth\"]}" - "}", - NULL); -} - -int ctx::device_status_headphone::subscribe() -{ - connected = get_current_status(); - - // Wired headphone - int ret = runtime_info_set_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, on_audio_jack_state_changed, this); - IF_FAIL_RETURN(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED); - - // Bluetooth headphone - set_bt_audio_callback(); - - return ERR_NONE; -} - -int ctx::device_status_headphone::unsubscribe() -{ - runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS); - unset_bt_audio_callback(); - - return ERR_NONE; -} - -int ctx::device_status_headphone::read() -{ - if (!being_subscribed) - connected = get_current_status(); - - Json data; - generate_data_packet(data); - ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_HEADPHONE, NULL, ERR_NONE, data); - - return ERR_NONE; -} - -void ctx::device_status_headphone::set_bt_audio_callback() -{ - IF_FAIL_VOID(!bt_audio_callback_on); - int ret; - - ret = bt_initialize(); - if (ret != BT_ERROR_NONE) { - _W("Bluetooth initialization failed"); - return; - } - - ret = bt_device_set_connection_state_changed_cb(on_bt_connection_changed, this); - if (ret != BT_ERROR_NONE) { - bt_deinitialize(); - return; - } - - bt_audio_callback_on = true; -} - -void ctx::device_status_headphone::unset_bt_audio_callback() -{ - IF_FAIL_VOID(bt_audio_callback_on); - - bt_device_unset_connection_state_changed_cb(); - bt_deinitialize(); - - bt_audio_callback_on = false; -} - -void ctx::device_status_headphone::set_bt_audio_state(bool state) -{ - bt_audio_state = state; -} - -bool ctx::device_status_headphone::get_current_status() -{ - int ret; - - // Wired audio - ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, &audio_jack_state); - IF_FAIL_RETURN(ret == ERR_NONE, connected); - - // Bluetooth audio - bt_audio_state = false; - ret = bt_initialize(); - if (ret == BT_ERROR_NONE) { - bt_adapter_foreach_bonded_device(on_bt_bond, this); - bt_deinitialize(); - } - - return ((audio_jack_state != RUNTIME_INFO_AUDIO_JACK_STATUS_UNCONNECTED) || bt_audio_state); -} - -void ctx::device_status_headphone::generate_data_packet(ctx::Json &data) -{ - data.set(NULL, DEVICE_ST_IS_CONNECTED, connected ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); - - switch (audio_jack_state) { - case RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_3WIRE: - data.set(NULL, DEVICE_ST_TYPE, DEVICE_ST_NORMAL); - break; - case RUNTIME_INFO_AUDIO_JACK_STATUS_CONNECTED_4WIRE: - data.set(NULL, DEVICE_ST_TYPE, DEVICE_ST_HEADSET); - break; - default: - if (bt_audio_state) - data.set(NULL, DEVICE_ST_TYPE, DEVICE_ST_BLUETOOTH); - break; - } -} - -bool ctx::device_status_headphone::handle_event() -{ - bool prev_state = connected; - connected = ((audio_jack_state != RUNTIME_INFO_AUDIO_JACK_STATUS_UNCONNECTED) || bt_audio_state); - - IF_FAIL_RETURN(prev_state != connected, false); - - ctx::Json data; - generate_data_packet(data); - ctx::context_manager::publish(DEVICE_ST_SUBJ_HEADPHONE, NULL, ERR_NONE, data); - return true; -} - -void ctx::device_status_headphone::handle_audio_jack_event() -{ - int ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_AUDIO_JACK_STATUS, &audio_jack_state); - IF_FAIL_VOID_TAG(ret == ERR_NONE, _E, "Getting runtime info failed"); - handle_event(); -} - -void ctx::device_status_headphone::on_audio_jack_state_changed(runtime_info_key_e runtime_key, void* user_data) -{ - _D("EarJack"); - ctx::device_status_headphone *instance = static_cast(user_data); - instance->handle_audio_jack_event(); -} - -void ctx::device_status_headphone::on_bt_connection_changed(bool connected, bt_device_connection_info_s *conn_info, void *user_data) -{ - ctx::device_status_headphone *instance = static_cast(user_data); - IF_FAIL_VOID(connected != instance->bt_audio_state); - IF_FAIL_VOID(!instance->bt_event_handler_added); - - if (connected) { - _D("BT state checking scheduled"); - instance->bt_event_handler_added = true; - instance->bt_event_handling_count = 0; - g_timeout_add(HANDLING_DELAY, handle_bt_event, user_data); - } else { - handle_bt_event(user_data); - } -} - -gboolean ctx::device_status_headphone::handle_bt_event(gpointer data) -{ - _D("BT state checking started"); - ctx::device_status_headphone *instance = static_cast(data); - instance->bt_event_handler_added = false; - - instance->set_bt_audio_state(false); - int err = bt_adapter_foreach_bonded_device(on_bt_bond, data); - IF_FAIL_RETURN_TAG(err == BT_ERROR_NONE, FALSE, _E, "bt_adapter_foreach_bonded_device() failed"); - - instance->bt_event_handling_count++; - - if (instance->handle_event() || instance->bt_event_handling_count >= MAX_HANDLING_COUNT) - return FALSE; - - return TRUE; -} - -bool ctx::device_status_headphone::on_bt_bond(bt_device_info_s *device_info, void* user_data) -{ - if (device_info->bt_class.major_device_class != BT_MAJOR_DEVICE_CLASS_AUDIO_VIDEO) - return true; - - bool st = false; - int err = bt_device_is_profile_connected(device_info->remote_address, BT_PROFILE_A2DP, &st); - IF_FAIL_RETURN_TAG(err == BT_ERROR_NONE, false, _E, "bt_device_is_profile_connected() failed"); - - if (st) { - ctx::device_status_headphone *instance = static_cast(user_data); - instance->set_bt_audio_state(true); - return false; - } - - return true; -} diff --git a/src/device/system/headphone.h b/src/device/system/headphone.h deleted file mode 100644 index 8922a61..0000000 --- a/src/device/system/headphone.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _DEVICE_STATUS_HEADPHONE_H_ -#define _DEVICE_STATUS_HEADPNOHE_H_ - -#include -#include -#include -#include "../device_provider_base.h" - -namespace ctx { - - class device_status_headphone : public device_provider_base { - - GENERATE_PROVIDER_COMMON_DECL(device_status_headphone); - - public: - int subscribe(); - int unsubscribe(); - int read(); - static bool is_supported(); - static void submit_trigger_item(); - - private: - bool connected; - int audio_jack_state; - bool bt_audio_state; - bool bt_audio_callback_on; - bool bt_event_handler_added; - int bt_event_handling_count; - - device_status_headphone(); - ~device_status_headphone(); - - bool get_current_status(); - void set_bt_audio_callback(); - void unset_bt_audio_callback(); - void set_bt_audio_state(bool state); - - void generate_data_packet(Json &data); - bool handle_event(); - void handle_audio_jack_event(); - - static gboolean handle_bt_event(gpointer data); - static void on_audio_jack_state_changed(runtime_info_key_e runtime_key, void* user_data); - static void on_bt_connection_changed(bool connected, bt_device_connection_info_s *conn_info, void *user_data); - static bool on_bt_bond(bt_device_info_s *device_info, void* user_data); - }; -} - -#endif // _DEVICE_STATUS_HEADPHONE_H_ diff --git a/src/device/system/runtime-info/charger.cpp b/src/device/system/runtime_info/Charger.cpp similarity index 64% rename from src/device/system/runtime-info/charger.cpp rename to src/device/system/runtime_info/Charger.cpp index d4cec25..30802d9 100644 --- a/src/device/system/runtime-info/charger.cpp +++ b/src/device/system/runtime_info/Charger.cpp @@ -15,53 +15,53 @@ */ #include -#include "../system_types.h" -#include "charger.h" +#include "../SystemTypes.h" +#include "Charger.h" -GENERATE_PROVIDER_COMMON_IMPL(device_status_charger); +GENERATE_PROVIDER_COMMON_IMPL(DeviceStatusCharger); -ctx::device_status_charger::device_status_charger() - : device_status_runtime_info(RUNTIME_INFO_KEY_CHARGER_CONNECTED) +ctx::DeviceStatusCharger::DeviceStatusCharger() : + DeviceStatusRuntimeInfo(RUNTIME_INFO_KEY_CHARGER_CONNECTED) { } -ctx::device_status_charger::~device_status_charger() +ctx::DeviceStatusCharger::~DeviceStatusCharger() { } -bool ctx::device_status_charger::is_supported() +bool ctx::DeviceStatusCharger::isSupported() { return true; } -void ctx::device_status_charger::submit_trigger_item() +void ctx::DeviceStatusCharger::submitTriggerItem() { context_manager::registerTriggerItem(DEVICE_ST_SUBJ_CHARGER, OPS_SUBSCRIBE | OPS_READ, "{" TRIG_BOOL_ITEM_DEF("IsConnected") "}", NULL); } -void ctx::device_status_charger::handle_update() +void ctx::DeviceStatusCharger::handleUpdate() { - bool charger_status = false; + bool chargerStatus = false; - int ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_CHARGER_CONNECTED, &charger_status); + int ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_CHARGER_CONNECTED, &chargerStatus); IF_FAIL_VOID_TAG(ret == RUNTIME_INFO_ERROR_NONE, _E, "Getting runtime info failed"); ctx::Json dataRead; - dataRead.set(NULL, DEVICE_ST_IS_CONNECTED, charger_status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + dataRead.set(NULL, DEVICE_ST_IS_CONNECTED, chargerStatus ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); context_manager::publish(DEVICE_ST_SUBJ_CHARGER, NULL, ERR_NONE, dataRead); } -int ctx::device_status_charger::read() +int ctx::DeviceStatusCharger::read() { - bool charger_status = false; + bool chargerStatus = false; ctx::Json dataRead; - int ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_CHARGER_CONNECTED, &charger_status); + int ret = runtime_info_get_value_bool(RUNTIME_INFO_KEY_CHARGER_CONNECTED, &chargerStatus); IF_FAIL_RETURN_TAG(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Getting runtime info failed"); - dataRead.set(NULL, DEVICE_ST_IS_CONNECTED, charger_status ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); + dataRead.set(NULL, DEVICE_ST_IS_CONNECTED, chargerStatus ? DEVICE_ST_TRUE : DEVICE_ST_FALSE); ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_CHARGER, NULL, ERR_NONE, dataRead); return ERR_NONE; diff --git a/src/device/system/runtime-info/charger.h b/src/device/system/runtime_info/Charger.h similarity index 61% rename from src/device/system/runtime-info/charger.h rename to src/device/system/runtime_info/Charger.h index 52aeb4c..38cbca8 100644 --- a/src/device/system/runtime-info/charger.h +++ b/src/device/system/runtime_info/Charger.h @@ -14,27 +14,29 @@ * limitations under the License. */ -#ifndef _DEVICE_STATUS_CHARGER_H_ -#define _DEVICE_STATUS_CHARGER_H_ +#ifndef _DEVICE_SYSTEM_STATUS_CHARGER_ +#define _DEVICE_SYSTEM_STATUS_CHARGER_ -#include "base_rtinfo.h" +#include "RuntimeInfoBase.h" namespace ctx { - class device_status_charger : public device_status_runtime_info { + class DeviceStatusCharger : public DeviceStatusRuntimeInfo { - GENERATE_PROVIDER_COMMON_DECL(device_status_charger); + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusCharger); public: int read(); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); + + protected: + void handleUpdate(); private: - device_status_charger(); - ~device_status_charger(); - void handle_update(); + DeviceStatusCharger(); + ~DeviceStatusCharger(); }; } -#endif // _DEVICE_STATUS_CHARGER_H_ +#endif // _DEVICE_SYSTEM_STATUS_CHARGER_H_ diff --git a/src/device/system/runtime-info/gps.cpp b/src/device/system/runtime_info/Gps.cpp similarity index 63% rename from src/device/system/runtime-info/gps.cpp rename to src/device/system/runtime_info/Gps.cpp index 9624d38..9ec1c02 100644 --- a/src/device/system/runtime-info/gps.cpp +++ b/src/device/system/runtime_info/Gps.cpp @@ -15,14 +15,14 @@ */ #include -#include "../system_types.h" -#include "gps.h" +#include "../SystemTypes.h" +#include "Gps.h" -GENERATE_PROVIDER_COMMON_IMPL(device_status_gps); +GENERATE_PROVIDER_COMMON_IMPL(DeviceStatusGps); -static const char* get_state_string(int gps_state) +static const char* __getStatusString(int gpsStatus) { - switch (gps_state) { + switch (gpsStatus) { case RUNTIME_INFO_GPS_STATUS_DISABLED: return DEVICE_ST_DISABLED; @@ -33,26 +33,26 @@ static const char* get_state_string(int gps_state) return DEVICE_ST_CONNECTED; default: - _E("Unknown GPS status: %d", gps_state); + _E("Unknown GPS status: %d", gpsStatus); return NULL; } } -ctx::device_status_gps::device_status_gps() - : device_status_runtime_info(RUNTIME_INFO_KEY_GPS_STATUS) +ctx::DeviceStatusGps::DeviceStatusGps() : + DeviceStatusRuntimeInfo(RUNTIME_INFO_KEY_GPS_STATUS) { } -ctx::device_status_gps::~device_status_gps() +ctx::DeviceStatusGps::~DeviceStatusGps() { } -bool ctx::device_status_gps::is_supported() +bool ctx::DeviceStatusGps::isSupported() { - return get_system_info_bool("tizen.org/feature/location.gps"); + return getSystemInfoBool("tizen.org/feature/location.gps"); } -void ctx::device_status_gps::submit_trigger_item() +void ctx::DeviceStatusGps::submitTriggerItem() { context_manager::registerTriggerItem(DEVICE_ST_SUBJ_GPS, OPS_SUBSCRIBE | OPS_READ, "{" @@ -61,34 +61,34 @@ void ctx::device_status_gps::submit_trigger_item() NULL); } -void ctx::device_status_gps::handle_update() +void ctx::DeviceStatusGps::handleUpdate() { - int gps_status; - int ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_GPS_STATUS, &gps_status); + int gpsStatus; + int ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_GPS_STATUS, &gpsStatus); IF_FAIL_VOID_TAG(ret == RUNTIME_INFO_ERROR_NONE, _E, "Getting runtime info failed"); ctx::Json dataRead; - const char* state_str = get_state_string(gps_status); - IF_FAIL_VOID(state_str); + const char* stateStr = __getStatusString(gpsStatus); + IF_FAIL_VOID(stateStr); - dataRead.set(NULL, DEVICE_ST_STATE, state_str); + dataRead.set(NULL, DEVICE_ST_STATE, stateStr); context_manager::publish(DEVICE_ST_SUBJ_GPS, NULL, ERR_NONE, dataRead); } -int ctx::device_status_gps::read() +int ctx::DeviceStatusGps::read() { - int gps_status; + int gpsStatus; ctx::Json dataRead; - int ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_GPS_STATUS, &gps_status); + int ret = runtime_info_get_value_int(RUNTIME_INFO_KEY_GPS_STATUS, &gpsStatus); IF_FAIL_RETURN_TAG(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED, _E, "Getting runtime info failed"); - const char* state_str = get_state_string(gps_status); - IF_FAIL_RETURN(state_str, ERR_OPERATION_FAILED); + const char* stateStr = __getStatusString(gpsStatus); + IF_FAIL_RETURN(stateStr, ERR_OPERATION_FAILED); - dataRead.set(NULL, DEVICE_ST_STATE, state_str); + dataRead.set(NULL, DEVICE_ST_STATE, stateStr); ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_GPS, NULL, ERR_NONE, dataRead); return ERR_NONE; diff --git a/src/device/system/runtime-info/usb.h b/src/device/system/runtime_info/Gps.h similarity index 63% rename from src/device/system/runtime-info/usb.h rename to src/device/system/runtime_info/Gps.h index bc01425..38bc8e8 100644 --- a/src/device/system/runtime-info/usb.h +++ b/src/device/system/runtime_info/Gps.h @@ -14,27 +14,29 @@ * limitations under the License. */ -#ifndef _DEVICE_STATUS_USB_H_ -#define _DEVICE_STATUS_USB_H_ +#ifndef _DEVICE_SYSTEM_STATUS_GPS_H_ +#define _DEVICE_SYSTEM_STATUS_GPS_H_ -#include "base_rtinfo.h" +#include "RuntimeInfoBase.h" namespace ctx { - class device_status_usb : public device_status_runtime_info { + class DeviceStatusGps : public DeviceStatusRuntimeInfo { - GENERATE_PROVIDER_COMMON_DECL(device_status_usb); + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusGps); public: int read(); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); + + protected: + void handleUpdate(); private: - device_status_usb(); - ~device_status_usb(); - void handle_update(); + DeviceStatusGps(); + ~DeviceStatusGps(); }; } -#endif // _DEVICE_STATUS_USB_H_ +#endif // _DEVICE_SYSTEM_STATUS_GPS_H_ diff --git a/src/device/system/runtime-info/base_rtinfo.cpp b/src/device/system/runtime_info/RuntimeInfoBase.cpp similarity index 53% rename from src/device/system/runtime-info/base_rtinfo.cpp rename to src/device/system/runtime_info/RuntimeInfoBase.cpp index 2d3f0e3..61b117f 100644 --- a/src/device/system/runtime-info/base_rtinfo.cpp +++ b/src/device/system/runtime_info/RuntimeInfoBase.cpp @@ -14,35 +14,35 @@ * limitations under the License. */ -#include "base_rtinfo.h" +#include "RuntimeInfoBase.h" -ctx::device_status_runtime_info::device_status_runtime_info(runtime_info_key_e key) - : info_key(key) +ctx::DeviceStatusRuntimeInfo::DeviceStatusRuntimeInfo(runtime_info_key_e key) : + __infoKey(key) { } -runtime_info_key_e ctx::device_status_runtime_info::get_info_key() +runtime_info_key_e ctx::DeviceStatusRuntimeInfo::__getInfoKey() { - return info_key; + return __infoKey; } -void ctx::device_status_runtime_info::update_cb(runtime_info_key_e key, void* user_data) +void ctx::DeviceStatusRuntimeInfo::updateCb(runtime_info_key_e runtimeKey, void* userData) { - device_status_runtime_info *instance = static_cast(user_data); - IF_FAIL_VOID_TAG(key == instance->get_info_key(), _W, "Runtime info key mismatch"); - instance->handle_update(); + DeviceStatusRuntimeInfo *instance = static_cast(userData); + IF_FAIL_VOID_TAG(runtimeKey == instance->__getInfoKey(), _W, "Runtime info key mismatch"); + instance->handleUpdate(); } -int ctx::device_status_runtime_info::subscribe() +int ctx::DeviceStatusRuntimeInfo::subscribe() { - int ret = runtime_info_set_changed_cb(info_key, update_cb, this); + int ret = runtime_info_set_changed_cb(__infoKey, updateCb, this); IF_FAIL_RETURN(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED); return ERR_NONE; } -int ctx::device_status_runtime_info::unsubscribe() +int ctx::DeviceStatusRuntimeInfo::unsubscribe() { - int ret = runtime_info_unset_changed_cb(info_key); + int ret = runtime_info_unset_changed_cb(__infoKey); IF_FAIL_RETURN(ret == RUNTIME_INFO_ERROR_NONE, ERR_OPERATION_FAILED); return ERR_NONE; } diff --git a/src/device/system/runtime-info/base_rtinfo.h b/src/device/system/runtime_info/RuntimeInfoBase.h similarity index 59% rename from src/device/system/runtime-info/base_rtinfo.h rename to src/device/system/runtime_info/RuntimeInfoBase.h index faaaa6a..a0e2c20 100644 --- a/src/device/system/runtime-info/base_rtinfo.h +++ b/src/device/system/runtime_info/RuntimeInfoBase.h @@ -14,32 +14,32 @@ * limitations under the License. */ -#ifndef __CONTEXT_DEVICE_STATUS_RUNTIME_INFO_H__ -#define __CONTEXT_DEVICE_STATUS_RUNTIME_INFO_H__ +#ifndef _DEVICE_SYSTEM_STATUS_RUNTIME_INFO_BASE_H_ +#define _DEVICE_SYSTEM_STATUS_RUNTIME_INFO_BASE_H_ #include -#include "../../device_provider_base.h" +#include "../../DeviceProviderBase.h" namespace ctx { - class device_status_runtime_info : public device_provider_base { + class DeviceStatusRuntimeInfo : public DeviceProviderBase { public: - device_status_runtime_info(runtime_info_key_e key); + DeviceStatusRuntimeInfo(runtime_info_key_e key); int subscribe(); int unsubscribe(); virtual int read() = 0; protected: - runtime_info_key_e info_key; + runtime_info_key_e __infoKey; - virtual ~device_status_runtime_info(){} - static void update_cb(runtime_info_key_e runtime_key, void* user_data); - virtual void handle_update() = 0; + virtual ~DeviceStatusRuntimeInfo(){} + static void updateCb(runtime_info_key_e runtimeKey, void* userData); + virtual void handleUpdate() = 0; private: - runtime_info_key_e get_info_key(); + runtime_info_key_e __getInfoKey(); }; } -#endif +#endif // _DEVICE_SYSTEM_STATUS_RUNTIME_INFO_BASE_H_ diff --git a/src/device/system/runtime-info/usb.cpp b/src/device/system/runtime_info/Usb.cpp similarity index 76% rename from src/device/system/runtime-info/usb.cpp rename to src/device/system/runtime_info/Usb.cpp index 2b7ddbc..929a03f 100644 --- a/src/device/system/runtime-info/usb.cpp +++ b/src/device/system/runtime_info/Usb.cpp @@ -15,32 +15,32 @@ */ #include -#include "../system_types.h" -#include "usb.h" +#include "../SystemTypes.h" +#include "Usb.h" -GENERATE_PROVIDER_COMMON_IMPL(device_status_usb); +GENERATE_PROVIDER_COMMON_IMPL(DeviceStatusUsb); -ctx::device_status_usb::device_status_usb() - : device_status_runtime_info(RUNTIME_INFO_KEY_USB_CONNECTED) +ctx::DeviceStatusUsb::DeviceStatusUsb() : + DeviceStatusRuntimeInfo(RUNTIME_INFO_KEY_USB_CONNECTED) { } -ctx::device_status_usb::~device_status_usb() +ctx::DeviceStatusUsb::~DeviceStatusUsb() { } -bool ctx::device_status_usb::is_supported() +bool ctx::DeviceStatusUsb::isSupported() { - return get_system_info_bool("tizen.org/feature/usb.host"); + return getSystemInfoBool("tizen.org/feature/usb.host"); } -void ctx::device_status_usb::submit_trigger_item() +void ctx::DeviceStatusUsb::submitTriggerItem() { context_manager::registerTriggerItem(DEVICE_ST_SUBJ_USB, OPS_SUBSCRIBE | OPS_READ, "{" TRIG_BOOL_ITEM_DEF("IsConnected") "}", NULL); } -void ctx::device_status_usb::handle_update() +void ctx::DeviceStatusUsb::handleUpdate() { bool status = false; @@ -53,7 +53,7 @@ void ctx::device_status_usb::handle_update() context_manager::publish(DEVICE_ST_SUBJ_USB, NULL, ERR_NONE, dataRead); } -int ctx::device_status_usb::read() +int ctx::DeviceStatusUsb::read() { bool status = false; ctx::Json dataRead; diff --git a/src/device/system/runtime-info/gps.h b/src/device/system/runtime_info/Usb.h similarity index 63% rename from src/device/system/runtime-info/gps.h rename to src/device/system/runtime_info/Usb.h index 4d94cc0..4602752 100644 --- a/src/device/system/runtime-info/gps.h +++ b/src/device/system/runtime_info/Usb.h @@ -14,27 +14,29 @@ * limitations under the License. */ -#ifndef _DEVICE_STATUS_GPS_H_ -#define _DEVICE_STATUS_GPS_H_ +#ifndef _DEVICE_SYSTEM_STATUS_USB_H_ +#define _DEVICE_SYSTEM_STATUS_USB_H_ -#include "base_rtinfo.h" +#include "RuntimeInfoBase.h" namespace ctx { - class device_status_gps : public device_status_runtime_info { + class DeviceStatusUsb : public DeviceStatusRuntimeInfo { - GENERATE_PROVIDER_COMMON_DECL(device_status_gps); + GENERATE_PROVIDER_COMMON_DECL(DeviceStatusUsb); public: int read(); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); + + protected: + void handleUpdate(); private: - device_status_gps(); - ~device_status_gps(); - void handle_update(); + DeviceStatusUsb(); + ~DeviceStatusUsb(); }; } -#endif // _DEVICE_STATUS_GPS_H_ +#endif // _DEVICE_SYSTEM_STATUS_USB_H_ diff --git a/src/device/system/wifi.cpp b/src/device/system/wifi.cpp deleted file mode 100644 index 4d237df..0000000 --- a/src/device/system/wifi.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include "system_types.h" -#include "wifi.h" - -ctx::device_status_wifi *ctx::device_status_wifi::__instance = NULL; - -ctx::device_status_wifi::device_status_wifi() - : last_state(_UNKNOWN) - , is_initialized(false) - , is_activated(false) - , conn_state(WIFI_CONNECTION_STATE_FAILURE) -{ - IF_FAIL_VOID_TAG(start_monitor(), _W, "WiFi monitor initialization failed"); - - if (!get_current_state()) { - stop_monitor(); - _W("Getting current WiFi status failed"); - } -} - -ctx::device_status_wifi::~device_status_wifi() -{ -} - -ctx::ContextProviderBase *ctx::device_status_wifi::create(void *data) -{ - CREATE_INSTANCE(device_status_wifi); -} - -void ctx::device_status_wifi::destroy(void *data) -{ - __instance->stop_monitor(); - DESTROY_INSTANCE(); -} - -void ctx::device_status_wifi::destroy_self() -{ - /* WiFi status will be monitored continuously, even if no client is subscribing it */ -} - -bool ctx::device_status_wifi::is_supported() -{ - return get_system_info_bool("tizen.org/feature/network.wifi"); -} - -void ctx::device_status_wifi::submit_trigger_item() -{ - context_manager::registerTriggerItem(DEVICE_ST_SUBJ_WIFI, OPS_SUBSCRIBE | OPS_READ, - "{" - "\"State\":{\"type\":\"string\",\"values\":[\"Disabled\",\"Unconnected\",\"Connected\"]}," - "\"BSSID\":{\"type\":\"string\"}" - "}", - NULL); -} - -bool ctx::device_status_wifi::get_current_state() -{ - int err; - - if (!is_initialized) { - err = wifi_initialize(); - IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_initialize() failed"); - } - - err = wifi_is_activated(&is_activated); - IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_is_activated() failed"); - - err = wifi_get_connection_state(&conn_state); - IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_get_connection_state() failed"); - - if (is_activated) { - if (conn_state == WIFI_CONNECTION_STATE_CONNECTED) { - last_state = _CONNECTED; - get_bssid(); - } else { - last_state = _UNCONNECTED; - clear_bssid(); - } - } else { - last_state = _DISABLED; - clear_bssid(); - } - - if (!is_initialized) - wifi_deinitialize(); - - return true; -} - -bool ctx::device_status_wifi::get_bssid() -{ - int err; - char *str_buf = NULL; - wifi_ap_h ap = NULL; - - err = wifi_get_connected_ap(&ap); - IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_get_connected_ap() failed"); - - wifi_ap_get_bssid(ap, &str_buf); - bssid = (str_buf != NULL ? str_buf : ""); - g_free(str_buf); - - wifi_ap_destroy(ap); - - if (bssid.empty()) - _W("Failed to get BSSID"); - - SharedVars().set(ctx::SharedVars::WIFI_BSSID, bssid); - _D("BSSID: %s", bssid.c_str()); - - return !bssid.empty(); -} - -void ctx::device_status_wifi::clear_bssid() -{ - bssid.clear(); - SharedVars().clear(ctx::SharedVars::WIFI_BSSID); - _D("No WiFi connection"); -} - -bool ctx::device_status_wifi::get_response_packet(ctx::Json &data) -{ - switch (last_state) { - case _DISABLED: - data.set(NULL, DEVICE_ST_STATE, DEVICE_ST_DISABLED); - break; - - case _UNCONNECTED: - data.set(NULL, DEVICE_ST_STATE, DEVICE_ST_UNCONNECTED); - break; - - case _CONNECTED: - data.set(NULL, DEVICE_ST_STATE, DEVICE_ST_CONNECTED); - data.set(NULL, DEVICE_ST_BSSID, bssid); - break; - - default: - return false; - } - - return true; -} - -int ctx::device_status_wifi::read() -{ - IF_FAIL_RETURN(get_current_state(), ERR_OPERATION_FAILED); - - ctx::Json dataRead; - - if (get_response_packet(dataRead)) { - ctx::context_manager::replyToRead(DEVICE_ST_SUBJ_WIFI, NULL, ERR_NONE, dataRead); - return ERR_NONE; - } - - return ERR_OPERATION_FAILED; -} - -bool ctx::device_status_wifi::start_monitor() -{ - IF_FAIL_RETURN(!is_initialized, true); - - int err; - err = wifi_initialize(); - IF_FAIL_RETURN_TAG(err == WIFI_ERROR_NONE, false, _E, "wifi_initialize() failed"); - - err = wifi_set_device_state_changed_cb(device_state_changed_cb, this); - IF_FAIL_CATCH_TAG(err == WIFI_ERROR_NONE, _E, "wifi_set_device_state_changed_cb() failed"); - - err = wifi_set_connection_state_changed_cb(connection_state_changed_cb, this); - IF_FAIL_CATCH_TAG(err == WIFI_ERROR_NONE, _E, "wifi_set_connection_state_changed_cb() failed"); - - is_initialized = true; - return true; - -CATCH: - wifi_deinitialize(); - return false; -} - -void ctx::device_status_wifi::stop_monitor() -{ - IF_FAIL_VOID(is_initialized); - - wifi_unset_device_state_changed_cb(); - wifi_unset_connection_state_changed_cb(); - wifi_deinitialize(); - is_initialized = false; -} - -int ctx::device_status_wifi::subscribe() -{ -#if 0 - IF_FAIL_RETURN(start_monitor(), ERR_OPERATION_FAILED); - if (!get_current_state()) { - stop_monitor(); - return ERR_OPERATION_FAILED; - } -#endif - - return ERR_NONE; -} - -int ctx::device_status_wifi::unsubscribe() -{ -#if 0 - stop_monitor(); -#endif - return ERR_NONE; -} - -void ctx::device_status_wifi::aggregate_updated_data() -{ - int prev_state = last_state; - - if (is_activated) { - if (conn_state == WIFI_CONNECTION_STATE_CONNECTED) { - last_state = _CONNECTED; - } else { - last_state = _UNCONNECTED; - } - } else { - last_state = _DISABLED; - } - - if (last_state != prev_state) { - if (last_state == _CONNECTED) { - get_bssid(); - } else { - clear_bssid(); - } - - ctx::Json data; - if (being_subscribed && get_response_packet(data)) - context_manager::publish(DEVICE_ST_SUBJ_WIFI, NULL, ERR_NONE, data); - } -} - -void ctx::device_status_wifi::device_state_changed_cb(wifi_device_state_e state, void *user_data) -{ - device_status_wifi *instance = static_cast(user_data); - instance->is_activated = (state == WIFI_DEVICE_STATE_ACTIVATED); - instance->aggregate_updated_data(); -} - -void ctx::device_status_wifi::connection_state_changed_cb(wifi_connection_state_e state, wifi_ap_h ap, void *user_data) -{ - device_status_wifi *instance = static_cast(user_data); - instance->conn_state = state; - instance->aggregate_updated_data(); -} diff --git a/src/device/system/wifi.h b/src/device/system/wifi.h deleted file mode 100644 index 3ed52d5..0000000 --- a/src/device/system/wifi.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __CONTEXT_DEVICE_STATUS_WIFI_H__ -#define __CONTEXT_DEVICE_STATUS_WIFI_H__ - -#include -#include -#include "../device_provider_base.h" - -namespace ctx { - - class device_status_wifi : public device_provider_base { - - GENERATE_PROVIDER_COMMON_DECL(device_status_wifi); - - public: - int subscribe(); - int unsubscribe(); - int read(); - static bool is_supported(); - static void submit_trigger_item(); - - private: - enum _state_e { - _UNKNOWN = -1, - _DISABLED = 0, - _UNCONNECTED, - _CONNECTED, - }; - - int last_state; - bool is_initialized; - bool is_activated; - wifi_connection_state_e conn_state; - std::string bssid; - - device_status_wifi(); - ~device_status_wifi(); - - bool get_current_state(); - bool get_bssid(); - void clear_bssid(); - bool get_response_packet(Json &data); - void aggregate_updated_data(); - bool start_monitor(); - void stop_monitor(); - static void device_state_changed_cb(wifi_device_state_e state, void *user_data); - static void connection_state_changed_cb(wifi_connection_state_e state, wifi_ap_h ap, void *user_data); - }; -} - -#endif -- 2.7.4 From 5ba9bc46546ff288c2694075106535f116c3f889 Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Wed, 6 Apr 2016 13:21:03 +0900 Subject: [PATCH 08/16] Applying Tizen C++ coding style to custom context provider Change-Id: I7cdbed7358584669caef5eb7ffc5a59c08b70734 Signed-off-by: Somin Kim --- src/custom/CustomBase.cpp | 91 ++++++++++++++++++++++ src/custom/{custom_base.h => CustomBase.h} | 36 ++++----- ...text_provider.cpp => CustomContextProvider.cpp} | 84 ++++++++++---------- src/custom/custom_base.cpp | 91 ---------------------- 4 files changed, 151 insertions(+), 151 deletions(-) create mode 100644 src/custom/CustomBase.cpp rename src/custom/{custom_base.h => CustomBase.h} (64%) rename src/custom/{custom_context_provider.cpp => CustomContextProvider.cpp} (70%) delete mode 100644 src/custom/custom_base.cpp diff --git a/src/custom/CustomBase.cpp b/src/custom/CustomBase.cpp new file mode 100644 index 0000000..529835b --- /dev/null +++ b/src/custom/CustomBase.cpp @@ -0,0 +1,91 @@ +/* + * 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 "CustomBase.h" + +ctx::CustomBase::CustomBase(std::string subject, std::string name, ctx::Json tmpl, std::string owner) : + __subject(subject), + __name(name), + __tmpl(tmpl), + __owner(owner) +{ +} + +ctx::CustomBase::~CustomBase() +{ +} + +bool ctx::CustomBase::isSupported() +{ + return true; +} + +void ctx::CustomBase::submitTriggerItem() +{ + context_manager::registerTriggerItem(__subject.c_str(), OPS_SUBSCRIBE | OPS_READ, + __tmpl.str(), NULL, __owner.c_str()); +} + +void ctx::CustomBase::unsubmitTriggerItem() +{ + context_manager::unregisterTriggerItem(__subject.c_str()); +} + +int ctx::CustomBase::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) +{ + return ERR_NONE; + +} + +int ctx::CustomBase::unsubscribe(const char *subject, ctx::Json option) +{ + return ERR_NONE; +} + +int ctx::CustomBase::read(const char *subject, ctx::Json option, ctx::Json *requestResult) +{ + ctx::Json data = __latest.str(); + ctx::context_manager::replyToRead(__subject.c_str(), NULL, ERR_NONE, data); + return ERR_NONE; +} + +int ctx::CustomBase::write(const char *subject, ctx::Json data, ctx::Json *requestResult) +{ + return ERR_NONE; +} + +void ctx::CustomBase::handleUpdate(ctx::Json data) +{ + // Store latest state + __latest = data.str(); + ctx::context_manager::publish(__subject.c_str(), NULL, ERR_NONE, data); +} + +const char* ctx::CustomBase::getSubject() +{ + return __subject.c_str(); +} + +std::string ctx::CustomBase::getOwner() +{ + return __owner; +} + +ctx::Json ctx::CustomBase::getTemplate() +{ + return __tmpl; +} diff --git a/src/custom/custom_base.h b/src/custom/CustomBase.h similarity index 64% rename from src/custom/custom_base.h rename to src/custom/CustomBase.h index 68e45cc..c95ba5c 100644 --- a/src/custom/custom_base.h +++ b/src/custom/CustomBase.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef _CUSTOM_BASE_H_ -#define _CUSTOM_BASE_H_ +#ifndef _CONTEXT_CUSTOM_BASE_H_ +#define _CONTEXT_CUSTOM_BASE_H_ #include #include @@ -23,33 +23,33 @@ namespace ctx { - class custom_base : public ContextProviderBase { + class CustomBase : public ContextProviderBase { public: - custom_base(std::string subject, std::string name, ctx::Json tmpl, std::string owner); - ~custom_base(); + CustomBase(std::string subject, std::string name, ctx::Json tmpl, std::string owner); + ~CustomBase(); int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); int read(const char *subject, ctx::Json option, ctx::Json *requestResult); int write(const char *subject, ctx::Json data, ctx::Json *requestResult); - static bool is_supported(); - void submit_trigger_item(); - void unsubmit_trigger_item(); + static bool isSupported(); + void submitTriggerItem(); + void unsubmitTriggerItem(); - void handle_update(ctx::Json data); + void handleUpdate(ctx::Json data); - const char* get_subject(); - std::string get_owner(); - ctx::Json get_template(); + const char* getSubject(); + std::string getOwner(); + ctx::Json getTemplate(); private: - std::string _subject; - std::string _name; - ctx::Json _tmpl; - std::string _owner; - ctx::Json latest; + std::string __subject; + std::string __name; + ctx::Json __tmpl; + std::string __owner; + ctx::Json __latest; }; } -#endif // _CUSTOM_BASE_H_ +#endif /* End of _CONTEXT_CUSTOM_BASE_H_ */ diff --git a/src/custom/custom_context_provider.cpp b/src/custom/CustomContextProvider.cpp similarity index 70% rename from src/custom/custom_context_provider.cpp rename to src/custom/CustomContextProvider.cpp index 5bec97e..286f28e 100644 --- a/src/custom/custom_context_provider.cpp +++ b/src/custom/CustomContextProvider.cpp @@ -21,13 +21,13 @@ #include #include #include -#include "custom_base.h" +#include "CustomBase.h" -std::map custom_map; +static std::map __customMap; -static bool is_valid_fact(std::string subject, ctx::Json& fact); -static bool check_value_int(ctx::Json& tmpl, std::string key, int value); -static bool check_value_string(ctx::Json& tmpl, std::string key, std::string value); +static bool __isValidFact(std::string subject, ctx::Json& fact); +static bool __checkValueInt(ctx::Json& tmpl, std::string key, int value); +static bool __checkValueString(ctx::Json& tmpl, std::string key, std::string value); void registerProvider(const char *subject, const char *privilege) { @@ -35,27 +35,27 @@ void registerProvider(const char *subject, const char *privilege) ctx::custom_context_provider::destroy, const_cast(subject), privilege); ctx::context_manager::registerProvider(subject, providerInfo); - custom_map[subject]->submit_trigger_item(); + __customMap[subject]->submitTriggerItem(); } void unregisterProvider(const char* subject) { - custom_map[subject]->unsubmit_trigger_item(); + __customMap[subject]->unsubmitTriggerItem(); ctx::context_manager::unregisterProvider(subject); } EXTAPI ctx::ContextProviderBase* ctx::custom_context_provider::create(void *data) { // Already created in addItem() function. Return corresponding custom provider - return custom_map[static_cast(data)]; + return __customMap[static_cast(data)]; } EXTAPI void ctx::custom_context_provider::destroy(void *data) { - std::map::iterator it = custom_map.find(static_cast(data)); - if (it != custom_map.end()) { + std::map::iterator it = __customMap.find(static_cast(data)); + if (it != __customMap.end()) { delete it->second; - custom_map.erase(it); + __customMap.erase(it); } } @@ -71,15 +71,15 @@ EXTAPI bool ctx::initCustomContextProvider() IF_FAIL_RETURN_TAG(ret, false, _E, "Create template table failed"); // Register custom items - std::string q_select = "SELECT * FROM context_trigger_custom_template"; - ret = db_manager::execute_sync(q_select.c_str(), &record); + std::string qSelect = "SELECT * FROM context_trigger_custom_template"; + ret = db_manager::execute_sync(qSelect.c_str(), &record); IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to query custom templates"); IF_FAIL_RETURN(record.size() > 0, true); int error; - std::vector::iterator vec_end = record.end(); - for (std::vector::iterator vec_pos = record.begin(); vec_pos != vec_end; ++vec_pos) { - ctx::Json elem = *vec_pos; + std::vector::iterator vedEnd = record.end(); + for (auto vecPos = record.begin(); vecPos != vedEnd; ++vecPos) { + ctx::Json elem = *vecPos; std::string subject; std::string name; std::string attributes; @@ -98,13 +98,13 @@ EXTAPI bool ctx::initCustomContextProvider() return true; } -EXTAPI int ctx::custom_context_provider::addItem(std::string subject, std::string name, ctx::Json tmpl, const char* owner, bool is_init) +EXTAPI int ctx::custom_context_provider::addItem(std::string subject, std::string name, ctx::Json tmpl, const char* owner, bool isInit) { - std::map::iterator it; - it = custom_map.find(subject); + std::map::iterator it; + it = __customMap.find(subject); - if (it != custom_map.end()) { - if ((it->second)->get_template() != tmpl) { // Same item name, but different template + if (it != __customMap.end()) { + if ((it->second)->getTemplate() != tmpl) { // Same item name, but different template return ERR_DATA_EXIST; } // Same item name with same template @@ -112,14 +112,14 @@ EXTAPI int ctx::custom_context_provider::addItem(std::string subject, std::strin } // Create custom base - ctx::custom_base* custom = new(std::nothrow) custom_base(subject, name, tmpl, owner); + ctx::CustomBase* custom = new(std::nothrow) CustomBase(subject, name, tmpl, owner); IF_FAIL_RETURN_TAG(custom, ERR_OUT_OF_MEMORY, _E, "Memory allocation failed"); - custom_map[subject] = custom; + __customMap[subject] = custom; - registerProvider(custom->get_subject(), NULL); + registerProvider(custom->getSubject(), NULL); // Add item to custom template db - if (!is_init) { + if (!isInit) { std::string q = "INSERT OR IGNORE INTO context_trigger_custom_template (subject, name, attributes, owner) VALUES ('" + subject + "', '" + name + "', '" + tmpl.str() + "', '" + owner + "'); "; std::vector record; @@ -132,9 +132,9 @@ EXTAPI int ctx::custom_context_provider::addItem(std::string subject, std::strin EXTAPI int ctx::custom_context_provider::removeItem(std::string subject) { - std::map::iterator it; - it = custom_map.find(subject); - IF_FAIL_RETURN_TAG(it != custom_map.end(), ERR_NOT_SUPPORTED, _E, "%s not supported", subject.c_str()); + std::map::iterator it; + it = __customMap.find(subject); + IF_FAIL_RETURN_TAG(it != __customMap.end(), ERR_NOT_SUPPORTED, _E, "%s not supported", subject.c_str()); unregisterProvider(subject.c_str()); @@ -149,20 +149,20 @@ EXTAPI int ctx::custom_context_provider::removeItem(std::string subject) EXTAPI int ctx::custom_context_provider::publishData(std::string subject, ctx::Json fact) { - std::map::iterator it; - it = custom_map.find(subject); - IF_FAIL_RETURN_TAG(it != custom_map.end(), ERR_NOT_SUPPORTED, _E, "%s not supported", subject.c_str()); + std::map::iterator it; + it = __customMap.find(subject); + IF_FAIL_RETURN_TAG(it != __customMap.end(), ERR_NOT_SUPPORTED, _E, "%s not supported", subject.c_str()); - bool ret = is_valid_fact(subject, fact); + bool ret = __isValidFact(subject, fact); IF_FAIL_RETURN_TAG(ret, ERR_INVALID_DATA, _E, "Invalid fact(%s)", subject.c_str()); - custom_map[subject]->handle_update(fact); + __customMap[subject]->handleUpdate(fact); return ERR_NONE; } -bool is_valid_fact(std::string subject, ctx::Json& fact) +bool __isValidFact(std::string subject, ctx::Json& fact) { - ctx::Json tmpl = custom_map[subject]->get_template(); + ctx::Json tmpl = __customMap[subject]->getTemplate(); IF_FAIL_RETURN_TAG(tmpl != EMPTY_JSON_OBJECT, false, _E, "Failed to get template"); bool ret; @@ -179,14 +179,14 @@ bool is_valid_fact(std::string subject, ctx::Json& fact) ret = fact.get(NULL, key.c_str(), &val); IF_FAIL_RETURN_TAG(ret, false, _E, "Custom fact: invalid data type"); - ret = check_value_int(tmpl, key, val); + ret = __checkValueInt(tmpl, key, val); IF_FAIL_RETURN_TAG(ret, false, _E, "Custom fact: invalid value"); } else if (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 = check_value_string(tmpl, key, val_str); + ret = __checkValueString(tmpl, key, val_str); IF_FAIL_RETURN_TAG(ret, false, _E, "Custom fact: invalid value"); } else { _E("Custom fact: invalid data type"); @@ -197,7 +197,7 @@ bool is_valid_fact(std::string subject, ctx::Json& fact) return true; } -bool check_value_int(ctx::Json& tmpl, std::string key, int value) +bool __checkValueInt(ctx::Json& tmpl, std::string key, int value) { int min, max; @@ -212,16 +212,16 @@ bool check_value_int(ctx::Json& tmpl, std::string key, int value) return true; } -bool check_value_string(ctx::Json& tmpl, std::string key, std::string value) +bool __checkValueString(ctx::Json& tmpl, std::string key, std::string value) { // case1: any value is accepted if (tmpl.getSize(key.c_str(), "values") <= 0) return true; // case2: check acceptable value - std::string t_val; - for (int i = 0; tmpl.getAt(key.c_str(), "values", i, &t_val); i++) { - if (t_val == value) + std::string tmplValue; + for (int i = 0; tmpl.getAt(key.c_str(), "values", i, &tmplValue); i++) { + if (tmplValue == value) return true; } diff --git a/src/custom/custom_base.cpp b/src/custom/custom_base.cpp deleted file mode 100644 index 4371202..0000000 --- a/src/custom/custom_base.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2016 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include "custom_base.h" - -ctx::custom_base::custom_base(std::string subject, std::string name, ctx::Json tmpl, std::string owner) : - _subject(subject), - _name(name), - _tmpl(tmpl), - _owner(owner) -{ -} - -ctx::custom_base::~custom_base() -{ -} - -bool ctx::custom_base::is_supported() -{ - return true; -} - -void ctx::custom_base::submit_trigger_item() -{ - context_manager::registerTriggerItem(_subject.c_str(), OPS_SUBSCRIBE | OPS_READ, - _tmpl.str(), NULL, _owner.c_str()); -} - -void ctx::custom_base::unsubmit_trigger_item() -{ - context_manager::unregisterTriggerItem(_subject.c_str()); -} - -int ctx::custom_base::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) -{ - return ERR_NONE; - -} - -int ctx::custom_base::unsubscribe(const char *subject, ctx::Json option) -{ - return ERR_NONE; -} - -int ctx::custom_base::read(const char *subject, ctx::Json option, ctx::Json *requestResult) -{ - ctx::Json data = latest.str(); - ctx::context_manager::replyToRead(_subject.c_str(), NULL, ERR_NONE, data); - return ERR_NONE; -} - -int ctx::custom_base::write(const char *subject, ctx::Json data, ctx::Json *requestResult) -{ - return ERR_NONE; -} - -void ctx::custom_base::handle_update(ctx::Json data) -{ - // Store latest state - latest = data.str(); - ctx::context_manager::publish(_subject.c_str(), NULL, ERR_NONE, data); -} - -const char* ctx::custom_base::get_subject() -{ - return _subject.c_str(); -} - -std::string ctx::custom_base::get_owner() -{ - return _owner; -} - -ctx::Json ctx::custom_base::get_template() -{ - return _tmpl; -} -- 2.7.4 From 3bbe9bd327d239c06ce3e15d5ecc7306ff4e5b50 Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Thu, 7 Apr 2016 18:28:07 +0900 Subject: [PATCH 09/16] Applying Tizen C++ coding style to place context provider(geofence) Change-Id: Ic81ae68d2e39dcea8adf4e7fbdbad6bafa9919aa Signed-off-by: Somin Kim --- ...ntext_provider.cpp => PlaceContextProvider.cpp} | 12 +- src/place/geofence/GeofenceMonitorHandle.cpp | 218 +++++++++++++++++++++ src/place/geofence/GeofenceMonitorHandle.h | 55 ++++++ src/place/geofence/PlaceGeofenceProvider.cpp | 151 ++++++++++++++ .../{place_geofence.h => PlaceGeofenceProvider.h} | 27 ++- ...place_geofence_types.h => PlaceGeofenceTypes.h} | 26 ++- src/place/geofence/myplace_handle.cpp | 218 --------------------- src/place/geofence/myplace_handle.h | 59 ------ src/place/geofence/place_geofence.cpp | 151 -------------- src/place/recognition/place_recognition.cpp | 2 +- src/place/recognition/place_recognition.h | 2 +- 11 files changed, 457 insertions(+), 464 deletions(-) rename src/place/{place_context_provider.cpp => PlaceContextProvider.cpp} (82%) create mode 100644 src/place/geofence/GeofenceMonitorHandle.cpp create mode 100644 src/place/geofence/GeofenceMonitorHandle.h create mode 100644 src/place/geofence/PlaceGeofenceProvider.cpp rename src/place/geofence/{place_geofence.h => PlaceGeofenceProvider.h} (69%) rename src/place/geofence/{place_geofence_types.h => PlaceGeofenceTypes.h} (63%) delete mode 100644 src/place/geofence/myplace_handle.cpp delete mode 100644 src/place/geofence/myplace_handle.h delete mode 100644 src/place/geofence/place_geofence.cpp diff --git a/src/place/place_context_provider.cpp b/src/place/PlaceContextProvider.cpp similarity index 82% rename from src/place/place_context_provider.cpp rename to src/place/PlaceContextProvider.cpp index c3efaef..f168dd1 100644 --- a/src/place/place_context_provider.cpp +++ b/src/place/PlaceContextProvider.cpp @@ -20,27 +20,27 @@ #include #ifdef _MOBILE_ -#include "geofence/place_geofence.h" +#include "geofence/PlaceGeofenceProvider.h" #ifndef _DISABLE_RECOG_ENGINE_ #include "recognition/place_recognition.h" #endif /* _DISABLE_RECOG_ENGINE_ */ #endif /* _MOBILE_ */ -template +template void registerProvider(const char *subject, const char *privilege) { - if (!provider::is_supported()) + if (!Provider::isSupported()) return; - ctx::ContextProviderInfo providerInfo(provider::create, provider::destroy, NULL, privilege); + ctx::ContextProviderInfo providerInfo(Provider::create, Provider::destroy, NULL, privilege); ctx::context_manager::registerProvider(subject, providerInfo); } EXTAPI bool ctx::initPlaceContextProvider() { #ifdef _MOBILE_ - registerProvider(PLACE_SUBJ_GEOFENCE, PLACE_PRIV_GEOFENCE); - place_geofence_provider::submit_trigger_item(); + registerProvider(PLACE_SUBJ_GEOFENCE, PLACE_PRIV_GEOFENCE); + PlaceGeofenceProvider::submitTriggerItem(); #ifndef _DISABLE_RECOG_ENGINE_ place_recognition_provider::create(NULL); diff --git a/src/place/geofence/GeofenceMonitorHandle.cpp b/src/place/geofence/GeofenceMonitorHandle.cpp new file mode 100644 index 0000000..52b4b07 --- /dev/null +++ b/src/place/geofence/GeofenceMonitorHandle.cpp @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "PlaceGeofenceTypes.h" +#include "GeofenceMonitorHandle.h" + +ctx::GeofenceMonitorHandle::GeofenceMonitorHandle() : + __placeId(-1), + __prevState(GEOFENCE_STATE_UNCERTAIN), + __geoHandle(NULL) +{ +} + +ctx::GeofenceMonitorHandle::~GeofenceMonitorHandle() +{ + __stopMonitor(); +} + +bool ctx::GeofenceMonitorHandle::startMonitor(int placeId) +{ + _D("Starts to monitor Place-%d", placeId); + + IF_FAIL_RETURN(placeId >= 0, false); + IF_FAIL_RETURN_TAG(__geoHandle == NULL, false, _E, "Re-starting MyPlace monitor"); + + geofence_manager_create(&__geoHandle); + IF_FAIL_RETURN_TAG(__geoHandle, false, _E, "Geofence initialization failed"); + + int ret; + + ret = geofence_manager_set_geofence_state_changed_cb(__geoHandle, __fenceStateCb, this); + IF_FAIL_CATCH_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, _E, "Setting state callback failed"); + + ret = geofence_manager_set_geofence_event_cb(__geoHandle, __fenceEventCb, this); + IF_FAIL_CATCH_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, _E, "Setting event callback failed"); + + ret = geofence_manager_foreach_place_geofence_list(__geoHandle, placeId, __fenceListCb, this); + IF_FAIL_CATCH_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, _E, "Getting fence list failed"); + + __placeId = placeId; + return true; + +CATCH: + __stopMonitor(); + return false; +} + +int ctx::GeofenceMonitorHandle::getPlaceId() +{ + return __placeId; +} + +void ctx::GeofenceMonitorHandle::__stopMonitor() +{ + _D("Stops monitoring Place-%d", __placeId); + + //TODO: Do we need to stop all geofences explicitly? + if (__geoHandle) { + geofence_manager_destroy(__geoHandle); + __geoHandle = NULL; + } + + __geoStateMap.clear(); + __placeId = -1; + __prevState = GEOFENCE_STATE_UNCERTAIN; +} + +bool ctx::GeofenceMonitorHandle::__startFence(int fenceId) +{ + int ret; + + ret = geofence_manager_start(__geoHandle, fenceId); + IF_FAIL_RETURN_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, true, _W, "Starting failed"); + + geofence_status_h status; + ret = geofence_status_create(fenceId, &status); + IF_FAIL_RETURN_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, true, _W, "Getting status failed"); + + geofence_state_e state = GEOFENCE_STATE_UNCERTAIN; + geofence_status_get_state(status, &state); + geofence_status_destroy(status); + + __geoStateMap[fenceId] = state; + + return true; +} + +void ctx::GeofenceMonitorHandle::__removeFence(int fenceId) +{ + geofence_manager_stop(__geoHandle, fenceId); + __geoStateMap.erase(fenceId); +} + +void ctx::GeofenceMonitorHandle::__updateFence(int fenceId, geofence_manage_e manage) +{ + switch (manage) { + case GEOFENCE_MANAGE_PLACE_REMOVED: + _W("[Place-%d] Removed", __placeId); + __stopMonitor(); + break; + case GEOFENCE_MANAGE_FENCE_ADDED: + _I("[Place %d] Fence-%d added", __placeId, fenceId); + __startFence(fenceId); + __emitStateChange(); + break; + case GEOFENCE_MANAGE_FENCE_REMOVED: + _I("[Place-%d] Fence-%d removed", __placeId, fenceId); + __removeFence(fenceId); + __emitStateChange(); + break; + case GEOFENCE_MANAGE_FENCE_STARTED: + _D("[Place-%d] Fence-%d started", __placeId, fenceId); + break; + case GEOFENCE_MANAGE_FENCE_STOPPED: + _D("[Place-%d] Fence-%d stopped", __placeId, fenceId); + //TODO: Do we need to restart this? + break; + default: + _D("[Place-%d] Ignoring the manage event %d", __placeId, manage); + break; + } +} + +void ctx::GeofenceMonitorHandle::__updateState(int fenceId, geofence_state_e state) +{ + __geoStateMap[fenceId] = state; +} + +static const char* get_state_string(geofence_state_e state) +{ + switch (state) { + case GEOFENCE_STATE_IN: + return PLACE_GEOFENCE_IN; + case GEOFENCE_STATE_OUT: + return PLACE_GEOFENCE_OUT; + case GEOFENCE_STATE_UNCERTAIN: + return PLACE_GEOFENCE_UNCERTAIN; + default: + return PLACE_GEOFENCE_UNCERTAIN; + } +} + +void ctx::GeofenceMonitorHandle::__emitStateChange() +{ + geofence_state_e current_state = GEOFENCE_STATE_UNCERTAIN; + int outCount = 0; + + for (auto it = __geoStateMap.begin(); it != __geoStateMap.end(); ++it) { + if (it->second == GEOFENCE_STATE_IN) { + current_state = GEOFENCE_STATE_IN; + break; + } else if (it->second == GEOFENCE_STATE_OUT) { + ++ outCount; + } + } + + if (current_state != GEOFENCE_STATE_IN && outCount > 0) { + current_state = GEOFENCE_STATE_OUT; + } + + if (current_state == __prevState) { + return; + } + + __prevState = current_state; + + Json option; + option.set(NULL, PLACE_GEOFENCE_PLACE_ID, __placeId); + + Json data; + data.set(NULL, PLACE_GEOFENCE_PLACE_ID, __placeId); + data.set(NULL, PLACE_GEOFENCE_EVENT, get_state_string(current_state)); + + context_manager::publish(PLACE_SUBJ_GEOFENCE, option, ERR_NONE, data); +} + +bool ctx::GeofenceMonitorHandle::__fenceListCb(int geofenceId, geofence_h fence, int fenceIndex, int fenceCount, void* userData) +{ + _D("FenceID: %d, Index: %d, Count: %d", geofenceId, fenceIndex, fenceCount); + IF_FAIL_RETURN(fenceCount > 0, false); + + GeofenceMonitorHandle *handle = reinterpret_cast(userData); + return handle->__startFence(geofenceId); +} + +void ctx::GeofenceMonitorHandle::__fenceEventCb(int placeId, int geofenceId, geofence_manager_error_e error, geofence_manage_e manage, void* userData) +{ + IF_FAIL_VOID_TAG(error == GEOFENCE_MANAGER_ERROR_NONE, _W, "Geofence error: %d", error); + + GeofenceMonitorHandle *handle = reinterpret_cast(userData); + + IF_FAIL_VOID_TAG(placeId == handle->getPlaceId(), _W, "Mismatched Place ID"); + + handle->__updateFence(geofenceId, manage); +} + +void ctx::GeofenceMonitorHandle::__fenceStateCb(int geofenceId, geofence_state_e state, void* userData) +{ + GeofenceMonitorHandle *handle = reinterpret_cast(userData); + handle->__updateState(geofenceId, state); + handle->__emitStateChange(); +} diff --git a/src/place/geofence/GeofenceMonitorHandle.h b/src/place/geofence/GeofenceMonitorHandle.h new file mode 100644 index 0000000..3f15432 --- /dev/null +++ b/src/place/geofence/GeofenceMonitorHandle.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _CONTEXT_PLACE_GEOFENCE_MONITOR_HANDLE_H_ +#define _CONTEXT_PLACE_GEOFENCE_MONITOR_HANDLE_H_ + +#include +#include +#include + +namespace ctx { + + class GeofenceMonitorHandle { + + public: + GeofenceMonitorHandle(); + ~GeofenceMonitorHandle(); + + bool startMonitor(int placeId); + int getPlaceId(); + + private: + int __placeId; + geofence_state_e __prevState; + geofence_manager_h __geoHandle; + std::map __geoStateMap; + + void __emitStateChange(); + void __stopMonitor(); + bool __startFence(int fenceId); + void __removeFence(int fenceId); + void __updateFence(int fenceId, geofence_manage_e manage); + void __updateState(int fenceId, geofence_state_e state); + + static bool __fenceListCb(int geofenceId, geofence_h fence, int fenceIndex, int fenceCount, void* userData); + static void __fenceEventCb(int placeId, int geofenceId, geofence_manager_error_e error, geofence_manage_e manage, void* userData); + static void __fenceStateCb(int geofenceId, geofence_state_e state, void* userData); + }; + +} /* namespace ctx */ + +#endif /* End of _CONTEXT_PLACE_GEOFENCE_MONITOR_HANDLE_H_ */ diff --git a/src/place/geofence/PlaceGeofenceProvider.cpp b/src/place/geofence/PlaceGeofenceProvider.cpp new file mode 100644 index 0000000..a1a5b5f --- /dev/null +++ b/src/place/geofence/PlaceGeofenceProvider.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include "PlaceGeofenceProvider.h" + +ctx::PlaceGeofenceProvider *ctx::PlaceGeofenceProvider::__instance = NULL; + +ctx::PlaceGeofenceProvider::PlaceGeofenceProvider() +{ +} + +ctx::PlaceGeofenceProvider::~PlaceGeofenceProvider() +{ + for (auto it = __handleMap.begin(); it != __handleMap.end(); ++it) { + delete it->second; + } + + __handleMap.clear(); +} + +ctx::ContextProviderBase *ctx::PlaceGeofenceProvider::create(void *data) +{ + IF_FAIL_RETURN(!__instance, __instance); + __instance = new(std::nothrow) PlaceGeofenceProvider(); + IF_FAIL_RETURN_TAG(__instance, NULL, _E, "Memory allocation failed"); + _I(BLUE("Created")); + return __instance; +} + +void ctx::PlaceGeofenceProvider::destroy(void *data) +{ + IF_FAIL_VOID(__instance); + delete __instance; + __instance = NULL; + _I(BLUE("Destroyed")); +} + +bool ctx::PlaceGeofenceProvider::isSupported() +{ + bool supported = false; + int ret = geofence_manager_is_supported(&supported); + IF_FAIL_RETURN_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, false, _E, "geofence_manager_is_supported() failed"); + return supported; +} + +void ctx::PlaceGeofenceProvider::submitTriggerItem() +{ + context_manager::registerTriggerItem(PLACE_SUBJ_GEOFENCE, OPS_SUBSCRIBE, + "{" + "\"Event\":{\"type\":\"string\",\"values\":[\"In\",\"Out\"]}" + "}", + "{" + "\"PlaceId\":{\"type\":\"integer\",\"min\":1}" + "}"); +} + +void ctx::PlaceGeofenceProvider::__destroyIfUnused() +{ + IF_FAIL_VOID(__handleMap.empty()); + destroy(NULL); +} + + +int ctx::PlaceGeofenceProvider::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) +{ + int ret = __subscribe(option); + __destroyIfUnused(); + return ret; +} + +int ctx::PlaceGeofenceProvider::unsubscribe(const char *subject, ctx::Json option) +{ + int ret = __unsubscribe(option); + __destroyIfUnused(); + return ret; +} + +int ctx::PlaceGeofenceProvider::read(const char *subject, ctx::Json option, ctx::Json *requestResult) +{ + __destroyIfUnused(); + return ERR_NOT_SUPPORTED; +} + +int ctx::PlaceGeofenceProvider::write(const char *subject, ctx::Json data, ctx::Json *requestResult) +{ + __destroyIfUnused(); + return ERR_NOT_SUPPORTED; +} + +int ctx::PlaceGeofenceProvider::__subscribe(ctx::Json option) +{ + int placeId = -1; + option.get(NULL, PLACE_GEOFENCE_PLACE_ID, &placeId); + IF_FAIL_RETURN_TAG(placeId != -1, ERR_INVALID_PARAMETER, _E, "Getting PlaceID failed"); + + auto it = __handleMap.find(placeId); + if (it != __handleMap.end()) { + _D("Place ID %d is being monitored already", placeId); + return ERR_NONE; + } + + GeofenceMonitorHandle *handle = new(std::nothrow) GeofenceMonitorHandle(); + ASSERT_ALLOC(handle); + + bool ret = handle->startMonitor(placeId); + if (!ret) { + _E("Monitoring Place ID %d failed", placeId); + delete handle; + return ERR_OPERATION_FAILED; + } + + __handleMap[placeId] = handle; + + return ERR_NONE; +} + +int ctx::PlaceGeofenceProvider::__unsubscribe(ctx::Json option) +{ + int placeId = -1; + option.get(NULL, PLACE_GEOFENCE_PLACE_ID, &placeId); + IF_FAIL_RETURN_TAG(placeId != -1, ERR_INVALID_PARAMETER, _E, "Getting PlaceID failed"); + + auto it = __handleMap.find(placeId); + if (it == __handleMap.end()) { + _D("Place ID %d is not being monitored", placeId); + return ERR_NONE; + } + + delete it->second; + __handleMap.erase(it); + + return ERR_NONE; +} diff --git a/src/place/geofence/place_geofence.h b/src/place/geofence/PlaceGeofenceProvider.h similarity index 69% rename from src/place/geofence/place_geofence.h rename to src/place/geofence/PlaceGeofenceProvider.h index 739610f..a95f4c6 100644 --- a/src/place/geofence/place_geofence.h +++ b/src/place/geofence/PlaceGeofenceProvider.h @@ -14,24 +14,23 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_GEOFENCE_H__ -#define __CONTEXT_PLACE_GEOFENCE_H__ +#ifndef _CONTEXT_PLACE_GEOFENCE_PROVIDER_H_ +#define _CONTEXT_PLACE_GEOFENCE_PROVIDER_H_ #include #include -#include "myplace_handle.h" -#include "place_geofence_types.h" +#include "GeofenceMonitorHandle.h" +#include "PlaceGeofenceTypes.h" namespace ctx { - class place_geofence_provider : public ContextProviderBase { - typedef std::map handle_map_t; + class PlaceGeofenceProvider : public ContextProviderBase { public: static ContextProviderBase *create(void *data); static void destroy(void *data); - static bool is_supported(); - static void submit_trigger_item(); + static bool isSupported(); + static void submitTriggerItem(); int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); @@ -39,17 +38,17 @@ namespace ctx { int write(const char *subject, ctx::Json data, ctx::Json *requestResult); private: - static place_geofence_provider *__instance; - handle_map_t __handle_map; + static PlaceGeofenceProvider *__instance; + std::map __handleMap; - place_geofence_provider(); - ~place_geofence_provider(); + PlaceGeofenceProvider(); + ~PlaceGeofenceProvider(); int __subscribe(ctx::Json option); int __unsubscribe(ctx::Json option); - void __destroy_if_unused(); + void __destroyIfUnused(); }; } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_GEOFENCE_H__ */ +#endif /* End of _CONTEXT_PLACE_GEOFENCE_PROVIDER_H_ */ diff --git a/src/place/geofence/place_geofence_types.h b/src/place/geofence/PlaceGeofenceTypes.h similarity index 63% rename from src/place/geofence/place_geofence_types.h rename to src/place/geofence/PlaceGeofenceTypes.h index b9aa61a..fa66a41 100644 --- a/src/place/geofence/place_geofence_types.h +++ b/src/place/geofence/PlaceGeofenceTypes.h @@ -14,24 +14,22 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_GEOFENCE_TYPES__ -#define __CONTEXT_PLACE_GEOFENCE_TYPES__ +#ifndef _CONTEXT_PLACE_GEOFENCE_TYPES_H_ +#define _CONTEXT_PLACE_GEOFENCE_TYPES_H_ -// Context Items +// Subject #define PLACE_SUBJ_GEOFENCE "place/geofence" +// Privilege #define PLACE_PRIV_GEOFENCE "location" -// Option Keys -#define PLACE_STATUS_OPT_MYPLACE_ID "PlaceId" +// Option & Data Key +#define PLACE_GEOFENCE_PLACE_ID "PlaceId" +#define PLACE_GEOFENCE_EVENT "Event" -// Data Keys -#define PLACE_STATUS_DATA_MYPLACE_ID "PlaceId" -#define PLACE_STATUS_DATA_MYPLACE_EVENT "Event" +// Data Value +#define PLACE_GEOFENCE_UNCERTAIN "Uncertain" +#define PLACE_GEOFENCE_IN "In" +#define PLACE_GEOFENCE_OUT "Out" -// Data Values -#define MYPLACE_EVENT_UNCERTAIN "Uncertain" -#define MYPLACE_EVENT_IN "In" -#define MYPLACE_EVENT_OUT "Out" - -#endif +#endif /* End of _CONTEXT_PLACE_GEOFENCE_TYPES_H_ */ diff --git a/src/place/geofence/myplace_handle.cpp b/src/place/geofence/myplace_handle.cpp deleted file mode 100644 index d7b8fcc..0000000 --- a/src/place/geofence/myplace_handle.cpp +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include "place_geofence_types.h" -#include "myplace_handle.h" - -ctx::myplace_handle::myplace_handle() - : _place_id(-1) - , prev_state(GEOFENCE_STATE_UNCERTAIN) - , geo_handle(NULL) -{ -} - -ctx::myplace_handle::~myplace_handle() -{ - stop_monitor(); -} - -bool ctx::myplace_handle::start_monitor(int place_id) -{ - _D("Starts to monitor Place-%d", place_id); - - IF_FAIL_RETURN(place_id >= 0, false); - IF_FAIL_RETURN_TAG(geo_handle == NULL, false, _E, "Re-starting MyPlace monitor"); - - geofence_manager_create(&geo_handle); - IF_FAIL_RETURN_TAG(geo_handle, false, _E, "Geofence initialization failed"); - - int ret; - - ret = geofence_manager_set_geofence_state_changed_cb(geo_handle, fence_state_cb, this); - IF_FAIL_CATCH_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, _E, "Setting state callback failed"); - - ret = geofence_manager_set_geofence_event_cb(geo_handle, fence_event_cb, this); - IF_FAIL_CATCH_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, _E, "Setting event callback failed"); - - ret = geofence_manager_foreach_place_geofence_list(geo_handle, place_id, fence_list_cb, this); - IF_FAIL_CATCH_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, _E, "Getting fence list failed"); - - _place_id = place_id; - return true; - -CATCH: - stop_monitor(); - return false; -} - -int ctx::myplace_handle::get_place_id() -{ - return _place_id; -} - -void ctx::myplace_handle::stop_monitor() -{ - _D("Stops monitoring Place-%d", _place_id); - - //TODO: Do we need to stop all geofences explicitly? - if (geo_handle) { - geofence_manager_destroy(geo_handle); - geo_handle = NULL; - } - - geo_state_map.clear(); - _place_id = -1; - prev_state = GEOFENCE_STATE_UNCERTAIN; -} - -bool ctx::myplace_handle::start_fence(int fence_id) -{ - int ret; - - ret = geofence_manager_start(geo_handle, fence_id); - IF_FAIL_RETURN_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, true, _W, "Starting failed"); - - geofence_status_h status; - ret = geofence_status_create(fence_id, &status); - IF_FAIL_RETURN_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, true, _W, "Getting status failed"); - - geofence_state_e state = GEOFENCE_STATE_UNCERTAIN; - geofence_status_get_state(status, &state); - geofence_status_destroy(status); - - geo_state_map[fence_id] = state; - - return true; -} - -void ctx::myplace_handle::remove_fence(int fence_id) -{ - geofence_manager_stop(geo_handle, fence_id); - geo_state_map.erase(fence_id); -} - -void ctx::myplace_handle::update_fence(int fence_id, geofence_manage_e manage) -{ - switch (manage) { - case GEOFENCE_MANAGE_PLACE_REMOVED: - _W("[Place-%d] Removed", _place_id); - stop_monitor(); - break; - case GEOFENCE_MANAGE_FENCE_ADDED: - _I("[Place %d] Fence-%d added", _place_id, fence_id); - start_fence(fence_id); - emit_state_change(); - break; - case GEOFENCE_MANAGE_FENCE_REMOVED: - _I("[Place-%d] Fence-%d removed", _place_id, fence_id); - remove_fence(fence_id); - emit_state_change(); - break; - case GEOFENCE_MANAGE_FENCE_STARTED: - _D("[Place-%d] Fence-%d started", _place_id, fence_id); - break; - case GEOFENCE_MANAGE_FENCE_STOPPED: - _D("[Place-%d] Fence-%d stopped", _place_id, fence_id); - //TODO: Do we need to restart this? - break; - default: - _D("[Place-%d] Ignoring the manage event %d", _place_id, manage); - break; - } -} - -void ctx::myplace_handle::update_state(int fence_id, geofence_state_e state) -{ - geo_state_map[fence_id] = state; -} - -static const char* get_state_string(geofence_state_e state) -{ - switch (state) { - case GEOFENCE_STATE_IN: - return MYPLACE_EVENT_IN; - case GEOFENCE_STATE_OUT: - return MYPLACE_EVENT_OUT; - case GEOFENCE_STATE_UNCERTAIN: - return MYPLACE_EVENT_UNCERTAIN; - default: - return MYPLACE_EVENT_UNCERTAIN; - } -} - -void ctx::myplace_handle::emit_state_change() -{ - geofence_state_e current_state = GEOFENCE_STATE_UNCERTAIN; - int out_count = 0; - - for (geo_state_map_t::iterator it = geo_state_map.begin(); it != geo_state_map.end(); ++it) { - if (it->second == GEOFENCE_STATE_IN) { - current_state = GEOFENCE_STATE_IN; - break; - } else if (it->second == GEOFENCE_STATE_OUT) { - ++ out_count; - } - } - - if (current_state != GEOFENCE_STATE_IN && out_count > 0) { - current_state = GEOFENCE_STATE_OUT; - } - - if (current_state == prev_state) { - return; - } - - prev_state = current_state; - - Json option; - option.set(NULL, PLACE_STATUS_DATA_MYPLACE_ID, _place_id); - - Json data; - data.set(NULL, PLACE_STATUS_DATA_MYPLACE_ID, _place_id); - data.set(NULL, PLACE_STATUS_DATA_MYPLACE_EVENT, get_state_string(current_state)); - - context_manager::publish(PLACE_SUBJ_GEOFENCE, option, ERR_NONE, data); -} - -bool ctx::myplace_handle::fence_list_cb(int geofence_id, geofence_h fence, int fence_index, int fence_cnt, void* user_data) -{ - _D("FenceID: %d, Index: %d, Count: %d", geofence_id, fence_index, fence_cnt); - IF_FAIL_RETURN(fence_cnt > 0, false); - - myplace_handle *handle = reinterpret_cast(user_data); - return handle->start_fence(geofence_id); -} - -void ctx::myplace_handle::fence_event_cb(int place_id, int geofence_id, geofence_manager_error_e error, geofence_manage_e manage, void* user_data) -{ - IF_FAIL_VOID_TAG(error == GEOFENCE_MANAGER_ERROR_NONE, _W, "Geofence error: %d", error); - - myplace_handle *handle = reinterpret_cast(user_data); - - IF_FAIL_VOID_TAG(place_id == handle->get_place_id(), _W, "Mismatched Place ID"); - - handle->update_fence(geofence_id, manage); -} - -void ctx::myplace_handle::fence_state_cb(int geofence_id, geofence_state_e state, void* user_data) -{ - myplace_handle *handle = reinterpret_cast(user_data); - handle->update_state(geofence_id, state); - handle->emit_state_change(); -} diff --git a/src/place/geofence/myplace_handle.h b/src/place/geofence/myplace_handle.h deleted file mode 100644 index c8b4913..0000000 --- a/src/place/geofence/myplace_handle.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __CONTEXT_PLACE_MYPLACE_HANDLE_H__ -#define __CONTEXT_PLACE_MYPLACE_HANDLE_H__ - -#include -#include -#include -#include - -namespace ctx { - - class myplace_handle { - - typedef std::map geo_state_map_t; - typedef std::set string_set_t; - - public: - myplace_handle(); - ~myplace_handle(); - - bool start_monitor(int place_id); - int get_place_id(); - - private: - int _place_id; - geofence_state_e prev_state; - geofence_manager_h geo_handle; - geo_state_map_t geo_state_map; - - void emit_state_change(); - void stop_monitor(); - bool start_fence(int fence_id); - void remove_fence(int fence_id); - void update_fence(int fence_id, geofence_manage_e manage); - void update_state(int fence_id, geofence_state_e state); - - static bool fence_list_cb(int geofence_id, geofence_h fence, int fence_index, int fence_cnt, void* user_data); - static void fence_event_cb(int place_id, int geofence_id, geofence_manager_error_e error, geofence_manage_e manage, void* user_data); - static void fence_state_cb(int geofence_id, geofence_state_e state, void* user_data); - }; - -} /* namespace ctx */ - -#endif /* __CONTEXT_PLACE_MYPLACE_HANDLE_H__ */ diff --git a/src/place/geofence/place_geofence.cpp b/src/place/geofence/place_geofence.cpp deleted file mode 100644 index 5bcfb7f..0000000 --- a/src/place/geofence/place_geofence.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (c) 2015 Samsung Electronics Co., Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include -#include -#include -#include "place_geofence.h" - -ctx::place_geofence_provider *ctx::place_geofence_provider::__instance = NULL; - -ctx::place_geofence_provider::place_geofence_provider() -{ -} - -ctx::place_geofence_provider::~place_geofence_provider() -{ - for (handle_map_t::iterator it = __handle_map.begin(); it != __handle_map.end(); ++it) { - delete it->second; - } - - __handle_map.clear(); -} - -ctx::ContextProviderBase *ctx::place_geofence_provider::create(void *data) -{ - IF_FAIL_RETURN(!__instance, __instance); - __instance = new(std::nothrow) place_geofence_provider(); - IF_FAIL_RETURN_TAG(__instance, NULL, _E, "Memory allocation failed"); - _I(BLUE("Created")); - return __instance; -} - -void ctx::place_geofence_provider::destroy(void *data) -{ - IF_FAIL_VOID(__instance); - delete __instance; - __instance = NULL; - _I(BLUE("Destroyed")); -} - -bool ctx::place_geofence_provider::is_supported() -{ - bool supported = false; - int ret = geofence_manager_is_supported(&supported); - IF_FAIL_RETURN_TAG(ret == GEOFENCE_MANAGER_ERROR_NONE, false, _E, "geofence_manager_is_supported() failed"); - return supported; -} - -void ctx::place_geofence_provider::submit_trigger_item() -{ - context_manager::registerTriggerItem(PLACE_SUBJ_GEOFENCE, OPS_SUBSCRIBE, - "{" - "\"Event\":{\"type\":\"string\",\"values\":[\"In\",\"Out\"]}" - "}", - "{" - "\"PlaceId\":{\"type\":\"integer\",\"min\":1}" - "}"); -} - -void ctx::place_geofence_provider::__destroy_if_unused() -{ - IF_FAIL_VOID(__handle_map.empty()); - destroy(NULL); -} - - -int ctx::place_geofence_provider::subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult) -{ - int ret = __subscribe(option); - __destroy_if_unused(); - return ret; -} - -int ctx::place_geofence_provider::unsubscribe(const char *subject, ctx::Json option) -{ - int ret = __unsubscribe(option); - __destroy_if_unused(); - return ret; -} - -int ctx::place_geofence_provider::read(const char *subject, ctx::Json option, ctx::Json *requestResult) -{ - __destroy_if_unused(); - return ERR_NOT_SUPPORTED; -} - -int ctx::place_geofence_provider::write(const char *subject, ctx::Json data, ctx::Json *requestResult) -{ - __destroy_if_unused(); - return ERR_NOT_SUPPORTED; -} - -int ctx::place_geofence_provider::__subscribe(ctx::Json option) -{ - int pid = -1; - option.get(NULL, PLACE_STATUS_OPT_MYPLACE_ID, &pid); - IF_FAIL_RETURN_TAG(pid != -1, ERR_INVALID_PARAMETER, _E, "Getting PlaceID failed"); - - handle_map_t::iterator it = __handle_map.find(pid); - if (it != __handle_map.end()) { - _D("Place ID %d is being monitored already", pid); - return ERR_NONE; - } - - myplace_handle *handle = new(std::nothrow) myplace_handle(); - ASSERT_ALLOC(handle); - - bool ret = handle->start_monitor(pid); - if (!ret) { - _E("Monitoring Place ID %d failed", pid); - delete handle; - return ERR_OPERATION_FAILED; - } - - __handle_map[pid] = handle; - - return ERR_NONE; -} - -int ctx::place_geofence_provider::__unsubscribe(ctx::Json option) -{ - int pid = -1; - option.get(NULL, PLACE_STATUS_OPT_MYPLACE_ID, &pid); - IF_FAIL_RETURN_TAG(pid != -1, ERR_INVALID_PARAMETER, _E, "Getting PlaceID failed"); - - handle_map_t::iterator it = __handle_map.find(pid); - if (it == __handle_map.end()) { - _D("Place ID %d is not being monitored", pid); - return ERR_NONE; - } - - delete it->second; - __handle_map.erase(it); - - return ERR_NONE; -} diff --git a/src/place/recognition/place_recognition.cpp b/src/place/recognition/place_recognition.cpp index 0b1b790..0088b5e 100644 --- a/src/place/recognition/place_recognition.cpp +++ b/src/place/recognition/place_recognition.cpp @@ -71,7 +71,7 @@ int ctx::place_recognition_provider::write(const char *subject, ctx::Json data, return ERR_NOT_SUPPORTED; } -bool ctx::place_recognition_provider::is_supported() +bool ctx::place_recognition_provider::isSupported() { return true; } diff --git a/src/place/recognition/place_recognition.h b/src/place/recognition/place_recognition.h index 40a93ec..14d76d9 100644 --- a/src/place/recognition/place_recognition.h +++ b/src/place/recognition/place_recognition.h @@ -28,7 +28,7 @@ namespace ctx { public: static ContextProviderBase *create(void *data); static void destroy(void *data); - static bool is_supported(); + static bool isSupported(); int subscribe(const char *subject, ctx::Json option, ctx::Json *requestResult); int unsubscribe(const char *subject, ctx::Json option); -- 2.7.4 From a3ec22a4e061a26cb2a07baca635cc59f494873e Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Fri, 8 Apr 2016 10:55:36 +0900 Subject: [PATCH 10/16] Version 0.7.5 Change-Id: Ib8b9d452b443ddc929d2d1d5471061ec1d8e0fea Signed-off-by: Somin Kim --- 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 3ddb5eb..a259bde 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -1,6 +1,6 @@ Name: context-provider Summary: Context Provider -Version: 0.7.4 +Version: 0.7.5 Release: 1 Group: Service/Context License: Apache-2.0 -- 2.7.4 From 0715475f7a2656048225ea151dbc2b4381e5a04f Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Fri, 8 Apr 2016 18:05:49 +0200 Subject: [PATCH 11/16] Applying Tizen C++ coding style to place context provider(recognition) Change-Id: I7b6afc5838c13dd2098cbeaccca5d6f508ddd030 Signed-off-by: Marcin Masternak --- src/place/recognition/place_recognition.cpp | 4 +- src/place/recognition/place_recognition.h | 6 +- src/place/recognition/place_recognition_types.h | 10 +- src/place/recognition/user_places/debug_utils.cpp | 2 +- src/place/recognition/user_places/debug_utils.h | 8 +- src/place/recognition/user_places/gmap.cpp | 22 +- src/place/recognition/user_places/gmap.h | 18 +- src/place/recognition/user_places/graph.cpp | 14 +- src/place/recognition/user_places/graph.h | 22 +- .../user_places/location_listener_iface.h | 8 +- .../recognition/user_places/location_logger.cpp | 406 ++++++++++----------- .../recognition/user_places/location_logger.h | 126 +++---- src/place/recognition/user_places/mahal.cpp | 2 +- src/place/recognition/user_places/mahal.h | 14 +- src/place/recognition/user_places/median.h | 6 +- .../recognition/user_places/piecewise_lin.cpp | 29 +- src/place/recognition/user_places/piecewise_lin.h | 16 +- .../recognition/user_places/place_categer.cpp | 22 +- src/place/recognition/user_places/place_categer.h | 14 +- .../recognition/user_places/places_detector.cpp | 162 ++++---- .../recognition/user_places/places_detector.h | 63 ++-- .../recognition/user_places/prob_features_model.h | 14 +- .../user_places/{similar.h => similarity.h} | 20 +- src/place/recognition/user_places/user_places.cpp | 52 +-- src/place/recognition/user_places/user_places.h | 21 +- .../recognition/user_places/user_places_params.h | 6 +- .../recognition/user_places/user_places_types.cpp | 50 +-- .../recognition/user_places/user_places_types.h | 84 ++--- .../recognition/user_places/visit_categer.cpp | 78 ++-- src/place/recognition/user_places/visit_categer.h | 45 ++- .../recognition/user_places/visit_detector.cpp | 319 ++++++++-------- src/place/recognition/user_places/visit_detector.h | 113 +++--- .../recognition/user_places/visit_listener_iface.h | 10 +- .../recognition/user_places/wifi_listener_iface.h | 8 +- src/place/recognition/user_places/wifi_logger.cpp | 292 +++++++-------- src/place/recognition/user_places/wifi_logger.h | 111 +++--- 36 files changed, 1104 insertions(+), 1093 deletions(-) rename src/place/recognition/user_places/{similar.h => similarity.h} (66%) diff --git a/src/place/recognition/place_recognition.cpp b/src/place/recognition/place_recognition.cpp index 0088b5e..60b174f 100644 --- a/src/place/recognition/place_recognition.cpp +++ b/src/place/recognition/place_recognition.cpp @@ -53,8 +53,8 @@ int ctx::place_recognition_provider::read(const char *subject, ctx::Json option, _I(BLUE("Read")); _J("Option", option); - std::vector> places = engine.get_places(); - Json dataRead = UserPlaces::compose_json(places); + std::vector> places = engine.getPlaces(); + Json dataRead = UserPlaces::composeJson(places); // The below function needs to be called once. // It does not need to be called within this read() function. diff --git a/src/place/recognition/place_recognition.h b/src/place/recognition/place_recognition.h index 14d76d9..f5de60e 100644 --- a/src/place/recognition/place_recognition.h +++ b/src/place/recognition/place_recognition.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_RECOGNITION_H__ -#define __CONTEXT_PLACE_RECOGNITION_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_H_ +#define _CONTEXT_PLACE_RECOGNITION_H_ #include #include "place_recognition_types.h" @@ -46,4 +46,4 @@ namespace ctx { } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_RECOGNITION_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_H_ */ diff --git a/src/place/recognition/place_recognition_types.h b/src/place/recognition/place_recognition_types.h index f11f946..435ea4a 100644 --- a/src/place/recognition/place_recognition_types.h +++ b/src/place/recognition/place_recognition_types.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_RECOGNITION_TYPES__ -#define __CONTEXT_PLACE_RECOGNITION_TYPES__ +#ifndef _CONTEXT_PLACE_RECOGNITION_TYPES_ +#define _CONTEXT_PLACE_RECOGNITION_TYPES_ // Context Items #define PLACE_SUBJ_RECOGNITION "place/pattern/personal_poi" @@ -74,16 +74,16 @@ #define PLACE_CREATE_DATE "CreateDate" // Data values -typedef enum { +enum PlaceCategId { PLACE_CATEG_ID_NONE = 0, PLACE_CATEG_ID_HOME = 1, PLACE_CATEG_ID_WORK = 2, PLACE_CATEG_ID_OTHER = 3 -} place_categ_id_e; +}; typedef enum { PLACE_RECOG_HIGH_ACCURACY_MODE = 0, PLACE_RECOG_LOW_POWER_MODE = 1 } place_recog_mode_e; -#endif +#endif /* End of _CONTEXT_PLACE_RECOGNITION_TYPES_ */ diff --git a/src/place/recognition/user_places/debug_utils.cpp b/src/place/recognition/user_places/debug_utils.cpp index af7f7fe..064e41b 100644 --- a/src/place/recognition/user_places/debug_utils.cpp +++ b/src/place/recognition/user_places/debug_utils.cpp @@ -17,7 +17,7 @@ #include "debug_utils.h" #include -std::string ctx::DebugUtils::human_readable_date_time(time_t timestamp, std::string format, size_t size, bool utc) +std::string ctx::DebugUtils::humanReadableDateTime(time_t timestamp, std::string format, size_t size, bool utc) { struct tm * timeinfo; if (utc) { diff --git a/src/place/recognition/user_places/debug_utils.h b/src/place/recognition/user_places/debug_utils.h index f399f4a..dde40bc 100644 --- a/src/place/recognition/user_places/debug_utils.h +++ b/src/place/recognition/user_places/debug_utils.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_DEBUG_UTILS_H__ -#define __CONTEXT_PLACE_STATUS_DEBUG_UTILS_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_DEBUG_UTILS_H_ +#define _CONTEXT_PLACE_RECOGNITION_DEBUG_UTILS_H_ #include #include @@ -25,10 +25,10 @@ namespace ctx { class DebugUtils { public: - static std::string human_readable_date_time(time_t timestamp, std::string format, size_t size, bool utc = false); + static std::string humanReadableDateTime(time_t timestamp, std::string format, size_t size, bool utc = false); }; /* class DebugUtils */ } /* namespace ctx */ -#endif /*__CONTEXT_PLACE_STATUS_DEBUG_UTILS_H__*/ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_DEBUG_UTILS_H_ */ diff --git a/src/place/recognition/user_places/gmap.cpp b/src/place/recognition/user_places/gmap.cpp index 6ad114d..99b155a 100644 --- a/src/place/recognition/user_places/gmap.cpp +++ b/src/place/recognition/user_places/gmap.cpp @@ -18,7 +18,7 @@ #include #include -const std::string ctx::Gmap::html_header = R"( +const std::string ctx::Gmap::__htmlHeader = R"( @@ -42,7 +42,7 @@ function initialize() { var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); )"; -const std::string ctx::Gmap::html_footer = R"( +const std::string ctx::Gmap::__htmlFooter = R"( } google.maps.event.addDomListener(window, 'load', initialize); @@ -55,7 +55,7 @@ google.maps.event.addDomListener(window, 'load', initialize); )"; -std::string ctx::Gmap::icon_for_categ_id(place_categ_id_e categ_id) +std::string ctx::Gmap::__iconForCategId(PlaceCategId categ_id) { switch (categ_id) { case PLACE_CATEG_ID_HOME: return "markerH.png"; @@ -66,28 +66,28 @@ std::string ctx::Gmap::icon_for_categ_id(place_categ_id_e categ_id) } } -void ctx::Gmap::place_marker_to_stream(const ctx::Place& place, std::ostream& out) +void ctx::Gmap::__placeMarker2Stream(const ctx::Place& place, std::ostream& out) { if (place.location_valid) { out << "new google.maps.Marker({" << std::endl; out << " position: new google.maps.LatLng(" << place.location.latitude << "," << place.location.longitude << ")," << std::endl; out << " map: map," << std::endl; - out << " icon: \"http://maps.google.com/mapfiles/" << icon_for_categ_id(place.categ_id)<< "\"" << std::endl; + out << " icon: \"http://maps.google.com/mapfiles/" << __iconForCategId(place.categ_id)<< "\"" << std::endl; out << "});" << std::endl; } } -void ctx::Gmap::html_to_stream(const std::vector>& places, std::ostream& out) +void ctx::Gmap::__html2Stream(const std::vector>& places, std::ostream& out) { - out << html_header; + out << __htmlHeader; for (std::shared_ptr place : places) { - place_marker_to_stream(*place, out); + __placeMarker2Stream(*place, out); } - out << html_footer; + out << __htmlFooter; } -void ctx::Gmap::write_map(const std::vector>& places) +void ctx::Gmap::writeMap(const std::vector>& places) { std::ofstream out(GMAP_FILE); - html_to_stream(places, out); + __html2Stream(places, out); } diff --git a/src/place/recognition/user_places/gmap.h b/src/place/recognition/user_places/gmap.h index aca182d..5d1f885 100644 --- a/src/place/recognition/user_places/gmap.h +++ b/src/place/recognition/user_places/gmap.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_GMAP_H__ -#define __CONTEXT_PLACE_STATUS_GMAP_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_GMAP_H_ +#define _CONTEXT_PLACE_RECOGNITION_GMAP_H_ #include "user_places_types.h" #include "../place_recognition_types.h" @@ -31,17 +31,17 @@ namespace ctx { class Gmap { private: - const static std::string html_header; - const static std::string html_footer; - static std::string icon_for_categ_id(place_categ_id_e categ_id); - static void place_marker_to_stream(const Place& place, std::ostream& out); - static void html_to_stream(const std::vector>& places, std::ostream& out); + const static std::string __htmlHeader; + const static std::string __htmlFooter; + static std::string __iconForCategId(PlaceCategId categ_id); + static void __placeMarker2Stream(const Place& place, std::ostream& out); + static void __html2Stream(const std::vector>& places, std::ostream& out); public: - static void write_map(const std::vector>& places); + static void writeMap(const std::vector>& places); }; /* class Gmap */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_VISIT_GMAP_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_GMAP_H_ */ diff --git a/src/place/recognition/user_places/graph.cpp b/src/place/recognition/user_places/graph.cpp index e33ca2c..b8bab27 100644 --- a/src/place/recognition/user_places/graph.cpp +++ b/src/place/recognition/user_places/graph.cpp @@ -18,26 +18,26 @@ #include #include "graph.h" -std::shared_ptr ctx::connected_components(graph_t &graph) +std::shared_ptr ctx::graph::connectedComponents(Graph &graph) { - std::shared_ptr ccs = std::make_shared(); + std::shared_ptr ccs = std::make_shared(); std::set fringe; - for (node_t i = 0; i < static_cast(graph.size()); i++) { + for (Node i = 0; i < static_cast(graph.size()); i++) { if (!graph[i]) { continue; } // neighbourhood of node i exists (was not removed) - std::shared_ptr c = std::make_shared(); + std::shared_ptr c = std::make_shared(); ccs->push_back(c); fringe.insert(i); while (!fringe.empty()) { - node_t curr_node = *fringe.begin(); + Node curr_node = *fringe.begin(); fringe.erase(fringe.begin()); c->insert(curr_node); - std::shared_ptr curr_nhood = graph[curr_node]; - for (node_t nhood_node : *curr_nhood) { + std::shared_ptr curr_nhood = graph[curr_node]; + for (Node nhood_node : *curr_nhood) { if (graph[nhood_node] && fringe.find(nhood_node) == fringe.end()) { fringe.insert(nhood_node); } diff --git a/src/place/recognition/user_places/graph.h b/src/place/recognition/user_places/graph.h index 7310e11..9fedb26 100644 --- a/src/place/recognition/user_places/graph.h +++ b/src/place/recognition/user_places/graph.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_GRAPH_H__ -#define __CONTEXT_PLACE_STATUS_GRAPH_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_GRAPH_H_ +#define _CONTEXT_PLACE_RECOGNITION_GRAPH_H_ #include #include @@ -23,18 +23,22 @@ namespace ctx { - typedef int node_t; - typedef std::set nhood_t; // neighbouring nodes - typedef std::vector> graph_t; - typedef std::set component_t; - typedef std::vector> components_t; +namespace graph { + + typedef int Node; + typedef std::set NeighbourNodes; + typedef std::vector> Graph; + typedef std::set Component; + typedef std::vector> Components; /* * make connected components of a given graph * caution: the graph will be changed (its nodes will be cleared) */ - std::shared_ptr connected_components(graph_t &graph); + std::shared_ptr connectedComponents(Graph &graph); + +} /* namespace graph */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_GRAPH_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_GRAPH_H_ */ diff --git a/src/place/recognition/user_places/location_listener_iface.h b/src/place/recognition/user_places/location_listener_iface.h index 1085030..914e022 100644 --- a/src/place/recognition/user_places/location_listener_iface.h +++ b/src/place/recognition/user_places/location_listener_iface.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_LOCATION_LISTENER_IFACE_H__ -#define __CONTEXT_PLACE_STATUS_LOCATION_LISTENER_IFACE_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_LOCATION_LISTENER_IFACE_H_ +#define _CONTEXT_PLACE_RECOGNITION_LOCATION_LISTENER_IFACE_H_ #include "user_places_types.h" @@ -25,10 +25,10 @@ namespace ctx { public: virtual ~ILocationListener() {}; - virtual void on_new_location(location_event_s location) = 0; + virtual void onNewLocation(LocationEvent location) = 0; }; /* class ILocationListener */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_LOCATION_LISTENER_IFACE_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_LOCATION_LISTENER_IFACE_H_ */ diff --git a/src/place/recognition/user_places/location_logger.cpp b/src/place/recognition/user_places/location_logger.cpp index 3bcd109..47b5e37 100644 --- a/src/place/recognition/user_places/location_logger.cpp +++ b/src/place/recognition/user_places/location_logger.cpp @@ -41,23 +41,23 @@ #define _LOCATION_ERROR_LOG(error) { \ if (error != LOCATIONS_ERROR_NONE) { \ - _E("ERROR == %s", location_error_str(error)); \ + _E("ERROR == %s", __locationError2Str(error)); \ } else { \ _D("SUCCESS"); \ } \ } -void ctx::LocationLogger::location_service_state_changed_cb(location_service_state_e state, void *user_data) +void ctx::LocationLogger::__locationServiceStateChangedCb(location_service_state_e state, void *user_data) { - ctx::LocationLogger* location_logger_p = (ctx::LocationLogger *)user_data; - location_logger_p->location_service_state = state; + ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)user_data; + locationLogger->__locationServiceState = state; if (state == LOCATIONS_SERVICE_ENABLED) { _D("LOCATIONS_SERVICE_ENABLED"); - switch (location_logger_p->timer_purpose) { + switch (locationLogger->__timerPurpose) { case LOCATION_LOGGER_WAITING_FOR_SERVICE_START: _D("Waiting for location service start FINISHED"); - location_logger_p->timer_stop(); - location_logger_p->location_request(); + locationLogger->__timerStop(); + locationLogger->__locationRequest(); break; case LOCATION_LOGGER_WAITING_FOR_ACTIVE_REQUEST: case LOCATION_LOGGER_WAITING_FOR_LOCATION_METHOD_SETTING_ON: @@ -69,25 +69,25 @@ void ctx::LocationLogger::location_service_state_changed_cb(location_service_sta } } else { _D("LOCATIONS_SERVICE_DISABLED"); -// location_logger_p->timer_stop(); +// locationLogger->__timerStop(); } } -void ctx::LocationLogger::location_setting_changed_cb(location_method_e method, bool enable, void *user_data) +void ctx::LocationLogger::__locationSettingChangedCb(location_method_e method, bool enable, void *user_data) { - ctx::LocationLogger* location_logger_p = (ctx::LocationLogger *)user_data; - location_logger_p->location_method_state = enable; - if (method == location_logger_p->location_method) { + ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)user_data; + locationLogger->__locationMethodState = enable; + if (method == locationLogger->__locationMethod) { if (enable) { _D("Location method settings ON"); - switch (location_logger_p->timer_purpose) { + switch (locationLogger->__timerPurpose) { case LOCATION_LOGGER_WAITING_FOR_LOCATION_METHOD_SETTING_ON: _D("Waiting for location method settings on FINISHED"); - if (location_logger_p->location_service_state == LOCATIONS_SERVICE_ENABLED) { - location_logger_p->timer_stop(); - location_logger_p->location_request(); + if (locationLogger->__locationServiceState == LOCATIONS_SERVICE_ENABLED) { + locationLogger->__timerStop(); + locationLogger->__locationRequest(); } else { - location_logger_p->manager_start(); + locationLogger->__locationManagerStart(); } break; case LOCATION_LOGGER_WAITING_FOR_SERVICE_START: @@ -100,34 +100,34 @@ void ctx::LocationLogger::location_setting_changed_cb(location_method_e method, } } else { _D("Location method settings OFF"); -// location_logger_p->timer_stop(); +// locationLogger->__timerStop(); } } } -void ctx::LocationLogger::position_updated_cb(double latitude, double longitude, +void ctx::LocationLogger::__positionUpdatedCb(double latitude, double longitude, double altitude, time_t timestamp, void *user_data) { _D(""); - ctx::LocationLogger* location_logger_p = (ctx::LocationLogger *)user_data; - double horizontal = location_logger_p->manager_get_horizontal_accuracy(); + ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)user_data; + double horizontal = locationLogger->__locationManagerGetHorizontalAccuracy(); #ifdef TIZEN_ENGINEER_MODE - ctx::location_event_s location(latitude, longitude, horizontal, timestamp, LOCATION_METHOD_REQUEST); + ctx::LocationEvent location(latitude, longitude, horizontal, timestamp, LOCATION_METHOD_REQUEST); #else /* TIZEN_ENGINEER_MODE */ - ctx::location_event_s location(latitude, longitude, horizontal, timestamp); + ctx::LocationEvent location(latitude, longitude, horizontal, timestamp); #endif /* TIZEN_ENGINEER_MODE */ - location_logger_p->broadcast(location); - location_logger_p->on_active_request_succeeded(); + locationLogger->__broadcast(location); + locationLogger->__onActiveRequestSucceeded(); } -void ctx::LocationLogger::location_updated_cb(location_error_e error, double latitude, double longitude, +void ctx::LocationLogger::__locationUpdatedCb(location_error_e error, double latitude, double longitude, double altitude, time_t timestamp, double speed, double direction, double climb, void *user_data) { _D(""); - position_updated_cb(latitude, longitude, altitude, timestamp, user_data); + __positionUpdatedCb(latitude, longitude, altitude, timestamp, user_data); } -const char* ctx::LocationLogger::location_error_str(int error) +const char* ctx::LocationLogger::__locationError2Str(int error) { switch (error) { case LOCATIONS_ERROR_NONE: @@ -156,7 +156,7 @@ const char* ctx::LocationLogger::location_error_str(int error) } -void ctx::LocationLogger::log(location_accessibility_state_e state) +void ctx::LocationLogger::__log(location_accessibility_state_e state) { switch (state) { case LOCATIONS_ACCESS_STATE_NONE : // Access state is not determined @@ -173,14 +173,14 @@ void ctx::LocationLogger::log(location_accessibility_state_e state) } } -int ctx::LocationLogger::create_table() +int ctx::LocationLogger::__dbCreateTable() { bool ret = db_manager::create_table(0, LOCATION_TABLE_NAME, LOCATION_CREATE_TABLE_COLUMNS, NULL, NULL); _D("%s -> Table Creation Request", ret ? "SUCCESS" : "FAIL"); return 0; } -int ctx::LocationLogger::db_insert_log(location_event_s location_event) +int ctx::LocationLogger::__dbInsertLog(LocationEvent location_event) { Json data; data.set(NULL, LOCATION_COLUMN_LATITUDE, location_event.coordinates.latitude); @@ -188,7 +188,7 @@ int ctx::LocationLogger::db_insert_log(location_event_s location_event) data.set(NULL, LOCATION_COLUMN_ACCURACY, location_event.coordinates.accuracy); data.set(NULL, LOCATION_COLUMN_TIMESTAMP, static_cast(location_event.timestamp)); #ifdef TIZEN_ENGINEER_MODE - std::string time_human = DebugUtils::human_readable_date_time(location_event.timestamp, "%F %T", 80); + std::string time_human = DebugUtils::humanReadableDateTime(location_event.timestamp, "%F %T", 80); data.set(NULL, LOCATION_COLUMN_TIMESTAMP_HUMAN, time_human); data.set(NULL, LOCATION_COLUMN_METHOD, static_cast(location_event.method)); #endif /* TIZEN_ENGINEER_MODE */ @@ -199,94 +199,94 @@ int ctx::LocationLogger::db_insert_log(location_event_s location_event) return ret; } -ctx::LocationLogger::LocationLogger(ILocationListener *listener_, bool test_mode_) - : listener(listener_) - , test_mode(test_mode_) - , active_request_attempts(0) - , active_attempts(0) - , all_attempts(0) - , location_count(0) - , active_request_succeeded(false) - , active_location_succeeded(false) - , timer_id(-1) - , timer_timestamp(0) - , timer_purpose(LOCATION_LOGGER_WAITING_FOR_PASSIVE_INTERVAL) - , location_service_state(LOCATIONS_SERVICE_DISABLED) - , location_method(LOCATION_LOGGER_METHOD) - , location_method_state(false) +ctx::LocationLogger::LocationLogger(ILocationListener *listener, bool testMode) : + __listener(listener), + __testMode(testMode), + __activeRequestAttempts(0), + __activeAttempts(0), + __allAttempts(0), + __locationCount(0), + __activeRequestSucceeded(false), + __activeLocationSucceeded(false), + __timerId(-1), + __timerTimestamp(0), + __timerPurpose(LOCATION_LOGGER_WAITING_FOR_PASSIVE_INTERVAL), + __locationServiceState(LOCATIONS_SERVICE_DISABLED), + __locationMethod(LOCATION_LOGGER_METHOD), + __locationMethodState(false) { _D("CONSTRUCTOR"); - manager_create(); + __locationManagerCreate(); - if (test_mode) { + if (__testMode) { return; } if (LOCATION_LOGGER_DATABASE) { - create_table(); + __dbCreateTable(); } - manager_set_service_state_changed_cb(); - manager_set_setting_changed_cb(); - location_method_state = manager_is_enabled_method(location_method); + __locationManagerSetServiceStateChangedCb(); + __locationManagerSetSettingChangedCb(); + __locationMethodState = __locationManagerIsEnabledMethod(__locationMethod); } ctx::LocationLogger::~LocationLogger() { _D("DESTRUCTOR"); - stop_logging(); - manager_unset_service_state_changed_cb(); - manager_unset_setting_changed_cb(); - manager_destroy(); + __stopLogging(); + __locationManagerUnsetServiceStateChangedCb(); + __locationManagerUnsetSettingChangedCb(); + __locationManagerDestroy(); } -void ctx::LocationLogger::manager_create() +void ctx::LocationLogger::__locationManagerCreate() { - int ret = location_manager_create(location_method, &manager); + int ret = location_manager_create(__locationMethod, &__locationManager); _LOCATION_ERROR_LOG(ret); } -void ctx::LocationLogger::manager_destroy() +void ctx::LocationLogger::__locationManagerDestroy() { - int ret = location_manager_destroy(manager); + int ret = location_manager_destroy(__locationManager); _LOCATION_ERROR_LOG(ret); } -void ctx::LocationLogger::manager_set_service_state_changed_cb() +void ctx::LocationLogger::__locationManagerSetServiceStateChangedCb() { - int ret = location_manager_set_service_state_changed_cb(manager, location_service_state_changed_cb, this); + int ret = location_manager_set_service_state_changed_cb(__locationManager, __locationServiceStateChangedCb, this); _LOCATION_ERROR_LOG(ret); } -void ctx::LocationLogger::manager_unset_service_state_changed_cb() +void ctx::LocationLogger::__locationManagerUnsetServiceStateChangedCb() { - int ret = location_manager_unset_service_state_changed_cb(manager); + int ret = location_manager_unset_service_state_changed_cb(__locationManager); _LOCATION_ERROR_LOG(ret); } -void ctx::LocationLogger::manager_start() +void ctx::LocationLogger::__locationManagerStart() { - int ret = location_manager_start(manager); + int ret = location_manager_start(__locationManager); _LOCATION_ERROR_LOG(ret); - start_service_timer_start(); + __startServiceTimerStart(); } -void ctx::LocationLogger::manager_stop() +void ctx::LocationLogger::__locationManagerStop() { - int ret = location_manager_stop(manager); + int ret = location_manager_stop(__locationManager); _LOCATION_ERROR_LOG(ret); } -double ctx::LocationLogger::manager_get_horizontal_accuracy() +double ctx::LocationLogger::__locationManagerGetHorizontalAccuracy() { location_accuracy_level_e accuracy_level; double horizontal, vertical; - int ret = location_manager_get_accuracy(manager, &accuracy_level, &horizontal, &vertical); + int ret = location_manager_get_accuracy(__locationManager, &accuracy_level, &horizontal, &vertical); _LOCATION_ERROR_LOG(ret); return horizontal; } -location_accessibility_state_e ctx::LocationLogger::manager_get_accessibility_state() +location_accessibility_state_e ctx::LocationLogger::__locationManagerGetAccessibilityState() { location_accessibility_state_e state; int ret = location_manager_get_accessibility_state(&state); @@ -294,109 +294,109 @@ location_accessibility_state_e ctx::LocationLogger::manager_get_accessibility_st return state; } -void ctx::LocationLogger::manager_set_setting_changed_cb() +void ctx::LocationLogger::__locationManagerSetSettingChangedCb() { - int ret = location_manager_set_setting_changed_cb(location_method, location_setting_changed_cb, this); + int ret = location_manager_set_setting_changed_cb(__locationMethod, __locationSettingChangedCb, this); _LOCATION_ERROR_LOG(ret); } -void ctx::LocationLogger::manager_unset_setting_changed_cb() +void ctx::LocationLogger::__locationManagerUnsetSettingChangedCb() { - int ret = location_manager_unset_setting_changed_cb(location_method); + int ret = location_manager_unset_setting_changed_cb(__locationMethod); _LOCATION_ERROR_LOG(ret); } -bool ctx::LocationLogger::manager_request_single_location() +bool ctx::LocationLogger::__locationManagerRequestSingleLocation() { - int ret = location_manager_request_single_location(manager, - LOCATION_LOGGER_ACTIVE_REQUEST_TIMEOUT_SECONDS, location_updated_cb, this); + int ret = location_manager_request_single_location(__locationManager, + LOCATION_LOGGER_ACTIVE_REQUEST_TIMEOUT_SECONDS, __locationUpdatedCb, this); _D("%s (seconds=%d) ----- ATTEMPTS: REQ[%d/%d], ACT[%d/%d], ALL[%d/%d]; ----- LOCATIONS:[%d/%d]", ret == LOCATIONS_ERROR_NONE ? "SUCCESS" : "ERROR", LOCATION_LOGGER_ACTIVE_REQUEST_TIMEOUT_SECONDS, - active_request_attempts, + __activeRequestAttempts, LOCATION_LOGGER_MAX_ACTIVE_REQUEST_ATTEMPTS, - active_attempts, + __activeAttempts, LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS, - all_attempts, + __allAttempts, LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS, - location_count, + __locationCount, LOCATION_LOGGER_MAX_LOCATION_COUNT); _LOCATION_ERROR_LOG(ret); - active_request_attempts++; - active_attempts++; - all_attempts++; + __activeRequestAttempts++; + __activeAttempts++; + __allAttempts++; if (ret == LOCATIONS_ERROR_NONE) { - active_request_timer_start(); + __activeRequestTimerStart(); return true; } else { return false; } } -bool ctx::LocationLogger::manager_get_location() +bool ctx::LocationLogger::__locationManagerGetLocation() { double altitude, latitude, longitude, climb, direction, speed, horizontal, vertical; location_accuracy_level_e level; time_t timestamp; - int ret = location_manager_get_location(manager, &altitude, &latitude, &longitude, + int ret = location_manager_get_location(__locationManager, &altitude, &latitude, &longitude, &climb, &direction, &speed, &level, &horizontal, &vertical, ×tamp); _D("%s ----- ATTEMPTS: REQ[%d/%d], ACT[%d/%d], ALL[%d/%d]; ----- LOCATIONS:[%d/%d]", ret == LOCATIONS_ERROR_NONE ? "SUCCESS" : "ERROR", - active_request_attempts, + __activeRequestAttempts, LOCATION_LOGGER_MAX_ACTIVE_REQUEST_ATTEMPTS, - active_attempts, + __activeAttempts, LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS, - all_attempts, + __allAttempts, LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS, - location_count, + __locationCount, LOCATION_LOGGER_MAX_LOCATION_COUNT); _LOCATION_ERROR_LOG(ret); - active_attempts++; - all_attempts++; + __activeAttempts++; + __allAttempts++; if (ret == LOCATIONS_ERROR_NONE) { #ifdef TIZEN_ENGINEER_MODE - ctx::location_event_s location(latitude, longitude, horizontal, timestamp, LOCATION_METHOD_GET_LOCATION); + ctx::LocationEvent location(latitude, longitude, horizontal, timestamp, LOCATION_METHOD_GET_LOCATION); #else /* TIZEN_ENGINEER_MODE */ - ctx::location_event_s location(latitude, longitude, horizontal, timestamp); + ctx::LocationEvent location(latitude, longitude, horizontal, timestamp); #endif /* TIZEN_ENGINEER_MODE */ - broadcast(location); - on_active_location_succeeded(); + __broadcast(location); + __onActiveLocationSucceeded(); return true; } else { return false; } } -void ctx::LocationLogger::manager_get_last_location() +void ctx::LocationLogger::__locationManagerGetLastLocation() { double altitude, latitude, longitude, climb, direction, speed, horizontal, vertical; location_accuracy_level_e level; time_t timestamp; - int ret = location_manager_get_last_location(manager, &altitude, &latitude, &longitude, + int ret = location_manager_get_last_location(__locationManager, &altitude, &latitude, &longitude, &climb, &direction, &speed, &level, &horizontal, &vertical, ×tamp); _D("%s ----- ATTEMPTS: REQ[%d/%d], ACT[%d/%d], ALL[%d/%d]; ----- LOCATIONS:[%d/%d]", ret == LOCATIONS_ERROR_NONE ? "SUCCESS" : "ERROR", - active_request_attempts, + __activeRequestAttempts, LOCATION_LOGGER_MAX_ACTIVE_REQUEST_ATTEMPTS, - active_attempts, + __activeAttempts, LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS, - all_attempts, + __allAttempts, LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS, - location_count, + __locationCount, LOCATION_LOGGER_MAX_LOCATION_COUNT); _LOCATION_ERROR_LOG(ret); - all_attempts++; + __allAttempts++; if (ret == LOCATIONS_ERROR_NONE) { #ifdef TIZEN_ENGINEER_MODE - ctx::location_event_s location(latitude, longitude, horizontal, timestamp, LOCATION_METHOD_GET_LAST_LOCATION); + ctx::LocationEvent location(latitude, longitude, horizontal, timestamp, LOCATION_METHOD_GET_LAST_LOCATION); #else /* TIZEN_ENGINEER_MODE */ - ctx::location_event_s location(latitude, longitude, horizontal, timestamp); + ctx::LocationEvent location(latitude, longitude, horizontal, timestamp); #endif /* TIZEN_ENGINEER_MODE */ - broadcast(location); + __broadcast(location); } } -bool ctx::LocationLogger::manager_is_enabled_method(location_method_e method) +bool ctx::LocationLogger::__locationManagerIsEnabledMethod(location_method_e method) { bool enable; int ret = location_manager_is_enabled_method(method, &enable); @@ -404,211 +404,211 @@ bool ctx::LocationLogger::manager_is_enabled_method(location_method_e method) return enable; } -bool ctx::LocationLogger::check_general_limits() +bool ctx::LocationLogger::__checkGeneralLimits() { - return (location_count < LOCATION_LOGGER_MAX_LOCATION_COUNT - && all_attempts < LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS); + return (__locationCount < LOCATION_LOGGER_MAX_LOCATION_COUNT + && __allAttempts < LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS); } -bool ctx::LocationLogger::check_active_limits() +bool ctx::LocationLogger::__checkActiveLimits() { - return (!active_location_succeeded - && active_attempts < LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS); + return (!__activeLocationSucceeded + && __activeAttempts < LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS); } -bool ctx::LocationLogger::check_active_request_limits() +bool ctx::LocationLogger::__checkActiveRequestLimits() { - return (!active_request_succeeded - && active_request_attempts < LOCATION_LOGGER_MAX_ACTIVE_REQUEST_ATTEMPTS); + return (!__activeRequestSucceeded + && __activeRequestAttempts < LOCATION_LOGGER_MAX_ACTIVE_REQUEST_ATTEMPTS); } -void ctx::LocationLogger::location_request() +void ctx::LocationLogger::__locationRequest() { _D(""); bool request_single_location_ret = false; bool get_location_ret = false; - if (check_general_limits() && check_active_limits() && check_active_request_limits()) { - request_single_location_ret = manager_request_single_location(); + if (__checkGeneralLimits() && __checkActiveLimits() && __checkActiveRequestLimits()) { + request_single_location_ret = __locationManagerRequestSingleLocation(); } - if (check_general_limits() && check_active_limits() && !request_single_location_ret) { - get_location_ret = manager_get_location(); + if (__checkGeneralLimits() && __checkActiveLimits() && !request_single_location_ret) { + get_location_ret = __locationManagerGetLocation(); } - if (check_general_limits() && !request_single_location_ret && !get_location_ret - && active_attempts >= LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS) { - manager_get_last_location(); + if (__checkGeneralLimits() && !request_single_location_ret && !get_location_ret + && __activeAttempts >= LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS) { + __locationManagerGetLastLocation(); } if (!request_single_location_ret) { - manager_stop(); - set_next_timer(); + __locationManagerStop(); + __setNextTimer(); } } -void ctx::LocationLogger::set_next_timer() +void ctx::LocationLogger::__setNextTimer() { _D("ATTEMPTS: REQ[%d/%d], ACT[%d/%d], ALL[%d/%d]; ----- LOCATIONS:[%d/%d])", - active_request_attempts, + __activeRequestAttempts, LOCATION_LOGGER_MAX_ACTIVE_REQUEST_ATTEMPTS, - active_attempts, + __activeAttempts, LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS, - all_attempts, + __allAttempts, LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS, - location_count, + __locationCount, LOCATION_LOGGER_MAX_LOCATION_COUNT); - if (check_general_limits()) { - if (check_active_limits()) { - active_interval_timer_start(); + if (__checkGeneralLimits()) { + if (__checkActiveLimits()) { + __activeIntervalTimerStart(); } else { - passive_interval_timer_start(); + __passiveIntervalTimerStart(); } } } -void ctx::LocationLogger::on_active_request_succeeded() +void ctx::LocationLogger::__onActiveRequestSucceeded() { _D(""); - manager_stop(); - active_request_succeeded = true; - on_active_location_succeeded(); + __locationManagerStop(); + __activeRequestSucceeded = true; + __onActiveLocationSucceeded(); } -void ctx::LocationLogger::on_active_location_succeeded() +void ctx::LocationLogger::__onActiveLocationSucceeded() { _D(""); - active_location_succeeded = true; + __activeLocationSucceeded = true; } -void ctx::LocationLogger::broadcast(ctx::location_event_s location_event) +void ctx::LocationLogger::__broadcast(ctx::LocationEvent location_event) { _D(""); - location_count++; - if (listener) { - listener->on_new_location(location_event); + __locationCount++; + if (__listener) { + __listener->onNewLocation(location_event); } if (LOCATION_LOGGER_DATABASE) { - db_insert_log(location_event); + __dbInsertLog(location_event); } } bool ctx::LocationLogger::onTimerExpired(int id) { time_t now = time(nullptr); - double seconds = difftime(now, timer_timestamp); + double seconds = difftime(now, __timerTimestamp); - switch (timer_purpose) { + switch (__timerPurpose) { case LOCATION_LOGGER_WAITING_FOR_ACTIVE_REQUEST: - _D("Active request FAILED, timer_id = %d[%d], from start = %.1fs", id, timer_id, seconds); - manager_stop(); - set_next_timer(); + _D("Active request FAILED, timerId = %d[%d], from start = %.1fs", id, __timerId, seconds); + __locationManagerStop(); + __setNextTimer(); return false; case LOCATION_LOGGER_WAITING_FOR_SERVICE_START: - _D("Service start in timeout time FAILED, timer_id = %d[%d], from start = %.1fs", id, timer_id, seconds); + _D("Service start in timeout time FAILED, timerId = %d[%d], from start = %.1fs", id, __timerId, seconds); // Waiting for service start FAILURE is also some kind of active request attempt - active_request_attempts++; - active_attempts++; - all_attempts++; - manager_stop(); - set_next_timer(); + __activeRequestAttempts++; + __activeAttempts++; + __allAttempts++; + __locationManagerStop(); + __setNextTimer(); return false; case LOCATION_LOGGER_WAITING_FOR_LOCATION_METHOD_SETTING_ON: - _D("Still waiting for Location method settings on, timer_id = %d[%d], from start = %.1fs", id, timer_id, seconds); + _D("Still waiting for Location method settings on, timerId = %d[%d], from start = %.1fs", id, __timerId, seconds); // Do nothing return false; case LOCATION_LOGGER_WAITING_FOR_ACTIVE_INTERVAL: - _D("Active interval time expired, timer_id = %d[%d], from start = %.1fs", id, timer_id, seconds); + _D("Active interval time expired, timerId = %d[%d], from start = %.1fs", id, __timerId, seconds); break; case LOCATION_LOGGER_WAITING_FOR_PASSIVE_INTERVAL: - _D("Passive interval time expired, timer_id = %d[%d], from start = %.1fs", id, timer_id, seconds); + _D("Passive interval time expired, timerId = %d[%d], from start = %.1fs", id, __timerId, seconds); break; default: - _D("Do nothing, timer_id = %d[%d], from start = %.1fs", id, timer_id, seconds); + _D("Do nothing, timerId = %d[%d], from start = %.1fs", id, __timerId, seconds); return false; } - if (location_method_state) { - manager_start(); + if (__locationMethodState) { + __locationManagerStart(); } else { - timer_purpose = LOCATION_LOGGER_WAITING_FOR_LOCATION_METHOD_SETTING_ON; + __timerPurpose = LOCATION_LOGGER_WAITING_FOR_LOCATION_METHOD_SETTING_ON; _D("LOCATION_LOGGER_WAITING_FOR_LOCATION_METHOD_SETTING_ON"); } return false; } -void ctx::LocationLogger::active_request_timer_start() +void ctx::LocationLogger::__activeRequestTimerStart() { int minutes = LOCATION_LOGGER_ACTIVE_REQUEST_TIMEOUT_SECONDS / 60; if (LOCATION_LOGGER_ACTIVE_REQUEST_TIMEOUT_SECONDS % 60) { minutes++; } - timer_purpose = LOCATION_LOGGER_WAITING_FOR_ACTIVE_REQUEST; + __timerPurpose = LOCATION_LOGGER_WAITING_FOR_ACTIVE_REQUEST; _D("LOCATION_LOGGER_WAITING_FOR_ACTIVE_REQUEST (minutes=%d)", minutes); - timer_start(minutes); + __timerStart(minutes); } -void ctx::LocationLogger::start_service_timer_start() +void ctx::LocationLogger::__startServiceTimerStart() { - timer_purpose = LOCATION_LOGGER_WAITING_FOR_SERVICE_START; + __timerPurpose = LOCATION_LOGGER_WAITING_FOR_SERVICE_START; _D("LOCATION_LOGGER_WAITING_FOR_SERVICE_START"); - timer_start(LOCATION_LOGGER_SERVICE_START_TIMEOUT_MINUTES); + __timerStart(LOCATION_LOGGER_SERVICE_START_TIMEOUT_MINUTES); } -void ctx::LocationLogger::active_interval_timer_start() +void ctx::LocationLogger::__activeIntervalTimerStart() { - timer_purpose = LOCATION_LOGGER_WAITING_FOR_ACTIVE_INTERVAL; + __timerPurpose = LOCATION_LOGGER_WAITING_FOR_ACTIVE_INTERVAL; _D("LOCATION_LOGGER_WAITING_FOR_ACTIVE_INTERVAL"); - timer_start(LOCATION_LOGGER_ACTIVE_INTERVAL_MINUTES); + __timerStart(LOCATION_LOGGER_ACTIVE_INTERVAL_MINUTES); } -void ctx::LocationLogger::passive_interval_timer_start() +void ctx::LocationLogger::__passiveIntervalTimerStart() { - timer_purpose = LOCATION_LOGGER_WAITING_FOR_PASSIVE_INTERVAL; + __timerPurpose = LOCATION_LOGGER_WAITING_FOR_PASSIVE_INTERVAL; _D("LOCATION_LOGGER_WAITING_FOR_PASSIVE_INTERVAL"); - timer_start(LOCATION_LOGGER_PASSIVE_INTERVAL_MINUTES); + __timerStart(LOCATION_LOGGER_PASSIVE_INTERVAL_MINUTES); } -void ctx::LocationLogger::timer_start(time_t minutes) +void ctx::LocationLogger::__timerStart(time_t minutes) { - timer_timestamp = time(nullptr); - timer_id = __timerManager.setFor(minutes, this); - _D("%s (minutes=%d) timer_id = %d", timer_id >= 0 ? "SUCCESS" : "ERROR", minutes, timer_id); + __timerTimestamp = time(nullptr); + __timerId = __timerManager.setFor(minutes, this); + _D("%s (minutes=%d) timerId = %d", __timerId >= 0 ? "SUCCESS" : "ERROR", minutes, __timerId); } -void ctx::LocationLogger::timer_stop() +void ctx::LocationLogger::__timerStop() { _D(""); - __timerManager.remove(timer_id); + __timerManager.remove(__timerId); } -void ctx::LocationLogger::start_logging() +void ctx::LocationLogger::__startLogging() { _D(""); - active_request_attempts = 0; - active_attempts = 0; - all_attempts = 0; - location_count = 0; - active_request_succeeded = false;; - active_location_succeeded = false; - manager_start(); + __activeRequestAttempts = 0; + __activeAttempts = 0; + __allAttempts = 0; + __locationCount = 0; + __activeRequestSucceeded = false;; + __activeLocationSucceeded = false; + __locationManagerStart(); } -void ctx::LocationLogger::stop_logging() +void ctx::LocationLogger::__stopLogging() { _D(""); - timer_stop(); - manager_stop(); + __timerStop(); + __locationManagerStop(); } -void ctx::LocationLogger::on_visit_start() +void ctx::LocationLogger::onVisitStart() { _D(""); - if (!test_mode) { - start_logging(); + if (!__testMode) { + __startLogging(); } } -void ctx::LocationLogger::on_visit_end() +void ctx::LocationLogger::onVisitEnd() { _D(""); - if (!test_mode) { - stop_logging(); + if (!__testMode) { + __stopLogging(); } } diff --git a/src/place/recognition/user_places/location_logger.h b/src/place/recognition/user_places/location_logger.h index f27bd31..caa1f21 100644 --- a/src/place/recognition/user_places/location_logger.h +++ b/src/place/recognition/user_places/location_logger.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_LOCATION_LOGGER_H__ -#define __CONTEXT_PLACE_STATUS_LOCATION_LOGGER_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_LOCATION_LOGGER_H_ +#define _CONTEXT_PLACE_RECOGNITION_LOCATION_LOGGER_H_ #include #include @@ -54,112 +54,112 @@ namespace ctx { - typedef enum { + enum TimerPurpose { LOCATION_LOGGER_WAITING_FOR_ACTIVE_REQUEST = 0, LOCATION_LOGGER_WAITING_FOR_SERVICE_START = 1, LOCATION_LOGGER_WAITING_FOR_LOCATION_METHOD_SETTING_ON = 2, LOCATION_LOGGER_WAITING_FOR_ACTIVE_INTERVAL = 3, LOCATION_LOGGER_WAITING_FOR_PASSIVE_INTERVAL = 4 - } timer_purpose_e; + }; class LocationLogger : public ITimerListener, public IVisitListener { public: - LocationLogger(ILocationListener *listener_ = nullptr, - bool test_mode_ = false); + LocationLogger(ILocationListener *listener = nullptr, + bool testMode = false); ~LocationLogger(); + private: /* INPUT */ - void on_visit_start(); - void on_visit_end(); + void onVisitStart(); + void onVisitEnd(); - private: /* OUTPUT */ - ILocationListener * const listener; - void broadcast(location_event_s location_event); + ILocationListener * const __listener; + void __broadcast(LocationEvent location_event); /* INTERNAL */ - bool test_mode; - void start_logging(); - void stop_logging(); - void location_request(); - void on_active_request_succeeded(); - void on_active_location_succeeded(); + bool __testMode; + void __startLogging(); + void __stopLogging(); + void __locationRequest(); + void __onActiveRequestSucceeded(); + void __onActiveLocationSucceeded(); /* INTERNAL : COUNTERS (LIMITS) */ - int active_request_attempts; - int active_attempts; - int all_attempts; - int location_count; - bool check_general_limits(); - bool check_active_limits(); - bool check_active_request_limits(); + int __activeRequestAttempts; + int __activeAttempts; + int __allAttempts; + int __locationCount; + bool __checkGeneralLimits(); + bool __checkActiveLimits(); + bool __checkActiveRequestLimits(); /* INTERNAL : FLAGS */ - bool active_request_succeeded; - bool active_location_succeeded; + bool __activeRequestSucceeded; + bool __activeLocationSucceeded; /* TIMER */ - int timer_id; - time_t timer_timestamp; + int __timerId; + time_t __timerTimestamp; TimerManager __timerManager; - timer_purpose_e timer_purpose; - void set_next_timer(); - void active_request_timer_start(); - void start_service_timer_start(); - void active_interval_timer_start(); - void passive_interval_timer_start(); - void timer_start(time_t minutes); - void timer_stop(); + TimerPurpose __timerPurpose; + void __setNextTimer(); + void __activeRequestTimerStart(); + void __startServiceTimerStart(); + void __activeIntervalTimerStart(); + void __passiveIntervalTimerStart(); + void __timerStart(time_t minutes); + void __timerStop(); bool onTimerExpired(int timerId); /* DATABASE */ - static int create_table(); - int db_insert_log(location_event_s location_event); + static int __dbCreateTable(); + int __dbInsertLog(LocationEvent location_event); /* DEBUG */ - static const char* location_error_str(int error); - static void log(location_accessibility_state_e state); + static const char* __locationError2Str(int error); + static void __log(location_accessibility_state_e state); /* LOCATION MANAGER */ - location_manager_h manager; - void manager_create(); - void manager_destroy(); - void manager_start(); - void manager_stop(); - location_accessibility_state_e manager_get_accessibility_state(); + location_manager_h __locationManager; + void __locationManagerCreate(); + void __locationManagerDestroy(); + void __locationManagerStart(); + void __locationManagerStop(); + location_accessibility_state_e __locationManagerGetAccessibilityState(); /* LOCATION MANAGER : LOCATION SERVICE STATE */ - location_service_state_e location_service_state; - static void location_service_state_changed_cb(location_service_state_e state, void *user_data); - void manager_set_service_state_changed_cb(); - void manager_unset_service_state_changed_cb(); + location_service_state_e __locationServiceState; + static void __locationServiceStateChangedCb(location_service_state_e state, void *user_data); + void __locationManagerSetServiceStateChangedCb(); + void __locationManagerUnsetServiceStateChangedCb(); /* LOCATION MANAGER : LOCATION METHOD SETTINGS */ - location_method_e location_method; - bool location_method_state; - bool manager_is_enabled_method(location_method_e method); - static void location_setting_changed_cb(location_method_e method, bool enable, void *user_data); - void manager_set_setting_changed_cb(); - void manager_unset_setting_changed_cb(); + location_method_e __locationMethod; + bool __locationMethodState; + bool __locationManagerIsEnabledMethod(location_method_e method); + static void __locationSettingChangedCb(location_method_e method, bool enable, void *user_data); + void __locationManagerSetSettingChangedCb(); + void __locationManagerUnsetSettingChangedCb(); /* LOCATION MANAGER : LOCATION */ + double __locationManagerGetHorizontalAccuracy(); /* LOCATION MANAGER : LOCATION : SYNCHRONOUS */ - bool manager_get_location(); - void manager_get_last_location(); - double manager_get_horizontal_accuracy(); + bool __locationManagerGetLocation(); + void __locationManagerGetLastLocation(); /* LOCATION MANAGER : LOCATION : ASYNCHRONOUS */ - static void position_updated_cb(double latitude, double longitude, + static void __positionUpdatedCb(double latitude, double longitude, double altitude, time_t timestamp, void *user_data); - static void location_updated_cb(location_error_e error, double latitude, + static void __locationUpdatedCb(location_error_e error, double latitude, double longitude, double altitude, time_t timestamp, double speed, double direction, double climb, void *user_data); - bool manager_request_single_location(); + bool __locationManagerRequestSingleLocation(); }; /* class LocationLogger */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_LOCATION_LOGGER_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_LOCATION_LOGGER_H_ */ diff --git a/src/place/recognition/user_places/mahal.cpp b/src/place/recognition/user_places/mahal.cpp index 3e283d1..f1bdae8 100644 --- a/src/place/recognition/user_places/mahal.cpp +++ b/src/place/recognition/user_places/mahal.cpp @@ -42,5 +42,5 @@ ctx::num_t ctx::MahalModel::dist_s(const std::vector &v1, const std::vect ctx::num_t ctx::MahalModel::dist(const std::vector &v) { - return dist_s(v, mean, sigma); + return dist_s(v, __mean, __sigma); } diff --git a/src/place/recognition/user_places/mahal.h b/src/place/recognition/user_places/mahal.h index b70ac70..34093f2 100644 --- a/src/place/recognition/user_places/mahal.h +++ b/src/place/recognition/user_places/mahal.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_MAHAL_H__ -#define __CONTEXT_PLACE_STATUS_MAHAL_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_MAHAL_H_ +#define _CONTEXT_PLACE_RECOGNITION_MAHAL_H_ #include #include "user_places_types.h" @@ -28,16 +28,18 @@ namespace ctx { class MahalModel { private: - std::vector mean; - std::vector sigma; // represents square matrix row-wise + std::vector __mean; + std::vector __sigma; // represents square matrix row-wise public: static num_t dist_s(const std::vector &v1, const std::vector &v2, const std::vector &m); - MahalModel(std::vector mean_, std::vector sigma_) : mean(mean_), sigma(sigma_) { } + MahalModel(std::vector mean, std::vector sigma) : + __mean(mean), + __sigma(sigma) { } num_t dist(const std::vector &v); }; /* class MahalModel */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_MAHAL_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_MAHAL_H_ */ diff --git a/src/place/recognition/user_places/median.h b/src/place/recognition/user_places/median.h index c6612dc..70461ae 100644 --- a/src/place/recognition/user_places/median.h +++ b/src/place/recognition/user_places/median.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_MEDIAN__ -#define __CONTEXT_PLACE_STATUS_MEDIAN__ +#ifndef _CONTEXT_PLACE_RECOGNITION_MEDIAN_ +#define _CONTEXT_PLACE_RECOGNITION_MEDIAN_ #include "user_places_types.h" #include @@ -27,4 +27,4 @@ namespace ctx { } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_MEDIAN__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_MEDIAN_ */ diff --git a/src/place/recognition/user_places/piecewise_lin.cpp b/src/place/recognition/user_places/piecewise_lin.cpp index e1cbd46..2222c16 100644 --- a/src/place/recognition/user_places/piecewise_lin.cpp +++ b/src/place/recognition/user_places/piecewise_lin.cpp @@ -17,33 +17,32 @@ #include "piecewise_lin.h" #include -ctx::PiecewiseLin::PiecewiseLin(std::vector _xs, std::vector _vs) - : n(0) +ctx::PiecewiseLin::PiecewiseLin(std::vector xs, std::vector vs) : + __xs(xs), + __vs(vs), + __n(xs.size()) { - if (_xs.size() != _vs.size()) { + if (xs.size() != vs.size()) { _E("Input arguments have different sizes"); return; } - xs = _xs; - vs = _vs; - n = xs.size(); } -ctx::num_t ctx::PiecewiseLin::val(num_t x) +ctx::num_t ctx::PiecewiseLin::value(num_t x) { - if (x <= xs[0]) { - return vs[0]; - } else if (x >= xs[n-1]) { - return vs[n - 1]; + if (x <= __xs[0]) { + return __vs[0]; + } else if (x >= __xs[__n-1]) { + return __vs[__n - 1]; } else { - num_t xp = xs[0]; - for (size_t i = 1; i < n; i++) { - num_t xn = xs[i]; + num_t xp = __xs[0]; + for (size_t i = 1; i < __n; i++) { + num_t xn = __xs[i]; if (x <= xn) { num_t d = xn - xp; num_t dxp = x - xp; num_t dxn = xn - x; - return (dxn * vs[i-1] + dxp * vs[i]) / d; + return (dxn * __vs[i-1] + dxp * __vs[i]) / d; } xp = xn; } diff --git a/src/place/recognition/user_places/piecewise_lin.h b/src/place/recognition/user_places/piecewise_lin.h index 275449c..0ef4bff 100644 --- a/src/place/recognition/user_places/piecewise_lin.h +++ b/src/place/recognition/user_places/piecewise_lin.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_PIECEWISE_LIN__ -#define __CONTEXT_PLACE_STATUS_PIECEWISE_LIN__ +#ifndef _CONTEXT_PLACE_RECOGNITION_PIECEWISE_LIN_ +#define _CONTEXT_PLACE_RECOGNITION_PIECEWISE_LIN_ #include "user_places_types.h" @@ -27,16 +27,16 @@ namespace ctx { class PiecewiseLin { private: - std::vector xs; // nodes - std::vector vs; // values in nodes - size_t n; + std::vector __xs; // nodes + std::vector __vs; // values in nodes + size_t __n; public: - PiecewiseLin(std::vector _xs, std::vector _vs); - num_t val(num_t x); + PiecewiseLin(std::vector xs, std::vector vs); + num_t value(num_t x); }; /* PiecewiseLin */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_PIECEWISE_LIN__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_PIECEWISE_LIN_ */ diff --git a/src/place/recognition/user_places/place_categer.cpp b/src/place/recognition/user_places/place_categer.cpp index b1656e3..685f138 100644 --- a/src/place/recognition/user_places/place_categer.cpp +++ b/src/place/recognition/user_places/place_categer.cpp @@ -22,13 +22,13 @@ #include #include -void ctx::PlaceCateger::reduce_outliers(ctx::visits_t &visits) +void ctx::PlaceCateger::reduceOutliers(ctx::visits_t &visits) { int size = visits.size(); visits.erase(std::remove_if( visits.begin(), visits.end(), - [](visit_s v) { + [](Visit v) { return v.categs[PLACE_CATEG_ID_HOME] < PLACES_CATEGER_MIN_VISITS_SCORE && v.categs[PLACE_CATEG_ID_WORK] < PLACES_CATEGER_MIN_VISITS_SCORE && v.categs[PLACE_CATEG_ID_OTHER] < PLACES_CATEGER_MIN_VISITS_SCORE; @@ -43,7 +43,7 @@ void ctx::PlaceCateger::reduce_outliers(ctx::visits_t &visits) /* * Change category if home or work has to few visits */ -bool ctx::PlaceCateger::reduce_category(const place_categ_id_e &categ, const ctx::visits_t &visits) +bool ctx::PlaceCateger::__reduceCategory(const PlaceCategId &categ, const ctx::visits_t &visits) { return (categ == PLACE_CATEG_ID_HOME && visits.size() < PLACES_CATEGER_MIN_VISITS_PER_HOME) || (categ == PLACE_CATEG_ID_WORK && visits.size() < PLACES_CATEGER_MIN_VISITS_PER_WORK); @@ -51,21 +51,21 @@ bool ctx::PlaceCateger::reduce_category(const place_categ_id_e &categ, const ctx void ctx::PlaceCateger::categorize(ctx::visits_t &visits, ctx::Place &place) { - reduce_outliers(visits); + reduceOutliers(visits); place.categ_id = PLACE_CATEG_ID_NONE; place.categ_confidence = 0.0; if (!visits.empty()) { - const std::vector categ_ids = { + const std::vector categ_ids = { PLACE_CATEG_ID_HOME, PLACE_CATEG_ID_WORK, PLACE_CATEG_ID_OTHER }; num_t sum_score = 0.0; num_t max_score = 0.0; - for (place_categ_id_e categ_id : categ_ids) { - std::vector categ_vector = categ_vector_from_visits(visits, categ_id); + for (PlaceCategId categ_id : categ_ids) { + std::vector categ_vector = categVectorFromVisits(visits, categ_id); num_t score = median(categ_vector); sum_score += score; if (score > max_score) { @@ -76,16 +76,16 @@ void ctx::PlaceCateger::categorize(ctx::visits_t &visits, ctx::Place &place) if (sum_score > 0) { place.categ_confidence = max_score / sum_score; } - if (reduce_category(place.categ_id, visits)) { + if (__reduceCategory(place.categ_id, visits)) { place.categ_id = PLACE_CATEG_ID_OTHER; place.categ_confidence = 0.0; } } - place.name = categ_id_to_name(place.categ_id); + place.name = categId2Name(place.categ_id); } -std::vector ctx::PlaceCateger::categ_vector_from_visits(const ctx::visits_t &visits, place_categ_id_e categ_id) +std::vector ctx::PlaceCateger::categVectorFromVisits(const ctx::visits_t &visits, PlaceCategId categ_id) { std::vector vec; for (auto &visit : visits) { @@ -97,7 +97,7 @@ std::vector ctx::PlaceCateger::categ_vector_from_visits(const ctx::v return vec; } -std::string ctx::PlaceCateger::categ_id_to_name(place_categ_id_e categ_id) { +std::string ctx::PlaceCateger::categId2Name(PlaceCategId categ_id) { switch (categ_id) { case PLACE_CATEG_ID_HOME: return "home"; case PLACE_CATEG_ID_WORK: return "work"; diff --git a/src/place/recognition/user_places/place_categer.h b/src/place/recognition/user_places/place_categer.h index cbab192..05612f3 100644 --- a/src/place/recognition/user_places/place_categer.h +++ b/src/place/recognition/user_places/place_categer.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_PLACE_CATEGER__ -#define __CONTEXT_PLACE_STATUS_PLACE_CATEGER__ +#ifndef _CONTEXT_PLACE_RECOGNITION_PLACE_CATEGER_ +#define _CONTEXT_PLACE_RECOGNITION_PLACE_CATEGER_ #include "user_places_types.h" #include @@ -28,16 +28,16 @@ namespace ctx { class PlaceCateger { private: - static bool reduce_category(const place_categ_id_e &categ, const ctx::visits_t &visits); + static bool __reduceCategory(const PlaceCategId &categ, const ctx::visits_t &visits); public: - static void reduce_outliers(visits_t &visits); - static std::vector categ_vector_from_visits(const ctx::visits_t &visits, place_categ_id_e categ_id); + static void reduceOutliers(visits_t &visits); // TODO: move to private + static std::vector categVectorFromVisits(const ctx::visits_t &visits, PlaceCategId categ_id); // TODO: move to private static void categorize(ctx::visits_t &visits, ctx::Place &place); - static std::string categ_id_to_name(place_categ_id_e categ_id); + static std::string categId2Name(PlaceCategId categ_id); // TODO: move to private }; /* class PlaceCateger */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_PLACE_CATEGER__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_PLACE_CATEGER_ */ diff --git a/src/place/recognition/user_places/places_detector.cpp b/src/place/recognition/user_places/places_detector.cpp index 98cb399..40faf67 100644 --- a/src/place/recognition/user_places/places_detector.cpp +++ b/src/place/recognition/user_places/places_detector.cpp @@ -18,7 +18,7 @@ #include #include #include -#include "similar.h" +#include "similarity.h" #include "places_detector.h" #include "place_categer.h" #include "graph.h" @@ -73,15 +73,15 @@ bool ctx::PlacesDetector::onTimerExpired(int timerId) { _D(""); - db_delete_places(); - db_delete_old_visits(); - std::vector records = db_get_visits(); - visits_t visits = visits_from_jsons(records); - process_visits(visits); + __dbDeletePlaces(); + __dbDeleteOldVisits(); + std::vector records = __dbGetVisits(); + visits_t visits = __visitsFromJsons(records); + __processVisits(visits); return true; } -std::vector ctx::PlacesDetector::db_get_visits() +std::vector ctx::PlacesDetector::__dbGetVisits() { std::vector records; bool ret = db_manager::execute_sync(GET_VISITS_QUERY, &records); @@ -89,7 +89,7 @@ std::vector ctx::PlacesDetector::db_get_visits() return records; } -std::vector ctx::PlacesDetector::db_get_places() +std::vector ctx::PlacesDetector::__dbGetPlaces() { std::vector records; bool ret = db_manager::execute_sync(GET_PLACES_QUERY, &records); @@ -97,24 +97,24 @@ std::vector ctx::PlacesDetector::db_get_places() return records; } -double ctx::PlacesDetector::double_value_from_json(Json &row, const char* key) +double ctx::PlacesDetector::__doubleValueFromJson(Json &row, const char* key) { double value; row.get(NULL, key, &value); - _D("double_value_from_json, key:%s, value: %lf", key, value); + _D("__doubleValueFromJson, key:%s, value: %lf", key, value); return value; } -ctx::categs_t ctx::PlacesDetector::visit_categs_from_json(Json &row) +ctx::categs_t ctx::PlacesDetector::__visitCategsFromJson(Json &row) { categs_t categs; - categs[PLACE_CATEG_ID_HOME] = double_value_from_json(row, VISIT_COLUMN_CATEG_HOME); - categs[PLACE_CATEG_ID_WORK] = double_value_from_json(row, VISIT_COLUMN_CATEG_WORK); - categs[PLACE_CATEG_ID_OTHER] = double_value_from_json(row, VISIT_COLUMN_CATEG_OTHER); + categs[PLACE_CATEG_ID_HOME] = __doubleValueFromJson(row, VISIT_COLUMN_CATEG_HOME); + categs[PLACE_CATEG_ID_WORK] = __doubleValueFromJson(row, VISIT_COLUMN_CATEG_WORK); + categs[PLACE_CATEG_ID_OTHER] = __doubleValueFromJson(row, VISIT_COLUMN_CATEG_OTHER); return categs; } -ctx::visit_s ctx::PlacesDetector::visit_from_json(Json &row) +ctx::Visit ctx::PlacesDetector::__visitFromJson(Json &row) { int start_time; int end_time; @@ -125,13 +125,13 @@ ctx::visit_s ctx::PlacesDetector::visit_from_json(Json &row) std::stringstream mac_set_ss; mac_set_ss << mac_set_string; - std::shared_ptr mac_set = std::make_shared(); - mac_set_ss >> *mac_set; + std::shared_ptr macSet = std::make_shared(); + mac_set_ss >> *macSet; - interval_s interval(start_time, end_time); - categs_t categs = visit_categs_from_json(row); + Interval interval(start_time, end_time); + categs_t categs = __visitCategsFromJson(row); - visit_s visit(interval, mac_set, categs); + Visit visit(interval, macSet, categs); { // location int location_valid_int; @@ -144,27 +144,27 @@ ctx::visit_s ctx::PlacesDetector::visit_from_json(Json &row) return visit; } -ctx::visits_t ctx::PlacesDetector::visits_from_jsons(std::vector& records) +ctx::visits_t ctx::PlacesDetector::__visitsFromJsons(std::vector& records) { visits_t visits; _D("db_result: number of all visits: %d", records.size()); for (Json &row : records) { - visit_s visit = visit_from_json(row); + Visit visit = __visitFromJson(row); visits.push_back(visit); } _D("number of all visits in vector: %d", visits.size()); return visits; } -std::shared_ptr ctx::PlacesDetector::place_from_json(Json &row) +std::shared_ptr ctx::PlacesDetector::__placeFromJson(Json &row) { std::shared_ptr place = std::make_shared(); { // category int categ_id; row.get(NULL, PLACE_COLUMN_CATEG_ID, &categ_id); // This is due to the fact the JSON module API interface doesn't handle enum - place->categ_id = static_cast(categ_id); + place->categ_id = static_cast(categ_id); } row.get(NULL, PLACE_COLUMN_NAME, &(place->name)); row.get(NULL, PLACE_COLUMN_WIFI_APS, &(place->wifi_aps)); @@ -185,26 +185,26 @@ std::shared_ptr ctx::PlacesDetector::place_from_json(Json &row) return place; } -std::vector> ctx::PlacesDetector::places_from_jsons(std::vector& records) +std::vector> ctx::PlacesDetector::__placesFromJsons(std::vector& records) { std::vector> places; _D("db_result: number of all places: %d", records.size()); for (Json &row : records) { - std::shared_ptr place = place_from_json(row); + std::shared_ptr place = __placeFromJson(row); places.push_back(place); } _D("number of all places in vector: %d", places.size()); return places; } -void ctx::PlacesDetector::reduce_outliers(ctx::visits_t &visits) +void ctx::PlacesDetector::reduceOutliers(ctx::visits_t &visits) { int size = visits.size(); visits.erase(std::remove_if( visits.begin(), visits.end(), - [](visit_s v) { + [](Visit v) { int minutes = (v.interval.end - v.interval.start) / 60; return (minutes < PLACES_DETECTOR_MIN_VISIT_DURATION_MINUTES) || (minutes > PLACES_DETECTOR_MAX_VISIT_DURATION_MINUTES); @@ -216,39 +216,39 @@ void ctx::PlacesDetector::reduce_outliers(ctx::visits_t &visits) } } -void ctx::PlacesDetector::process_visits(ctx::visits_t &visits) +void ctx::PlacesDetector::__processVisits(ctx::visits_t &visits) { - reduce_outliers(visits); + reduceOutliers(visits); - _D("test_mode = %d", test_mode); - auto components = merge_visits(visits); - std::vector> new_detected_places; + _D("__testMode = %d", __testMode); + auto components = __mergeVisits(visits); + std::vector> newDetectedPlaces; #ifdef TIZEN_ENGINEER_MODE std::vector places_visits; // TODO: remove from final solution. #endif /* TIZEN_ENGINEER_MODE */ - for (std::shared_ptr component : *components) { + for (std::shared_ptr component : *components) { // Small places outliers reduction - if (!test_mode && 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 (node_t i : *component) { + for (graph::Node i : *component) { merged->push_back(visits[i]); } - std::shared_ptr place = place_from_merged(*merged); + std::shared_ptr place = __placeFromMergedVisits(*merged); if (place->categ_id == PLACE_CATEG_ID_NONE) { continue; } - new_detected_places.push_back(place); - if (!test_mode) { - db_insert_place(*place); + newDetectedPlaces.push_back(place); + if (!__testMode) { + __dbInsertPlace(*place); } #ifdef TIZEN_ENGINEER_MODE { // TODO: Only for debug -> remove in final solution visits_t place_visits; - for (node_t i : *component) { + for (graph::Node i : *component) { place_visits.push_back(visits[i]); } places_visits.push_back(place_visits); @@ -256,20 +256,20 @@ void ctx::PlacesDetector::process_visits(ctx::visits_t &visits) #endif /* TIZEN_ENGINEER_MODE */ } - detected_places_update(new_detected_places); + __detectedPlacesUpdate(newDetectedPlaces); #ifdef TIZEN_ENGINEER_MODE { // Print to file TODO: Only for debug -> remove in final solution std::ofstream out(USER_PLACES_FILE); - for (size_t i = 0; i < new_detected_places.size(); i++) { - new_detected_places[i]->print_to_stream(out); + for (size_t i = 0; i < newDetectedPlaces.size(); i++) { + newDetectedPlaces[i]->print_to_stream(out); visits_t place_visits = places_visits[i]; - for (visit_s visit : place_visits) { + for (Visit visit : place_visits) { visit.print_short_to_stream(out); } } out.close(); - Gmap::write_map(detected_places); + Gmap::writeMap(newDetectedPlaces); } #endif /* TIZEN_ENGINEER_MODE */ } @@ -277,19 +277,19 @@ void ctx::PlacesDetector::process_visits(ctx::visits_t &visits) /* * Replace old places by new ones. */ -void ctx::PlacesDetector::detected_places_update(std::vector> &new_places) +void ctx::PlacesDetector::__detectedPlacesUpdate(std::vector> &new_places) { _D(""); // XXX: In case of thread safety issues use std::mutex to protect places list. - detected_places = new_places; + __detectedPlaces = new_places; } -void ctx::PlacesDetector::merge_location(const visits_t &visits, Place &place) +void ctx::PlacesDetector::__mergeLocation(const visits_t &visits, Place &place) { place.location_valid = false; std::vector latitudes; std::vector longitudes; - for (const visit_s& visit : visits) { + for (const Visit& visit : visits) { if (visit.location_valid) { latitudes.push_back(visit.location.latitude); longitudes.push_back(visit.location.longitude); @@ -302,32 +302,32 @@ void ctx::PlacesDetector::merge_location(const visits_t &visits, Place &place) } } -std::shared_ptr ctx::PlacesDetector::place_from_merged(visits_t &merged_visits) +std::shared_ptr ctx::PlacesDetector::__placeFromMergedVisits(visits_t &merged_visits) { std::shared_ptr place = std::make_shared(); place->create_date = std::time(nullptr); - std::vector> mac_sets; - for (const visit_s &visit : merged_visits) { - mac_sets.push_back(visit.mac_set); + std::vector> macSets; + for (const Visit &visit : merged_visits) { + macSets.push_back(visit.macSet); } - std::shared_ptr all_macs = mac_sets_union(mac_sets); + std::shared_ptr all_macs = mac_sets_union(macSets); std::stringstream all_macs_ss; all_macs_ss << *all_macs; place->wifi_aps = all_macs_ss.str(); - merge_location(merged_visits, *place); + __mergeLocation(merged_visits, *place); PlaceCateger::categorize(merged_visits, *place); return place; } -void ctx::PlacesDetector::reduce_outliers(std::shared_ptr &cc) +void ctx::PlacesDetector::reduceOutliers(std::shared_ptr &cc) { int size = cc->size(); cc->erase(std::remove_if(cc->begin(), cc->end(), - [](std::shared_ptr &c) { + [](std::shared_ptr &c) { return c->size() < PLACES_DETECTOR_MIN_VISITS_PER_PLACE; }), cc->end()); @@ -337,22 +337,22 @@ void ctx::PlacesDetector::reduce_outliers(std::shared_ptr &cc } } -std::shared_ptr ctx::PlacesDetector::merge_visits(const std::vector &visits) +std::shared_ptr ctx::PlacesDetector::__mergeVisits(const std::vector &visits) { - auto graph = graph_from_visits(visits); - auto cc = connected_components(*graph); - reduce_outliers(cc); + auto graph = __graphFromVisits(visits); + auto cc = graph::connectedComponents(*graph); + reduceOutliers(cc); return cc; } -std::shared_ptr ctx::PlacesDetector::graph_from_visits(const std::vector &visits) +std::shared_ptr ctx::PlacesDetector::__graphFromVisits(const std::vector &visits) { - std::shared_ptr graph = std::make_shared(); + std::shared_ptr graph = std::make_shared(); graph->resize(visits.size()); for (size_t i = 0; i < visits.size(); i++) { - (*graph)[i] = std::make_shared(); + (*graph)[i] = std::make_shared(); for (size_t j = 0; j < i; j++) { - if (is_joint(*visits[i].mac_set, *visits[j].mac_set)) { + if (similarity::isJoint(*visits[i].macSet, *visits[j].macSet)) { (*graph)[i]->insert(j); (*graph)[j]->insert(i); } @@ -361,22 +361,22 @@ std::shared_ptr ctx::PlacesDetector::graph_from_visits(const std:: return graph; } -void ctx::PlacesDetector::db_delete_places() +void ctx::PlacesDetector::__dbDeletePlaces() { std::vector records; bool ret = db_manager::execute_sync(DELETE_PLACES_QUERY, &records); _D("delete places execute query result: %s", ret ? "SUCCESS" : "FAIL"); } -void ctx::PlacesDetector::db_delete_old_visits() +void ctx::PlacesDetector::__dbDeleteOldVisits() { time_t current_time; time(¤t_time); time_t threshold_time = current_time - PLACES_DETECTOR_RETENTION_SECONDS; - db_delete_older_visits(threshold_time); + __dbDeleteOlderVisitsThan(threshold_time); } -void ctx::PlacesDetector::db_delete_older_visits(time_t threshold) +void ctx::PlacesDetector::__dbDeleteOlderVisitsThan(time_t threshold) { _D("deleting vistits older than: %d", threshold); std::stringstream query; @@ -388,25 +388,25 @@ void ctx::PlacesDetector::db_delete_older_visits(time_t threshold) _D("delete old visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); } -ctx::PlacesDetector::PlacesDetector(bool test_mode_) - : test_mode(test_mode_) +ctx::PlacesDetector::PlacesDetector(bool testMode) : + __testMode(testMode) { - if (test_mode) { + if (testMode) { return; } - db_create_table(); - std::vector records = db_get_places(); - std::vector> db_places = places_from_jsons(records); - detected_places_update(db_places); + __dbCreateTable(); + std::vector records = __dbGetPlaces(); + std::vector> db_places = __placesFromJsons(records); + __detectedPlacesUpdate(db_places); } -void ctx::PlacesDetector::db_create_table() +void ctx::PlacesDetector::__dbCreateTable() { bool ret = db_manager::create_table(0, PLACE_TABLE, PLACE_TABLE_COLUMNS); _D("db: place Table Creation Result: %s", ret ? "SUCCESS" : "FAIL"); } -void ctx::PlacesDetector::db_insert_place(const Place &place) +void ctx::PlacesDetector::__dbInsertPlace(const Place &place) { Json data; data.set(NULL, PLACE_COLUMN_CATEG_ID, place.categ_id); @@ -425,8 +425,8 @@ void ctx::PlacesDetector::db_insert_place(const Place &place) _D("insert place execute query result: %s", ret ? "SUCCESS" : "FAIL"); } -std::vector> ctx::PlacesDetector::get_places() +std::vector> ctx::PlacesDetector::getPlaces() { // XXX: In case of thread safety issues use std::mutex to protect places list. - return detected_places; + return __detectedPlaces; } diff --git a/src/place/recognition/user_places/places_detector.h b/src/place/recognition/user_places/places_detector.h index e0461d9..7ad43fb 100644 --- a/src/place/recognition/user_places/places_detector.h +++ b/src/place/recognition/user_places/places_detector.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_PLACES_DETECTOR__ -#define __CONTEXT_PLACE_STATUS_PLACES_DETECTOR__ +#ifndef _CONTEXT_PLACE_RECOGNITION_PLACES_DETECTOR_ +#define _CONTEXT_PLACE_RECOGNITION_PLACES_DETECTOR_ #include "visit_detector.h" #include @@ -29,37 +29,42 @@ namespace ctx { class PlacesDetector : public ITimerListener { private: - bool test_mode; - double double_value_from_json(Json &row, const char* key); - categs_t visit_categs_from_json(Json &row); - visit_s visit_from_json(Json &row); - visits_t visits_from_jsons(std::vector& records); - std::shared_ptr place_from_json(Json &row); - std::vector> places_from_jsons(std::vector& records); - std::shared_ptr graph_from_visits(const std::vector &visits); - void db_create_table(); - void db_delete_places(); - void db_delete_old_visits(); - void db_delete_older_visits(time_t threshold); - std::vector db_get_visits(); - std::vector db_get_places(); - void db_insert_place(const Place &place); - std::shared_ptr place_from_merged(visits_t &merged_visits); - std::vector> detected_places; - void detected_places_update(std::vector> &new_places); + bool __testMode; + + double __doubleValueFromJson(Json &row, const char* key); + categs_t __visitCategsFromJson(Json &row); + Visit __visitFromJson(Json &row); + visits_t __visitsFromJsons(std::vector& records); + std::shared_ptr __placeFromJson(Json &row); + std::vector> __placesFromJsons(std::vector& records); + + std::shared_ptr __graphFromVisits(const std::vector &visits); + + void __dbCreateTable(); + void __dbDeletePlaces(); + void __dbDeleteOldVisits(); + void __dbDeleteOlderVisitsThan(time_t threshold); + std::vector __dbGetVisits(); + std::vector __dbGetPlaces(); + void __dbInsertPlace(const Place &place); + + std::shared_ptr __placeFromMergedVisits(visits_t &merged_visits); + std::vector> __detectedPlaces; + void __detectedPlacesUpdate(std::vector> &new_places); + void __processVisits(visits_t &visits); + static void __mergeLocation(const visits_t &merged_visits, Place &place); + std::shared_ptr __mergeVisits(const std::vector &visits); - public: - static void reduce_outliers(visits_t &visits); - static void reduce_outliers(std::shared_ptr &cc); - void process_visits(visits_t &visits); - static void merge_location(const visits_t &merged_visits, Place &place); - PlacesDetector(bool test_mode_ = false); bool onTimerExpired(int timerId); - std::shared_ptr merge_visits(const std::vector &visits); - std::vector> get_places(); + + public: + PlacesDetector(bool testMode = false); + static void reduceOutliers(visits_t &visits); // TODO: move to private + static void reduceOutliers(std::shared_ptr &cc); // TODO: move to private + std::vector> getPlaces(); }; /* class PlacesDetector */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_PLACES_DETECTOR__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_PLACES_DETECTOR_ */ diff --git a/src/place/recognition/user_places/prob_features_model.h b/src/place/recognition/user_places/prob_features_model.h index e4e87f0..d30f548 100644 --- a/src/place/recognition/user_places/prob_features_model.h +++ b/src/place/recognition/user_places/prob_features_model.h @@ -14,20 +14,22 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_PROB_FEATURES_MODEL_H__ -#define __CONTEXT_PLACE_PROB_FEATURES_MODEL_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_FEATURES_MODEL_H_ +#define _CONTEXT_PLACE_RECOGNITION_FEATURES_MODEL_H_ namespace ctx { +namespace prob_features { + /* * Probabilities for whole week with minutes resolution * from beginning of the week (sunday -> monday midnight) <0, 10080). - * Key is place_categ_id_e: + * Key is PlaceCategId: * PLACE_CATEG_ID_HOME * PLACE_CATEG_ID_WORK * PLACE_CATEG_ID_OTHER */ - std::map> week_model { + std::map> weekModel { { PLACE_CATEG_ID_HOME, { 0.9824561403508770, @@ -30282,6 +30284,8 @@ namespace ctx { } }; +} /* namespace prob_features */ + } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_PROB_FEATURES_MODEL_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_FEATURES_MODEL_H_ */ diff --git a/src/place/recognition/user_places/similar.h b/src/place/recognition/user_places/similarity.h similarity index 66% rename from src/place/recognition/user_places/similar.h rename to src/place/recognition/user_places/similarity.h index 1495de8..5938ef5 100644 --- a/src/place/recognition/user_places/similar.h +++ b/src/place/recognition/user_places/similarity.h @@ -14,16 +14,16 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_SIMILAR_H__ -#define __CONTEXT_PLACE_STATUS_SIMILAR_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_SIMILAR_H_ +#define _CONTEXT_PLACE_RECOGNITION_SIMILAR_H_ #include "user_places_types.h" namespace ctx { - /* similarity functions */ +namespace similarity { - template ctx::share_t overlap_first_over_second(const T &s1, const T &s2) + template ctx::share_t overlap1stOver2nd(const T &s1, const T &s2) { if (s2.empty()) { return 0; @@ -37,16 +37,16 @@ namespace ctx { return (ctx::share_t) count / s2.size(); } - template ctx::share_t overlap_bigger_over_smaller(const T &s1, const T &s2) + template ctx::share_t overlapBiggerOverSmaller(const T &s1, const T &s2) { if (s1.size() > s2.size()) { - return overlap_first_over_second(s1, s2); + return similarity::overlap1stOver2nd(s1, s2); } else { - return overlap_first_over_second(s2, s1); + return similarity::overlap1stOver2nd(s2, s1); } } - template bool is_joint(const T &s1, const T &s2) + template bool isJoint(const T &s1, const T &s2) { for (auto e : s2) { if (s1.find(e) != s1.end()) { @@ -56,6 +56,8 @@ namespace ctx { return false; } +} /* namespace similarity */ + } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_SIMILAR_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_SIMILAR_H_ */ diff --git a/src/place/recognition/user_places/user_places.cpp b/src/place/recognition/user_places/user_places.cpp index c0bb736..c61cb2a 100644 --- a/src/place/recognition/user_places/user_places.cpp +++ b/src/place/recognition/user_places/user_places.cpp @@ -22,30 +22,30 @@ #include "../place_recognition_types.h" #include "db_mgr.h" -ctx::UserPlaces::UserPlaces(place_recog_mode_e energy_mode) - : visit_detector(nullptr) - , places_detector(nullptr) - , places_detector_timer_id(-1) +ctx::UserPlaces::UserPlaces(place_recog_mode_e energyMode): + __visitDetector(nullptr), + __placesDetector(nullptr), + __placesDetectorTimerId(-1) { time_t now = std::time(nullptr); - visit_detector = new(std::nothrow) VisitDetector(now, energy_mode); - if (visit_detector == nullptr) { - _E("Cannot initialize visit_detector"); + __visitDetector = new(std::nothrow) VisitDetector(now, energyMode); + if (__visitDetector == nullptr) { + _E("Cannot initialize __visitDetector"); return; } - places_detector = new(std::nothrow) PlacesDetector(); - if (places_detector == nullptr) { - _E("Cannot initialize places_detector"); + __placesDetector = new(std::nothrow) PlacesDetector(); + if (__placesDetector == nullptr) { + _E("Cannot initialize __placesDetector"); return; } - places_detector_timer_id = __timerManager.setAt( // execute once every night + __placesDetectorTimerId = __timerManager.setAt( // execute once every night PLACES_DETECTOR_TASK_START_HOUR, PLACES_DETECTOR_TASK_START_MINUTE, DayOfWeek::EVERYDAY, - places_detector); - if (places_detector_timer_id < 0) { + __placesDetector); + if (__placesDetectorTimerId < 0) { _E("PlacesDetector timer set FAIL"); return; } else { @@ -55,24 +55,24 @@ ctx::UserPlaces::UserPlaces(place_recog_mode_e energy_mode) ctx::UserPlaces::~UserPlaces() { - if (places_detector_timer_id >= 0) { - __timerManager.remove(places_detector_timer_id); + if (__placesDetectorTimerId >= 0) { + __timerManager.remove(__placesDetectorTimerId); _D("PlacesDetector timer removed"); } - if (visit_detector) { - delete visit_detector; + if (__visitDetector) { + delete __visitDetector; } - if (places_detector) { - delete places_detector; + if (__placesDetector) { + delete __placesDetector; } }; -std::vector> ctx::UserPlaces::get_places() +std::vector> ctx::UserPlaces::getPlaces() { - if (places_detector) { - return places_detector->get_places(); + if (__placesDetector) { + return __placesDetector->getPlaces(); } else { return std::vector>(); } @@ -110,7 +110,7 @@ std::vector> ctx::UserPlaces::get_places() * ] * } */ -ctx::Json ctx::UserPlaces::compose_json(std::vector> places) +ctx::Json ctx::UserPlaces::composeJson(std::vector> places) { ctx::Json data; for (std::shared_ptr place : places) { @@ -129,9 +129,9 @@ ctx::Json ctx::UserPlaces::compose_json(std::vector> plac return data; } -void ctx::UserPlaces::set_mode(place_recog_mode_e energy_mode) +void ctx::UserPlaces::setMode(place_recog_mode_e energyMode) { - if (visit_detector) { - visit_detector->set_mode(energy_mode); + if (__visitDetector) { + __visitDetector->setMode(energyMode); } } diff --git a/src/place/recognition/user_places/user_places.h b/src/place/recognition/user_places/user_places.h index b7084d8..d4275cb 100644 --- a/src/place/recognition/user_places/user_places.h +++ b/src/place/recognition/user_places/user_places.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_USER_PLACES_ENGINE_H__ -#define __CONTEXT_PLACE_STATUS_USER_PLACES_ENGINE_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_USER_PLACES_H_ +#define _CONTEXT_PLACE_RECOGNITION_USER_PLACES_H_ #include #include @@ -29,22 +29,21 @@ namespace ctx { class UserPlaces { private: - VisitDetector *visit_detector; - PlacesDetector *places_detector; - int places_detector_timer_id; + VisitDetector *__visitDetector; + PlacesDetector *__placesDetector; + int __placesDetectorTimerId; TimerManager __timerManager; public: - UserPlaces(place_recog_mode_e energy_mode = PLACE_RECOG_HIGH_ACCURACY_MODE); + UserPlaces(place_recog_mode_e energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE); ~UserPlaces(); - void set_mode(place_recog_mode_e energy_mode); - std::vector> get_places(); - static Json compose_json(std::vector> places); + void setMode(place_recog_mode_e energyMode); + std::vector> getPlaces(); + static Json composeJson(std::vector> places); }; /* class UserPlaces */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_USER_PLACES_ENGINE_H__ */ - +#endif /* End of _CONTEXT_PLACE_RECOGNITION_USER_PLACES_H_ */ diff --git a/src/place/recognition/user_places/user_places_params.h b/src/place/recognition/user_places/user_places_params.h index fc041c0..ec70a29 100644 --- a/src/place/recognition/user_places/user_places_params.h +++ b/src/place/recognition/user_places/user_places_params.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_USER_PLACES_PARAMS_H__ -#define __CONTEXT_PLACE_STATUS_USER_PLACES_PARAMS_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_USER_PLACES_PARAMS_H_ +#define _CONTEXT_PLACE_RECOGNITION_USER_PLACES_PARAMS_H_ /* * WiFi scanning frequency (in minutes) in PLACE_RECOG_HIGH_ACCURACY_MODE. @@ -108,4 +108,4 @@ */ #define PLACES_CATEGER_MIN_VISITS_PER_WORK 2 -#endif /* __CONTEXT_PLACE_STATUS_USER_PLACES_PARAMS_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_USER_PLACES_PARAMS_H_ */ diff --git a/src/place/recognition/user_places/user_places_types.cpp b/src/place/recognition/user_places/user_places_types.cpp index 81e253c..9fafbc4 100644 --- a/src/place/recognition/user_places/user_places_types.cpp +++ b/src/place/recognition/user_places/user_places_types.cpp @@ -121,7 +121,7 @@ bool ctx::operator<(const Mac &m1, const Mac &m2) return false; // they are equal } -std::istream& ctx::operator>>(std::istream &input, ctx::mac_set_t &mac_set) +std::istream& ctx::operator>>(std::istream &input, ctx::mac_set_t &macSet) { Mac mac; char delimeter; @@ -129,10 +129,10 @@ std::istream& ctx::operator>>(std::istream &input, ctx::mac_set_t &mac_set) try { input >> mac; } catch (std::runtime_error &e) { - _E("Cannot read mac_set. Exception: %s", e.what()); + _E("Cannot read macSet. Exception: %s", e.what()); break; } - mac_set.insert(mac); + macSet.insert(mac); if (input.eof()) { break; } @@ -145,10 +145,10 @@ std::istream& ctx::operator>>(std::istream &input, ctx::mac_set_t &mac_set) return input; } -std::ostream& ctx::operator<<(std::ostream &output, const ctx::mac_set_t &mac_set) +std::ostream& ctx::operator<<(std::ostream &output, const ctx::mac_set_t &macSet) { - std::vector mac_vec(mac_set.size()); - std::copy(mac_set.begin(), mac_set.end(), mac_vec.begin()); + std::vector mac_vec(macSet.size()); + std::copy(macSet.begin(), macSet.end(), mac_vec.begin()); std::sort(mac_vec.begin(), mac_vec.end()); bool first = true; @@ -163,9 +163,9 @@ std::ostream& ctx::operator<<(std::ostream &output, const ctx::mac_set_t &mac_se return output; } -void ctx::location_event_s::log() +void ctx::LocationEvent::log() { - std::string time_str = DebugUtils::human_readable_date_time(timestamp, "%T", 9); + std::string time_str = DebugUtils::humanReadableDateTime(timestamp, "%T", 9); #ifdef TIZEN_ENGINEER_MODE _D("location lat=%.8f, lon=%.8f, acc=%.2f[m], time=%s, method=%d", coordinates.latitude, @@ -182,24 +182,24 @@ void ctx::location_event_s::log() #endif /* TIZEN_ENGINEER_MODE */ } -void ctx::visit_s::set_location(location_s location_) +void ctx::Visit::set_location(Location location_) { location_valid = true; location = location_; } -void ctx::visit_s::print_short_to_stream(std::ostream &out) const +void ctx::Visit::print_short_to_stream(std::ostream &out) const { // print only valid visits if (interval.end != 0) { float duration = ((float) (interval.end - interval.start)) / 3600; // [h] out << "__VISIT " << duration << "h: "; - out << DebugUtils::human_readable_date_time(interval.start, "%m/%d %H:%M", 15) << " ÷ "; - out << DebugUtils::human_readable_date_time(interval.end, "%m/%d %H:%M", 15) << std::endl; + out << DebugUtils::humanReadableDateTime(interval.start, "%m/%d %H:%M", 15) << " ÷ "; + out << DebugUtils::humanReadableDateTime(interval.end, "%m/%d %H:%M", 15) << std::endl; } } -bool ctx::operator==(const ctx::visit_s &v1, const ctx::visit_s &v2) +bool ctx::operator==(const ctx::Visit &v1, const ctx::Visit &v2) { return v1.interval.start == v2.interval.start && v1.interval.end == v2.interval.end @@ -208,16 +208,16 @@ bool ctx::operator==(const ctx::visit_s &v1, const ctx::visit_s &v2) && v1.location.longitude == v2.location.longitude && v1.location.accuracy == v2.location.accuracy && v1.location_valid == v2.location_valid - && v1.mac_set == v2.mac_set; + && v1.macSet == v2.macSet; } ctx::mac_set_t ctx::mac_set_from_string(const std::string &str) { - mac_set_t mac_set; + mac_set_t macSet; std::stringstream ss; ss << str; - ss >> mac_set; - return mac_set; + ss >> macSet; + return macSet; } bool ctx::operator>(const Mac &m1, const Mac &m2) @@ -227,23 +227,23 @@ bool ctx::operator>(const Mac &m1, const Mac &m2) std::shared_ptr ctx::mac_set_from_mac_counts(const mac_counts_t &mac_counts) { - std::shared_ptr mac_set(std::make_shared()); + std::shared_ptr macSet(std::make_shared()); for (auto &c: mac_counts) { - mac_set->insert(c.first); + macSet->insert(c.first); } - return mac_set; + return macSet; } -std::shared_ptr ctx::mac_sets_union(const std::vector> &mac_sets) +std::shared_ptr ctx::mac_sets_union(const std::vector> &macSets) { std::shared_ptr union_set = std::make_shared(); - for (std::shared_ptr mac_set : mac_sets) { - union_set->insert(mac_set->begin(), mac_set->end()); + for (std::shared_ptr macSet : macSets) { + union_set->insert(macSet->begin(), macSet->end()); } return union_set; } -ctx::interval_s::interval_s(time_t start_, time_t end_) : start(start_), end(end_) { +ctx::Interval::Interval(time_t start_, time_t end_) : start(start_), end(end_) { if (end_ < start_) { _E("Negative interval, start=%d, end=%d", start_, end_); } @@ -258,5 +258,5 @@ void ctx::Place::print_to_stream(std::ostream &out) const out << ", lon=" << location.longitude << std::setprecision(5) << std::endl; } out << "__WIFI:" << wifi_aps << std::endl; - out << "__CREATE_DATE: " << DebugUtils::human_readable_date_time(create_date, "%F %T", 80) << std::endl; + out << "__CREATE_DATE: " << DebugUtils::humanReadableDateTime(create_date, "%F %T", 80) << std::endl; } diff --git a/src/place/recognition/user_places/user_places_types.h b/src/place/recognition/user_places/user_places_types.h index 8eed322..a19c015 100644 --- a/src/place/recognition/user_places/user_places_types.h +++ b/src/place/recognition/user_places/user_places_types.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_USER_PLACES_TYPES_H__ -#define __CONTEXT_PLACE_STATUS_USER_PLACES_TYPES_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_USER_PLACES_TYPES_H_ +#define _CONTEXT_PLACE_RECOGNITION_USER_PLACES_TYPES_H_ #include #include @@ -83,25 +83,25 @@ namespace ctx { typedef std::unordered_set mac_set_t; - std::istream &operator>>(std::istream &input, ctx::mac_set_t &mac_set); - std::ostream &operator<<(std::ostream &output, const ctx::mac_set_t &mac_set); + std::istream &operator>>(std::istream &input, ctx::mac_set_t &macSet); + std::ostream &operator<<(std::ostream &output, const ctx::mac_set_t &macSet); ctx::mac_set_t mac_set_from_string(const std::string &str); - std::shared_ptr mac_sets_union(const std::vector> &mac_sets); + std::shared_ptr mac_sets_union(const std::vector> &macSets); - struct interval_s { + struct Interval { time_t start; time_t end; - interval_s(time_t start_, time_t end_); + Interval(time_t start_, time_t end_); }; } /* namespace ctx */ namespace std { - template <> struct hash { - size_t operator()(const ctx::interval_s & interval) const { + template <> struct hash { + size_t operator()(const ctx::Interval & interval) const { return interval.end * interval.start; } }; @@ -113,98 +113,98 @@ namespace ctx { /* * fully describes interval data after the interval is finished */ - struct frame_s { - interval_s interval; - count_t no_timestamps; - mac_counts_t mac_counts; + struct Frame { + Interval interval; + count_t numberOfTimestamps; + mac_counts_t macCountsMap; - frame_s(interval_s interval_) : interval(interval_), no_timestamps(0) {}; + Frame(Interval interval_) : interval(interval_), numberOfTimestamps(0) {}; }; /* * mac address + its timestamp */ - struct mac_event_s { + struct MacEvent { time_t timestamp; Mac mac; - mac_event_s(time_t timestamp_, Mac mac_) : timestamp(timestamp_), mac(mac_) {} + MacEvent(time_t timestamp_, Mac mac_) : timestamp(timestamp_), mac(mac_) {} }; typedef std::map categs_t; // scores of categories - struct location_s { + struct Location { double latitude; double longitude; double accuracy; // [m] - location_s(double latitude_ = 0.0, double longitude_ = 0.0, double accuracy_ = -1.0) + Location(double latitude_ = 0.0, double longitude_ = 0.0, double accuracy_ = -1.0) : latitude(latitude_), longitude(longitude_), accuracy(accuracy_) {} - }; /* struct location_s */ + }; /* struct Location */ #ifdef TIZEN_ENGINEER_MODE - typedef enum { + enum LocationSource { LOCATION_METHOD_REQUEST = 0, LOCATION_METHOD_GET_LOCATION = 1, LOCATION_METHOD_GET_LAST_LOCATION = 2 - } location_source_e; + }; #endif /* TIZEN_ENGINEER_MODE */ /* * location + timestamp + method */ - struct location_event_s { - location_s coordinates; + struct LocationEvent { + Location coordinates; time_t timestamp; #ifdef TIZEN_ENGINEER_MODE - location_source_e method; + LocationSource method; - location_event_s(double latitude_, double longitude_, double accuracy_, time_t timestamp_, location_source_e method_) + LocationEvent(double latitude_, double longitude_, double accuracy_, time_t timestamp_, LocationSource method_) : coordinates(latitude_, longitude_, accuracy_), timestamp(timestamp_), method(method_) {} #else /* TIZEN_ENGINEER_MODE */ - location_event_s(double latitude_, double longitude_, double accuracy_, time_t timestamp_) + LocationEvent(double latitude_, double longitude_, double accuracy_, time_t timestamp_) : coordinates(latitude_, longitude_, accuracy_), timestamp(timestamp_) {} #endif /* TIZEN_ENGINEER_MODE */ void log(); - }; /* struct location_event_s */ + }; /* struct LocationEvent */ - struct visit_s { - interval_s interval; - std::shared_ptr mac_set; + struct Visit { + Interval interval; + std::shared_ptr macSet; categs_t categs; bool location_valid; - location_s location; // makes sense if location_valid == true; + Location location; // makes sense if location_valid == true; - visit_s(interval_s interval_, std::shared_ptr mac_set_ = std::make_shared(), categs_t categs_ = categs_t()) : + Visit(Interval interval_, std::shared_ptr macSet_ = std::make_shared(), categs_t categs_ = categs_t()) : interval(interval_), - mac_set(mac_set_), + macSet(macSet_), categs(categs_), location_valid(false) {} - void set_location(location_s location); + void set_location(Location location); void print_short_to_stream(std::ostream &out) const; - }; /* struct visit_s */ + }; /* struct Visit */ - bool operator==(const visit_s &v1, const visit_s &v2); - typedef std::vector visits_t; - typedef std::vector mac_events; // used to store current interval logs + bool operator==(const Visit &v1, const Visit &v2); + typedef std::vector visits_t; + typedef std::vector mac_events; // used to store current interval logs - std::shared_ptr mac_set_from_mac_counts(const mac_counts_t &mac_counts); + std::shared_ptr mac_set_from_mac_counts(const mac_counts_t &macCountsMap); typedef float confidence_t; class Place { public: - place_categ_id_e categ_id; // category of a place (work/home/other) + PlaceCategId categ_id; // category of a place (work/home/other) confidence_t categ_confidence; // confidence of the above category - between [0,1] std::string name; // for now: "work"/"home"/"other" bool location_valid; - location_s location; // makes sense if location_valid == true; + Location location; // makes sense if location_valid == true; std::string wifi_aps; // WiFi APs MAC addresses separated by "," time_t create_date; // The last update time of this place @@ -214,4 +214,4 @@ namespace ctx { } /* namespace ctx */ -#endif /*__CONTEXT_PLACE_STATUS_USER_PLACES_TYPES_H__*/ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_USER_PLACES_TYPES_H_ */ diff --git a/src/place/recognition/user_places/visit_categer.cpp b/src/place/recognition/user_places/visit_categer.cpp index fb19d10..c09dd01 100644 --- a/src/place/recognition/user_places/visit_categer.cpp +++ b/src/place/recognition/user_places/visit_categer.cpp @@ -22,7 +22,7 @@ #include // categorizer model parameters trained offline (implemented in python): -const std::map ctx::VisitCateger::models({ +const std::map ctx::VisitCateger::__models({ { PLACE_CATEG_ID_HOME, ctx::MahalModel( @@ -72,7 +72,7 @@ const std::map ctx::VisitCateger::models({ }) }}); -ctx::PiecewiseLin ctx::VisitCateger::chi_approx( +ctx::PiecewiseLin ctx::VisitCateger::__chiApprox( { 0. , 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1 , 0.11, 0.12, 0.13, 0.14, 0.15, 0.16, 0.17, @@ -274,7 +274,7 @@ ctx::PiecewiseLin ctx::VisitCateger::chi_approx( } // this is chi cdf for 7 degrees of freedom (because we have 7 features) ); -const std::vector ctx::VisitCateger::features_mean( +const std::vector ctx::VisitCateger::__featuresMean( { 344.542975696503, 894.178423236515, @@ -285,7 +285,7 @@ const std::vector ctx::VisitCateger::features_mean( 0.139583453187 }); -const std::vector ctx::VisitCateger::features_std( +const std::vector ctx::VisitCateger::__featuresStd( { 416.061437196941, 301.401812101781, @@ -296,36 +296,36 @@ const std::vector ctx::VisitCateger::features_std( 0.109386661911 }); -ctx::time_features_s ctx::VisitCateger::time_features(const time_t &time) +ctx::TimeFeatures ctx::VisitCateger::timeFeatures(const time_t &time) { struct tm *timeinfo = localtime(&time); if (timeinfo == NULL) { return {0, 0, 0, false}; } - int minutes_since_midnight = 60 * timeinfo->tm_hour + timeinfo->tm_min; + int minutesSinceMidnight = 60 * timeinfo->tm_hour + timeinfo->tm_min; int weekday = (timeinfo->tm_wday + 6) % 7; // Monday is 0, Sunday is 6 bool weekend = weekday > 4; - int minutes_since_begining_of_the_week = 24 * 60 * weekday + minutes_since_midnight; + int minutesSinceBeginingOfTheWeek = 24 * 60 * weekday + minutesSinceMidnight; return { - minutes_since_midnight, - minutes_since_begining_of_the_week, + minutesSinceMidnight, + minutesSinceBeginingOfTheWeek, weekday, weekend }; } -int ctx::VisitCateger::weeks_scope(const time_features_s &start_f, const interval_s &interval) +int ctx::VisitCateger::weeksScope(const TimeFeatures &start_f, const Interval &interval) { int duration_minutes = (interval.end - interval.start) / 60; - int scope_minutes = start_f.minutes_since_begining_of_the_week + duration_minutes; - int weeks_scope = scope_minutes / MINUTES_IN_WEEK; + int scope_minutes = start_f.minutesSinceBeginingOfTheWeek + duration_minutes; + int weeksScope = scope_minutes / MINUTES_IN_WEEK; if (scope_minutes % MINUTES_IN_WEEK > 0) { - weeks_scope++; + weeksScope++; } - return weeks_scope; + return weeksScope; } -ctx::num_t ctx::VisitCateger::sum(const std::vector model, const size_t &from, const size_t &to) +ctx::num_t ctx::VisitCateger::__sum(const std::vector model, const size_t &from, const size_t &to) { size_t to_secure = to; if (to >= model.size()) { @@ -345,20 +345,20 @@ ctx::num_t ctx::VisitCateger::sum(const std::vector model, const size_t & return result; } -ctx::num_t ctx::VisitCateger::week_model_mean_value(place_categ_id_e categ, const interval_s &interval, - const time_features_s &start_f, const time_features_s &end_f) +ctx::num_t ctx::VisitCateger::__weekModelMeanValue(PlaceCategId categ, const Interval &interval, + const TimeFeatures &start_f, const TimeFeatures &end_f) { num_t ret = 0.0; int minutes = 0; - int ws = weeks_scope(start_f, interval); + int ws = weeksScope(start_f, interval); for (int week = 1; week <= ws; week++) { size_t start_index = (week == 1) - ? start_f.minutes_since_begining_of_the_week + ? start_f.minutesSinceBeginingOfTheWeek : 0; size_t end_index = (week == ws) - ? end_f.minutes_since_begining_of_the_week + ? end_f.minutesSinceBeginingOfTheWeek : MINUTES_IN_WEEK - 1; - ret += sum(week_model[categ], start_index, end_index); + ret += __sum(prob_features::weekModel[categ], start_index, end_index); minutes += end_index - start_index + 1; } if (minutes > 0) { @@ -367,12 +367,12 @@ ctx::num_t ctx::VisitCateger::week_model_mean_value(place_categ_id_e categ, cons return ret; } -ctx::categs_t ctx::VisitCateger::week_model_features(const interval_s &interval, const time_features_s &start_f, - const time_features_s &end_f) +ctx::categs_t ctx::VisitCateger::weekModelFeatures(const Interval &interval, const TimeFeatures &start_f, + const TimeFeatures &end_f) { ctx::categs_t categs; - for (const auto &item : week_model) { - categs[item.first] = week_model_mean_value(item.first, interval, start_f, end_f); + for (const auto &item : prob_features::weekModel) { + categs[item.first] = __weekModelMeanValue(item.first, interval, start_f, end_f); } _D("categs: H=%.12f, W=%.12f, O=%.12f", categs[PLACE_CATEG_ID_HOME], @@ -381,16 +381,16 @@ ctx::categs_t ctx::VisitCateger::week_model_features(const interval_s &interval, return categs; } -std::vector ctx::VisitCateger::interval_features(const interval_s &interval) +std::vector ctx::VisitCateger::intervalFeatures(const Interval &interval) { num_t duration_minutes = 1.0 * (interval.end - interval.start) / 60; - time_features_s start_features = time_features(interval.start); - time_features_s end_features = time_features(interval.end); - categs_t week_features = week_model_features(interval, start_features, end_features); + TimeFeatures start_features = timeFeatures(interval.start); + TimeFeatures end_features = timeFeatures(interval.end); + categs_t week_features = weekModelFeatures(interval, start_features, end_features); return { duration_minutes, - (num_t) start_features.minutes_since_midnight, - (num_t) end_features.minutes_since_midnight, + (num_t) start_features.minutesSinceMidnight, + (num_t) end_features.minutesSinceMidnight, (num_t) start_features.weekday, week_features[PLACE_CATEG_ID_HOME], week_features[PLACE_CATEG_ID_WORK], @@ -398,26 +398,26 @@ std::vector ctx::VisitCateger::interval_features(const interval_s &i }; } -void ctx::VisitCateger::normalize(std::vector &features) +void ctx::VisitCateger::__normalize(std::vector &features) { size_t n = features.size(); for (size_t i = 0; i < n; i++) { - features[i] -= features_mean[i]; - features[i] /= features_std[i]; + features[i] -= __featuresMean[i]; + features[i] /= __featuresStd[i]; } } -void ctx::VisitCateger::categorize(ctx::visit_s &visit) +void ctx::VisitCateger::categorize(ctx::Visit &visit) { - std::vector features = interval_features(visit.interval); - normalize(features); + std::vector features = intervalFeatures(visit.interval); + __normalize(features); - for (auto &model_pair : models) { + for (auto &model_pair : __models) { int categ_i = model_pair.first; MahalModel model = model_pair.second; num_t mahal_dist = model.dist(features); - num_t prob = 1 - chi_approx.val(mahal_dist); // sth like probability but not exactly + num_t prob = 1 - __chiApprox.value(mahal_dist); // sth like probability but not exactly visit.categs[categ_i] = prob; } } diff --git a/src/place/recognition/user_places/visit_categer.h b/src/place/recognition/user_places/visit_categer.h index 6ab762e..d7888bb 100644 --- a/src/place/recognition/user_places/visit_categer.h +++ b/src/place/recognition/user_places/visit_categer.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_VISIT_CATEGER_H__ -#define __CONTEXT_PLACE_STATUS_VISIT_CATEGER_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_VISIT_CATEGER_H_ +#define _CONTEXT_PLACE_RECOGNITION_VISIT_CATEGER_H_ #include "user_places_types.h" #include "mahal.h" @@ -24,9 +24,9 @@ namespace ctx { - struct time_features_s { - int minutes_since_midnight; - int minutes_since_begining_of_the_week; + struct TimeFeatures { + int minutesSinceMidnight; + int minutesSinceBeginingOfTheWeek; int weekday; bool weekend; }; @@ -38,26 +38,25 @@ namespace ctx { private: const static int MINUTES_IN_WEEK = 60 * 24 * 7; - const static std::map models; - const static std::vector features_mean; - const static std::vector features_std; - static num_t sum(const std::vector model, const size_t &from, const size_t &to); - static num_t week_model_mean_value(place_categ_id_e categ, const interval_s &interval, - const time_features_s &start_f, const time_features_s &end_f); - static void normalize(std::vector &features); + const static std::map __models; + const static std::vector __featuresMean; + const static std::vector __featuresStd; + static num_t __sum(const std::vector model, const size_t &from, const size_t &to); + static num_t __weekModelMeanValue(PlaceCategId categ, const Interval &interval, + const TimeFeatures &start_f, const TimeFeatures &end_f); + static void __normalize(std::vector &features); + static PiecewiseLin __chiApprox; // tabled chi function approximator public: - static PiecewiseLin chi_approx; // tabled chi function approximator - /** * Function interpret time in timestamp input argument, * - * @param time timestamp - * @return time_features_s structure with interpretations of timestamp + * @param time timestamp + * @return TimeFeatures structure with interpretations of timestamp */ - static time_features_s time_features(const time_t &time); + static TimeFeatures timeFeatures(const time_t &time); - static int weeks_scope(const time_features_s &start_f, const interval_s &interval); + static int weeksScope(const TimeFeatures &start_f, const Interval &interval); /** * Function interpret time interval input argument and calculates scores @@ -68,8 +67,8 @@ namespace ctx { * @param end_f end time features * @return categs_t score that argument interval is home, work or other */ - static categs_t week_model_features(const interval_s &interval, const time_features_s &start_f, - const time_features_s &end_f); + static categs_t weekModelFeatures(const Interval &interval, const TimeFeatures &start_f, + const TimeFeatures &end_f); /** * Function interpret time interval input argument, @@ -77,15 +76,15 @@ namespace ctx { * @param interval time interval * @return std::vector vector with interpretations of input time interval */ - static std::vector interval_features(const interval_s &interval); + static std::vector intervalFeatures(const Interval &interval); /** * Function categorize visit based on visits time interval and fill its categories values. */ - static void categorize(ctx::visit_s &visit); + static void categorize(ctx::Visit &visit); }; /* class VisitCateger */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_VISIT_CATEGER_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_VISIT_CATEGER_H_ */ diff --git a/src/place/recognition/user_places/visit_detector.cpp b/src/place/recognition/user_places/visit_detector.cpp index 26c3bb5..d0ee631 100644 --- a/src/place/recognition/user_places/visit_detector.cpp +++ b/src/place/recognition/user_places/visit_detector.cpp @@ -25,7 +25,7 @@ #include "visit_detector.h" #include "user_places_params.h" #include "visit_categer.h" -#include "similar.h" +#include "similarity.h" #include "median.h" #include "debug_utils.h" @@ -55,190 +55,184 @@ VISIT_COLUMN_CATEG_OTHER " REAL" #endif /* TIZEN_ENGINEER_MODE */ - -ctx::VisitDetector::VisitDetector(time_t t_start_scan, place_recog_mode_e energy_mode, bool test_mode_) - : test_mode(test_mode_) - , location_logger(this, test_mode_) - , wifi_logger(this, energy_mode, test_mode_) - , current_interval(t_start_scan, t_start_scan + VISIT_DETECTOR_PERIOD_SECONDS_HIGH_ACCURACY) - , stable_counter(0) - , tolerance(VISIT_DETECTOR_TOLERANCE_DEPTH) - , entrance_to_place(false) - , period_seconds(VISIT_DETECTOR_PERIOD_SECONDS_HIGH_ACCURACY) - , entrance_time(0) - , departure_time(0) +ctx::VisitDetector::VisitDetector(time_t t_start_scan, place_recog_mode_e energyMode, bool testMode) : + __testMode(testMode), + __locationLogger(this, testMode), + __wifiLogger(this, energyMode, testMode), + __currentInterval(t_start_scan, t_start_scan + VISIT_DETECTOR_PERIOD_SECONDS_HIGH_ACCURACY), + __stableCounter(0), + __tolerance(VISIT_DETECTOR_TOLERANCE_DEPTH), + __entranceToPlace(false), + __periodSeconds(VISIT_DETECTOR_PERIOD_SECONDS_HIGH_ACCURACY), + __entranceTime(0), + __departureTime(0) { - set_period(energy_mode); - current_interval = interval_s(t_start_scan, t_start_scan + period_seconds); - current_logger = std::make_shared(); - stay_macs = std::make_shared(); + __setPeriod(energyMode); + __currentInterval = Interval(t_start_scan, t_start_scan + __periodSeconds); + __currentLogger = std::make_shared(); + __stayMacs = std::make_shared(); - if (test_mode) { - detected_visits = std::make_shared(); + if (__testMode) { + __detectedVisits = std::make_shared(); return; } - listeners.push_back(&location_logger); - listeners.push_back(&wifi_logger); - db_create_table(); - wifi_logger.start_logging(); + __listeners.push_back(&__locationLogger); + __listeners.push_back(&__wifiLogger); + __dbCreateTable(); + __wifiLogger.startLogging(); } ctx::VisitDetector::~VisitDetector() { } -ctx::interval_s ctx::VisitDetector::get_current_interval() -{ - return current_interval; -} - -bool ctx::VisitDetector::is_valid(const ctx::Mac &mac) +bool ctx::VisitDetector::__isValid(const ctx::Mac &mac) { return mac != "00:00:00:00:00:00"; } -void ctx::VisitDetector::on_wifi_scan(ctx::mac_event_s e) +void ctx::VisitDetector::onWifiScan(ctx::MacEvent e) { - _D("timestamp=%d, curent_interval.end=%d, mac=%s", e.timestamp, current_interval.end, std::string(e.mac).c_str()); - if (is_valid(e.mac)) { - while (e.timestamp > current_interval.end) { - process_current_logger(); - shift_current_interval(); + _D("timestamp=%d, curent_interval.end=%d, mac=%s", e.timestamp, __currentInterval.end, std::string(e.mac).c_str()); + if (__isValid(e.mac)) { + while (e.timestamp > __currentInterval.end) { + __processCurrentLogger(); + __shiftCurrentInterval(); } - current_logger->push_back(e); + __currentLogger->push_back(e); } } -void ctx::VisitDetector::process_current_logger() +void ctx::VisitDetector::__processCurrentLogger() { _D(""); - std::shared_ptr frame = make_frame(this->current_logger, this->current_interval); - detect_entrance_or_departure(frame); - current_logger->clear(); + std::shared_ptr frame = __makeFrame(__currentLogger, __currentInterval); + __detectEntranceOrDeparture(frame); + __currentLogger->clear(); } -std::shared_ptr ctx::VisitDetector::make_frame(std::shared_ptr logger, ctx::interval_s interval) +std::shared_ptr ctx::VisitDetector::__makeFrame(std::shared_ptr logger, ctx::Interval interval) { std::set timestamps; - std::shared_ptr frame = std::make_shared(interval); + std::shared_ptr frame = std::make_shared(interval); for (auto log : *logger) { timestamps.insert(log.timestamp); - if (frame->mac_counts.find(log.mac) == frame->mac_counts.end()) { - frame->mac_counts[log.mac] = 1; + if (frame->macCountsMap.find(log.mac) == frame->macCountsMap.end()) { + frame->macCountsMap[log.mac] = 1; } else { - frame->mac_counts[log.mac] += 1; + frame->macCountsMap[log.mac] += 1; } } - frame->no_timestamps = timestamps.size(); + frame->numberOfTimestamps = timestamps.size(); return frame; } -void ctx::VisitDetector::shift_current_interval() +void ctx::VisitDetector::__shiftCurrentInterval() { - current_interval.end += period_seconds; - current_interval.start += period_seconds; + __currentInterval.end += __periodSeconds; + __currentInterval.start += __periodSeconds; } -void ctx::VisitDetector::detect_entrance_or_departure(std::shared_ptr frame) +void ctx::VisitDetector::__detectEntranceOrDeparture(std::shared_ptr frame) { - entrance_to_place ? detect_departure(frame) : detect_entrance(frame); + __entranceToPlace ? __detectDeparture(frame) : __detectEntrance(frame); } -bool ctx::VisitDetector::is_disjoint(const ctx::mac_counts_t &mac_counts, const ctx::mac_set_t &mac_set) +bool ctx::VisitDetector::__isDisjoint(const ctx::mac_counts_t &macCountsMap, const ctx::mac_set_t &macSet) { - for (auto &mac : mac_set) { - if (mac_counts.find(mac) != mac_counts.end()) { + for (auto &mac : macSet) { + if (macCountsMap.find(mac) != macCountsMap.end()) { return false; } } return true; } -bool ctx::VisitDetector::protrudes_from(const ctx::mac_counts_t &mac_counts, const ctx::mac_set_t &mac_set) +bool ctx::VisitDetector::__protrudesFrom(const ctx::mac_counts_t &macCountsMap, const ctx::mac_set_t &macSet) { - for (auto &m : mac_counts) { - if (mac_set.find(m.first) == mac_set.end()) { + for (auto &m : macCountsMap) { + if (macSet.find(m.first) == macSet.end()) { return true; } } return false; } -void ctx::VisitDetector::detect_departure(std::shared_ptr frame) +void ctx::VisitDetector::__detectDeparture(std::shared_ptr frame) { - if (tolerance == VISIT_DETECTOR_TOLERANCE_DEPTH) { - departure_time = frame->interval.start; - buffered_frames.clear(); - } else { // tolerance < VISIT_DETECTOR_TOLERANCE_DEPTH - buffered_frames.push_back(frame); + if (__tolerance == VISIT_DETECTOR_TOLERANCE_DEPTH) { + __departureTime = frame->interval.start; + __bufferedFrames.clear(); + } else { // __tolerance < VISIT_DETECTOR_TOLERANCE_DEPTH + __bufferedFrames.push_back(frame); } - if (is_disjoint(frame->mac_counts, *rep_macs)) { - if (frame->mac_counts.empty() || protrudes_from(frame->mac_counts, *stay_macs)) { - tolerance--; + if (__isDisjoint(frame->macCountsMap, *__representativesMacs)) { + if (frame->macCountsMap.empty() || __protrudesFrom(frame->macCountsMap, *__stayMacs)) { + __tolerance--; } else { // no new macs - buffered_frames.clear(); + __bufferedFrames.clear(); } - if (tolerance == 0) { // departure detected - visit_end_detected(); - buffer_processing(frame); + if (__tolerance == 0) { // departure detected + __visitEndDetected(); + __processBuffer(frame); } - } else if (tolerance < VISIT_DETECTOR_TOLERANCE_DEPTH) { - tolerance++; + } else if (__tolerance < VISIT_DETECTOR_TOLERANCE_DEPTH) { + __tolerance++; } } -void ctx::VisitDetector::visit_start_detected() +void ctx::VisitDetector::__visitStartDetected() { - entrance_to_place = true; + __entranceToPlace = true; - locations.clear(); - if (!test_mode) { - for (IVisitListener* listener : listeners) { - listener->on_visit_start(); + __locationEvents.clear(); + if (!__testMode) { + for (IVisitListener* listener : __listeners) { + listener->onVisitStart(); } } - rep_macs = select_representatives(history_frames); - entrance_time = history_frames[0]->interval.start; - _I("Entrance detected, timestamp: %d", entrance_time); - history_reset(); + __representativesMacs = __selectRepresentatives(__historyFrames); + __entranceTime = __historyFrames[0]->interval.start; + _I("Entrance detected, timestamp: %d", __entranceTime); + __resetHistory(); } -void ctx::VisitDetector::visit_end_detected() +void ctx::VisitDetector::__visitEndDetected() { - if (!test_mode) { - for (IVisitListener* listener : listeners) { - listener->on_visit_end(); + if (!__testMode) { + for (IVisitListener* listener : __listeners) { + listener->onVisitEnd(); } } - _I("Departure detected, timestamp: %d", departure_time); + _I("Departure detected, timestamp: %d", __departureTime); - interval_s interval(entrance_time, departure_time); - visit_s visit(interval, rep_macs); + Interval interval(__entranceTime, __departureTime); + Visit visit(interval, __representativesMacs); VisitCateger::categorize(visit); - put_visit_location(visit); + __putLocationToVisit(visit); - if (test_mode) { - detected_visits->push_back(visit); + if (__testMode) { + __detectedVisits->push_back(visit); } else { - db_insert_visit(visit); + __dbInsertVisit(visit); } // cleaning - entrance_to_place = false; - rep_macs.reset(); - tolerance = VISIT_DETECTOR_TOLERANCE_DEPTH; + __entranceToPlace = false; + __representativesMacs.reset(); + __tolerance = VISIT_DETECTOR_TOLERANCE_DEPTH; } -void ctx::VisitDetector::put_visit_location(ctx::visit_s &visit) +void ctx::VisitDetector::__putLocationToVisit(ctx::Visit &visit) { // TODO: remove small accuracy locations from vectors? std::vector latitudes; std::vector longitudes; visit.location_valid = false; - for (location_event_s location : locations) { - if (location.timestamp >= entrance_time && location.timestamp <= departure_time) { + for (LocationEvent location : __locationEvents) { + if (location.timestamp >= __entranceTime && location.timestamp <= __departureTime) { latitudes.push_back(location.coordinates.latitude); longitudes.push_back(location.coordinates.longitude); visit.location_valid = true; @@ -253,84 +247,84 @@ void ctx::VisitDetector::put_visit_location(ctx::visit_s &visit) } } -void ctx::VisitDetector::buffer_processing(std::shared_ptr frame) +void ctx::VisitDetector::__processBuffer(std::shared_ptr frame) { - if (buffered_frames.empty()) { - history_frames.push_back(frame); + if (__bufferedFrames.empty()) { + __historyFrames.push_back(frame); } else { - history_frames.push_back(buffered_frames[0]); - for (size_t i = 1; i < buffered_frames.size(); i++) { - detect_entrance(buffered_frames[i]); - if (entrance_to_place) { + __historyFrames.push_back(__bufferedFrames[0]); + for (size_t i = 1; i < __bufferedFrames.size(); i++) { + __detectEntrance(__bufferedFrames[i]); + if (__entranceToPlace) { break; } } } } -void ctx::VisitDetector::detect_entrance(std::shared_ptr current_frame) +void ctx::VisitDetector::__detectEntrance(std::shared_ptr current_frame) { - if (current_frame->mac_counts.empty() || history_frames.empty()) { - history_reset(current_frame); + if (current_frame->macCountsMap.empty() || __historyFrames.empty()) { + __resetHistory(current_frame); return; } - if (stable_counter == 0) { - std::shared_ptr oldest_history_frame = history_frames[0]; - stay_macs = mac_set_from_mac_counts(oldest_history_frame->mac_counts); + if (__stableCounter == 0) { + std::shared_ptr oldest_history_frame = __historyFrames[0]; + __stayMacs = mac_set_from_mac_counts(oldest_history_frame->macCountsMap); } - std::shared_ptr current_beacons = mac_set_from_mac_counts(current_frame->mac_counts); + std::shared_ptr current_beacons = mac_set_from_mac_counts(current_frame->macCountsMap); - if (overlap_bigger_over_smaller(*current_beacons, *stay_macs) > VISIT_DETECTOR_OVERLAP) { - stable_counter++; - history_frames.push_back(current_frame); + if (similarity::overlapBiggerOverSmaller(*current_beacons, *__stayMacs) > VISIT_DETECTOR_OVERLAP) { + __stableCounter++; + __historyFrames.push_back(current_frame); - if (stable_counter == VISIT_DETECTOR_STABLE_DEPTH) { // entrance detected - visit_start_detected(); + if (__stableCounter == VISIT_DETECTOR_STABLE_DEPTH) { // entrance detected + __visitStartDetected(); } } else { - history_reset(current_frame); + __resetHistory(current_frame); } return; } -void ctx::VisitDetector::history_reset() +void ctx::VisitDetector::__resetHistory() { - stable_counter = 0; - history_frames.clear(); + __stableCounter = 0; + __historyFrames.clear(); } -void ctx::VisitDetector::history_reset(std::shared_ptr frame) +void ctx::VisitDetector::__resetHistory(std::shared_ptr frame) { - history_reset(); - history_frames.push_back(frame); + __resetHistory(); + __historyFrames.push_back(frame); } -std::shared_ptr ctx::VisitDetector::select_representatives(const std::vector> &frames) +std::shared_ptr ctx::VisitDetector::__selectRepresentatives(const std::vector> &frames) { mac_counts_t repr_counts; count_t all_count = 0; for (auto frame : frames) { - all_count += frame->no_timestamps; - for (auto &c : frame->mac_counts) { + all_count += frame->numberOfTimestamps; + for (auto &c : frame->macCountsMap) { repr_counts[c.first] += c.second; } } - std::shared_ptr repr_shares = mac_shares_from_counts(repr_counts, all_count); + std::shared_ptr repr_shares = __macSharesFromCounts(repr_counts, all_count); - share_t max_share = calc_max_share(*repr_shares); + share_t max_share = __calcMaxShare(*repr_shares); share_t threshold = max_share < VISIT_DETECTOR_REP_THRESHOLD ? max_share : VISIT_DETECTOR_REP_THRESHOLD; - std::shared_ptr repr_mac_set = mac_set_of_greater_or_equal_share(*repr_shares, threshold); + std::shared_ptr repr_mac_set = __macSetOfGreaterOrEqualShare(*repr_shares, threshold); return repr_mac_set; } -ctx::share_t ctx::VisitDetector::calc_max_share(const ctx::mac_shares_t &mac_shares) +ctx::share_t ctx::VisitDetector::__calcMaxShare(const ctx::mac_shares_t &mac_shares) { ctx::share_t max_value = 0.0; for (auto &ms : mac_shares) { @@ -341,38 +335,38 @@ ctx::share_t ctx::VisitDetector::calc_max_share(const ctx::mac_shares_t &mac_sha return max_value; } -std::shared_ptr ctx::VisitDetector::mac_set_of_greater_or_equal_share(const ctx::mac_shares_t &mac_shares, ctx::share_t threshold) +std::shared_ptr ctx::VisitDetector::__macSetOfGreaterOrEqualShare(const ctx::mac_shares_t &mac_shares, ctx::share_t threshold) { - std::shared_ptr mac_set = std::make_shared(); + std::shared_ptr macSet = std::make_shared(); for (auto &ms : mac_shares) { if (ms.second >= threshold) { - mac_set->insert(ms.first); + macSet->insert(ms.first); } } - return mac_set; + return macSet; } -std::shared_ptr ctx::VisitDetector::mac_shares_from_counts(ctx::mac_counts_t const &mac_counts, ctx::count_t denominator) +std::shared_ptr ctx::VisitDetector::__macSharesFromCounts(ctx::mac_counts_t const &macCountsMap, ctx::count_t denominator) { std::shared_ptr mac_shares(std::make_shared()); - for (auto mac_count : mac_counts) { + for (auto mac_count : macCountsMap) { (*mac_shares)[mac_count.first] = (share_t) mac_count.second / denominator; } return mac_shares; } -std::shared_ptr ctx::VisitDetector::get_visits() +std::shared_ptr ctx::VisitDetector::getVisits() { - return detected_visits; + return __detectedVisits; } -void ctx::VisitDetector::db_create_table() +void ctx::VisitDetector::__dbCreateTable() { bool ret = db_manager::create_table(0, VISIT_TABLE, VISIT_TABLE_COLUMNS); _D("db: visit Table Creation Result: %s", ret ? "SUCCESS" : "FAIL"); } -void ctx::VisitDetector::json_put_visit_categ(Json &data, const char* key, const categs_t &categs, int categ_type) +void ctx::VisitDetector::__putVisitCategToJson(const char* key, const categs_t &categs, int categ_type, Json &data) { auto categ_p = categs.find(categ_type); if (categ_p == categs.end()) { @@ -382,17 +376,17 @@ void ctx::VisitDetector::json_put_visit_categ(Json &data, const char* key, const } } -void ctx::VisitDetector::json_put_visit_categs(Json &data, const categs_t &categs) +void ctx::VisitDetector::__putVisitCategsToJson(const categs_t &categs, Json &data) { - json_put_visit_categ(data, VISIT_COLUMN_CATEG_HOME, categs, PLACE_CATEG_ID_HOME); - json_put_visit_categ(data, VISIT_COLUMN_CATEG_WORK, categs, PLACE_CATEG_ID_WORK); - json_put_visit_categ(data, VISIT_COLUMN_CATEG_OTHER, categs, PLACE_CATEG_ID_OTHER); + __putVisitCategToJson(VISIT_COLUMN_CATEG_HOME, categs, PLACE_CATEG_ID_HOME, data); + __putVisitCategToJson(VISIT_COLUMN_CATEG_WORK, categs, PLACE_CATEG_ID_WORK, data); + __putVisitCategToJson(VISIT_COLUMN_CATEG_OTHER, categs, PLACE_CATEG_ID_OTHER, data); } -int ctx::VisitDetector::db_insert_visit(visit_s visit) +int ctx::VisitDetector::__dbInsertVisit(Visit visit) { std::stringstream macs_ss; - macs_ss << *visit.mac_set; + macs_ss << *visit.macSet; Json data; data.set(NULL, VISIT_COLUMN_WIFI_APS, macs_ss.str().c_str()); @@ -405,51 +399,48 @@ int ctx::VisitDetector::db_insert_visit(visit_s visit) data.set(NULL, VISIT_COLUMN_END_TIME, static_cast(visit.interval.end)); #ifdef TIZEN_ENGINEER_MODE - std::string start_time_human = DebugUtils::human_readable_date_time(visit.interval.start, "%F %T", 80); - std::string end_time_human = DebugUtils::human_readable_date_time(visit.interval.end, "%F %T", 80); + std::string start_time_human = DebugUtils::humanReadableDateTime(visit.interval.start, "%F %T", 80); + std::string end_time_human = DebugUtils::humanReadableDateTime(visit.interval.end, "%F %T", 80); data.set(NULL, VISIT_COLUMN_START_TIME_HUMAN, start_time_human.c_str()); data.set(NULL, VISIT_COLUMN_END_TIME_HUMAN, end_time_human.c_str()); - - json_put_visit_categs(data, visit.categs); - _D("db: visit table insert interval: (%d, %d): (%s, %s)", visit.interval.start, visit.interval.end, start_time_human.c_str(), end_time_human.c_str()); #else - json_put_visit_categs(data, visit.categs); - _D("db: visit table insert interval: (%d, %d)", visit.interval.start, visit.interval.end); #endif /* TIZEN_ENGINEER_MODE */ + __putVisitCategsToJson(visit.categs, data); + int64_t row_id; bool ret = db_manager::insert_sync(VISIT_TABLE, data, &row_id); _D("db: visit table insert result: %s", ret ? "SUCCESS" : "FAIL"); return ret; } -void ctx::VisitDetector::on_new_location(location_event_s location_event) +void ctx::VisitDetector::onNewLocation(LocationEvent location_event) { _D(""); location_event.log(); - locations.push_back(location_event); + __locationEvents.push_back(location_event); }; -void ctx::VisitDetector::set_period(place_recog_mode_e energy_mode) +void ctx::VisitDetector::__setPeriod(place_recog_mode_e energyMode) { - switch (energy_mode) { + switch (energyMode) { case PLACE_RECOG_LOW_POWER_MODE: - period_seconds = VISIT_DETECTOR_PERIOD_SECONDS_LOW_POWER; + __periodSeconds = VISIT_DETECTOR_PERIOD_SECONDS_LOW_POWER; break; case PLACE_RECOG_HIGH_ACCURACY_MODE: - period_seconds = VISIT_DETECTOR_PERIOD_SECONDS_HIGH_ACCURACY; + __periodSeconds = VISIT_DETECTOR_PERIOD_SECONDS_HIGH_ACCURACY; break; default: _E("Incorrect energy mode"); } } -void ctx::VisitDetector::set_mode(place_recog_mode_e energy_mode) +void ctx::VisitDetector::setMode(place_recog_mode_e energyMode) { _D(""); - set_period(energy_mode); - wifi_logger.set_mode(energy_mode); + __setPeriod(energyMode); + __wifiLogger.setMode(energyMode); } diff --git a/src/place/recognition/user_places/visit_detector.h b/src/place/recognition/user_places/visit_detector.h index 52d0b20..a4c9b34 100644 --- a/src/place/recognition/user_places/visit_detector.h +++ b/src/place/recognition/user_places/visit_detector.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_VISIT_DETECTOR_H__ -#define __CONTEXT_PLACE_STATUS_VISIT_DETECTOR_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_VISIT_DETECTOR_H_ +#define _CONTEXT_PLACE_RECOGNITION_VISIT_DETECTOR_H_ #include #include @@ -35,68 +35,67 @@ namespace ctx { class VisitDetector : public IWifiListener, ILocationListener { private: - bool test_mode; - std::shared_ptr detected_visits; // only used in test mode - LocationLogger location_logger; - WifiLogger wifi_logger; - std::vector listeners; - - std::shared_ptr current_logger; - interval_s current_interval; - - std::vector> history_frames; // python: history_scans + history_times - std::vector> buffered_frames; // python: buffered_scans + buffered_times - - int stable_counter; - int tolerance; - bool entrance_to_place; - int period_seconds; + bool __testMode; + std::shared_ptr __detectedVisits; // only used in test mode + LocationLogger __locationLogger; + WifiLogger __wifiLogger; + std::vector __listeners; + std::shared_ptr __currentLogger; + Interval __currentInterval; + std::vector __locationEvents; + std::vector> __historyFrames; // python: history_scans + history_times + std::vector> __bufferedFrames; // python: buffered_scans + buffered_times + int __stableCounter; + int __tolerance; + bool __entranceToPlace; + int __periodSeconds; // fields that are used only in case of entrance detection - std::shared_ptr rep_macs; // mac that represent the current place - std::shared_ptr stay_macs; // macs that can appear in the current place - time_t entrance_time; - time_t departure_time; - - std::vector locations; - - bool is_valid(const Mac &mac); - void shift_current_interval(); - void detect_entrance_or_departure(std::shared_ptr frame); - void detect_entrance(std::shared_ptr frame); - void detect_departure(std::shared_ptr frame); - void buffer_processing(std::shared_ptr frame); // python: buffer_anaysing - std::shared_ptr make_frame(std::shared_ptr mac_events, interval_s interval); // python: scans2fingerprint - void history_reset(); - void history_reset(std::shared_ptr frame); - void visit_start_detected(); - void visit_end_detected(); - void put_visit_location(visit_s &visit); - std::shared_ptr select_representatives(const std::vector> &frames); - std::shared_ptr mac_set_of_greater_or_equal_share(const mac_shares_t &mac_shares, share_t threshold); - std::shared_ptr mac_shares_from_counts(mac_counts_t const &mac_counts, count_t denominator); // python: response_rate - share_t calc_max_share(const mac_shares_t &mac_shares); - bool is_disjoint(const mac_counts_t &mac_counts, const mac_set_t &mac_set); - bool protrudes_from(const mac_counts_t &mac_counts, const mac_set_t &mac_set); - - void db_create_table(); - void json_put_visit_categ(Json &data, const char* key, const categs_t &categs, int categ_type); - void json_put_visit_categs(Json &data, const categs_t &categs); - int db_insert_visit(visit_s visit); - void set_period(place_recog_mode_e mode); + std::shared_ptr __representativesMacs; // macs that represent the current place + std::shared_ptr __stayMacs; // macs that can appear in the current place + time_t __entranceTime; + time_t __departureTime; + + bool __isValid(const Mac &mac); + void __shiftCurrentInterval(); + void __detectEntranceOrDeparture(std::shared_ptr frame); + void __detectEntrance(std::shared_ptr frame); + void __detectDeparture(std::shared_ptr frame); + void __processBuffer(std::shared_ptr frame); // python: buffer_analysing + std::shared_ptr __makeFrame(std::shared_ptr mac_events, Interval interval); // python: scans2fingerprint + void __resetHistory(); + void __resetHistory(std::shared_ptr frame); + void __visitStartDetected(); + void __visitEndDetected(); + void __putLocationToVisit(Visit &visit); + std::shared_ptr __selectRepresentatives(const std::vector> &frames); + std::shared_ptr __macSetOfGreaterOrEqualShare(const mac_shares_t &mac_shares, share_t threshold); + std::shared_ptr __macSharesFromCounts(mac_counts_t const &mac_counts, count_t denominator); // python: response_rate + share_t __calcMaxShare(const mac_shares_t &mac_shares); + bool __isDisjoint(const mac_counts_t &mac_counts, const mac_set_t &macSet); + bool __protrudesFrom(const mac_counts_t &mac_counts, const mac_set_t &macSet); + void __setPeriod(place_recog_mode_e mode); + void __processCurrentLogger(); + + /* DATABASE */ + void __dbCreateTable(); + int __dbInsertVisit(Visit visit); + void __putVisitCategToJson(const char* key, const categs_t &categs, int categ_type, Json &data); + void __putVisitCategsToJson(const categs_t &categs, Json &data); + + /* INPUT */ + void onWifiScan(MacEvent event); + void onNewLocation(LocationEvent location); public: - VisitDetector(time_t t_start_scan, place_recog_mode_e energy_mode = PLACE_RECOG_HIGH_ACCURACY_MODE, bool test_mode_ = false); + VisitDetector(time_t t_start_scan, place_recog_mode_e energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE, bool testMode = false); ~VisitDetector(); - interval_s get_current_interval(); - void on_wifi_scan(mac_event_s event); - void process_current_logger(); - std::shared_ptr get_visits(); // only used in test mode - void on_new_location(location_event_s location); - void set_mode(place_recog_mode_e energy_mode); + + std::shared_ptr getVisits(); // only used in test mode + void setMode(place_recog_mode_e energyMode); }; /* class VisitDetector */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_VISIT_DETECTOR_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_VISIT_DETECTOR_H_ */ diff --git a/src/place/recognition/user_places/visit_listener_iface.h b/src/place/recognition/user_places/visit_listener_iface.h index 9b87b70..fefc926 100644 --- a/src/place/recognition/user_places/visit_listener_iface.h +++ b/src/place/recognition/user_places/visit_listener_iface.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_VISIT_LISTENER_IFACE_H__ -#define __CONTEXT_PLACE_STATUS_VISIT_LISTENER_IFACE_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_VISIT_LISTENER_IFACE_H_ +#define _CONTEXT_PLACE_RECOGNITION_VISIT_LISTENER_IFACE_H_ namespace ctx { @@ -23,11 +23,11 @@ namespace ctx { public: virtual ~IVisitListener() {}; - virtual void on_visit_start() = 0; - virtual void on_visit_end() = 0; + virtual void onVisitStart() = 0; + virtual void onVisitEnd() = 0; }; /* class IVisitListener */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_VISIT_LISTENER_IFACE_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_VISIT_LISTENER_IFACE_H_ */ diff --git a/src/place/recognition/user_places/wifi_listener_iface.h b/src/place/recognition/user_places/wifi_listener_iface.h index e9a546c..8f91c22 100644 --- a/src/place/recognition/user_places/wifi_listener_iface.h +++ b/src/place/recognition/user_places/wifi_listener_iface.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_WIFI_LISTENER_IFACE_H__ -#define __CONTEXT_PLACE_STATUS_WIFI_LISTENER_IFACE_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_WIFI_LISTENER_IFACE_H_ +#define _CONTEXT_PLACE_RECOGNITION_WIFI_LISTENER_IFACE_H_ #include "user_places_types.h" @@ -25,10 +25,10 @@ namespace ctx { public: virtual ~IWifiListener() {}; - virtual void on_wifi_scan(ctx::mac_event_s e) = 0; + virtual void onWifiScan(ctx::MacEvent e) = 0; }; /* IWifiListener */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_WIFI_LISTENER_IFACE_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_WIFI_LISTENER_IFACE_H_ */ diff --git a/src/place/recognition/user_places/wifi_logger.cpp b/src/place/recognition/user_places/wifi_logger.cpp index 7d0c89d..29dabd4 100644 --- a/src/place/recognition/user_places/wifi_logger.cpp +++ b/src/place/recognition/user_places/wifi_logger.cpp @@ -27,100 +27,100 @@ #define _WIFI_ERROR_LOG(error) { \ if (error != WIFI_ERROR_NONE) { \ - _E("ERROR == %s", wifi_error_str(error)); \ + _E("ERROR == %s", __wifiError2Str(error)); \ } else { \ _D("SUCCESS"); \ } \ } -int ctx::WifiLogger::create_table() +int ctx::WifiLogger::__dbCreateTable() { bool ret = db_manager::create_table(0, WIFI_TABLE_NAME, WIFI_CREATE_TABLE_COLUMNS, NULL, NULL); _D("Table Creation Request: %s", ret ? "SUCCESS" : "FAIL"); return ret; } -int ctx::WifiLogger::db_insert_logs() +int ctx::WifiLogger::__dbInsertLogs() { - if (logs.size() > 0) { + if (__logs.size() > 0) { std::stringstream query; const char* separator = " "; query << "BEGIN TRANSACTION; \ INSERT INTO " WIFI_TABLE_NAME " \ ( " WIFI_COLUMN_BSSID ", " WIFI_COLUMN_TIMESTAMP " ) \ VALUES"; - for (mac_event_s mac_event : logs) { + for (MacEvent mac_event : __logs) { query << separator << "( '" << mac_event.mac << "', '" << mac_event.timestamp << "' )"; separator = ", "; } - logs.clear(); + __logs.clear(); query << "; \ END TRANSACTION;"; bool ret = ctx::db_manager::execute(0, query.str().c_str(), NULL); _D("DB insert request: %s", ret ? "SUCCESS" : "FAIL"); return ret; } - _D("logs vector empty -> nothing to insert"); + _D("__logs vector empty -> nothing to insert"); return 0; } -ctx::WifiLogger::WifiLogger(IWifiListener * listener_, place_recog_mode_e energy_mode, bool test_mode_) - : test_mode(test_mode_) - , listener(listener_) - , last_scan_time(time_t(0)) - , last_timer_callback_time(time_t(0)) - , timer_on(false) - , interval_minutes(WIFI_LOGGER_INTERVAL_MINUTES_HIGH_ACCURACY) - , during_visit(false) - , connected_to_wifi_ap(false) - , started(false) - , running(false) +ctx::WifiLogger::WifiLogger(IWifiListener * listener, place_recog_mode_e energyMode, bool testMode) : + __timerOn(false), + __intervalMinutes(WIFI_LOGGER_INTERVAL_MINUTES_HIGH_ACCURACY), + __testMode(testMode), + __listener(listener), + __lastScanTime(time_t(0)), + __lasTimerCallbackTime(time_t(0)), + __duringVisit(false), + __connectedToWifiAp(false), + __started(false), + __running(false) { _D("CONSTRUCTOR"); - if (test_mode) { + if (testMode) { return; } - set_interval(energy_mode); + __setInterval(energyMode); if (WIFI_LOGGER_DATABASE) { - create_table(); + __dbCreateTable(); } - logs = std::vector(); + __logs = std::vector(); - wifi_initialize_request(); - wifi_set_device_state_changed_cb_request(); + __wifiInitializeRequest(); + __wifiSetDeviceStateChangedCbRequest(); if (WIFI_LOGGER_LOW_POWER_MODE) { - wifi_set_connection_state_changed_cb_request(); + __wifiSetConnectionStateChangedCbRequest(); } - wifi_connection_state_e state = wifi_get_connection_state_request(); - connected_to_wifi_ap = (state == WIFI_CONNECTION_STATE_CONNECTED); - _D("connected_to_wifi_ap = %d, during_visit = %d IN CONSTRUCTOR", - static_cast(connected_to_wifi_ap), - static_cast(during_visit)); + wifi_connection_state_e state = __wifiGetConnectionStateRequest(); + __connectedToWifiAp = (state == WIFI_CONNECTION_STATE_CONNECTED); + _D("__connectedToWifiAp = %d, __duringVisit = %d IN CONSTRUCTOR", + static_cast(__connectedToWifiAp), + static_cast(__duringVisit)); } ctx::WifiLogger::~WifiLogger() { _D("DESTRUCTOR"); - stop_logging(); - wifi_deinitialize_request(); + stopLogging(); + __wifiDeinitializeRequest(); } -void ctx::WifiLogger::wifi_device_state_changed_cb(wifi_device_state_e state, void *user_data) +void ctx::WifiLogger::__wifiDeviceStateChangedCb(wifi_device_state_e state, void *user_data) { - ctx::WifiLogger* wifi_logger_p = (ctx::WifiLogger *)user_data; + ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)user_data; switch (state) { case WIFI_DEVICE_STATE_DEACTIVATED: _D("WIFI setting OFF"); - if (wifi_logger_p->started) { - wifi_logger_p->_stop_logging(); + if (wifiLogger->__started) { + wifiLogger->__stopLogging(); } break; case WIFI_DEVICE_STATE_ACTIVATED: _D("WIFI setting ON"); - if (wifi_logger_p->started) { - wifi_logger_p->_start_logging(); + if (wifiLogger->__started) { + wifiLogger->__startLogging(); } break; default: @@ -128,29 +128,29 @@ void ctx::WifiLogger::wifi_device_state_changed_cb(wifi_device_state_e state, vo } } -void ctx::WifiLogger::wifi_connection_state_changed_cb(wifi_connection_state_e state, wifi_ap_h ap, void *user_data) +void ctx::WifiLogger::__wifiConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *user_data) { - ctx::WifiLogger* wifi_logger_p = (ctx::WifiLogger *)user_data; + ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)user_data; switch (state) { case WIFI_CONNECTION_STATE_CONNECTED: _D("connected to AP"); - wifi_logger_p->connected_to_wifi_ap = true; + wifiLogger->__connectedToWifiAp = true; break; default: - _D("disconnected from AP -> last_scans_pool.clear()"); - wifi_logger_p->connected_to_wifi_ap = false; - wifi_logger_p->last_scans_pool.clear(); + _D("disconnected from AP -> __lastScansPool.clear()"); + wifiLogger->__connectedToWifiAp = false; + wifiLogger->__lastScansPool.clear(); break; } // TODO: Check if AP bssid (MAC Address) will be helpful somehow in LOW_POWER mode } -bool ctx::WifiLogger::wifi_found_ap_cb(wifi_ap_h ap, void *user_data) +bool ctx::WifiLogger::__wifiFoundApCb(wifi_ap_h ap, void *user_data) { - ctx::WifiLogger* wifi_logger_p = (ctx::WifiLogger *)user_data; + ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)user_data; char *bssid = NULL; - int ret = wifi_ap_get_bssid_request(ap, &bssid); + int ret = __wifiApGetBssidRequest(ap, &bssid); if (ret != WIFI_ERROR_NONE) { return false; } @@ -163,23 +163,23 @@ bool ctx::WifiLogger::wifi_found_ap_cb(wifi_ap_h ap, void *user_data) return false; } - mac_event_s log(wifi_logger_p->last_scan_time, mac); - if (wifi_logger_p->listener) { - wifi_logger_p->listener->on_wifi_scan(log); + MacEvent log(wifiLogger->__lastScanTime, mac); + if (wifiLogger->__listener) { + wifiLogger->__listener->onWifiScan(log); if (WIFI_LOGGER_LOW_POWER_MODE - && (wifi_logger_p->connected_to_wifi_ap || wifi_logger_p->during_visit) ) { + && (wifiLogger->__connectedToWifiAp || wifiLogger->__duringVisit) ) { // Add to last scans AP's set - wifi_logger_p->last_scans_pool.insert(std::string(bssid)); + wifiLogger->__lastScansPool.insert(std::string(bssid)); } } if (WIFI_LOGGER_DATABASE) { - wifi_logger_p->logs.push_back(log); + wifiLogger->__logs.push_back(log); } return true; } -const char* ctx::WifiLogger::wifi_error_str(int error) +const char* ctx::WifiLogger::__wifiError2Str(int error) { switch (error) { case WIFI_ERROR_INVALID_PARAMETER: @@ -215,36 +215,36 @@ const char* ctx::WifiLogger::wifi_error_str(int error) } } -void ctx::WifiLogger::wifi_scan_finished_cb(wifi_error_e error_code, void *user_data) +void ctx::WifiLogger::__wifiScanFinishedCb(wifi_error_e error_code, void *user_data) { - ctx::WifiLogger* wifi_logger_p = (ctx::WifiLogger *)user_data; + ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)user_data; time_t now = time(nullptr); #ifdef TIZEN_ENGINEER_MODE double seconds = 0; - if (wifi_logger_p->last_scan_time > 0) { - seconds = difftime(now, wifi_logger_p->last_scan_time); + if (wifiLogger->__lastScanTime > 0) { + seconds = difftime(now, wifiLogger->__lastScanTime); } - std::string time_str = DebugUtils::human_readable_date_time(now, "%T", 9); - _D("connected_to_wifi_ap = %d, during_visit = %d, last_scans_pool.size() = %d -> scan %s (from last : %.1fs)", - static_cast(wifi_logger_p->connected_to_wifi_ap), - static_cast(wifi_logger_p->during_visit), - wifi_logger_p->last_scans_pool.size(), + std::string time_str = DebugUtils::humanReadableDateTime(now, "%T", 9); + _D("__connectedToWifiAp = %d, __duringVisit = %d, __lastScansPool.size() = %d -> scan %s (from last : %.1fs)", + static_cast(wifiLogger->__connectedToWifiAp), + static_cast(wifiLogger->__duringVisit), + wifiLogger->__lastScansPool.size(), time_str.c_str(), seconds); #endif /* TIZEN_ENGINEER_MODE */ - wifi_logger_p->last_scan_time = now; + wifiLogger->__lastScanTime = now; - int ret = wifi_foreach_found_aps_request(user_data); + int ret = __wifiForeachFoundApsRequest(user_data); if (ret != WIFI_ERROR_NONE) { return; } if (WIFI_LOGGER_DATABASE) { - wifi_logger_p->db_insert_logs(); + wifiLogger->__dbInsertLogs(); } } -bool ctx::WifiLogger::check_wifi_is_activated() +bool ctx::WifiLogger::__checkWifiIsActivated() { bool wifi_activated = true; int ret = wifi_is_activated(&wifi_activated); @@ -253,20 +253,20 @@ bool ctx::WifiLogger::check_wifi_is_activated() return wifi_activated; } -void ctx::WifiLogger::wifi_scan_request() +void ctx::WifiLogger::__wifiScanRequest() { - int ret = wifi_scan(wifi_scan_finished_cb, this); + int ret = wifi_scan(__wifiScanFinishedCb, this); _WIFI_ERROR_LOG(ret); } -int ctx::WifiLogger::wifi_foreach_found_aps_request(void *user_data) +int ctx::WifiLogger::__wifiForeachFoundApsRequest(void *user_data) { - int ret = wifi_foreach_found_aps(wifi_found_ap_cb, user_data); + int ret = wifi_foreach_found_aps(__wifiFoundApCb, user_data); _WIFI_ERROR_LOG(ret); return ret; } -wifi_connection_state_e ctx::WifiLogger::wifi_get_connection_state_request() +wifi_connection_state_e ctx::WifiLogger::__wifiGetConnectionStateRequest() { wifi_connection_state_e connection_state; int ret = wifi_get_connection_state(&connection_state); @@ -274,67 +274,67 @@ wifi_connection_state_e ctx::WifiLogger::wifi_get_connection_state_request() return connection_state; } -void ctx::WifiLogger::wifi_set_background_scan_cb_request() +void ctx::WifiLogger::__wifiSetBackgroundScanCbRequest() { - int ret = wifi_set_background_scan_cb(wifi_scan_finished_cb, this); + int ret = wifi_set_background_scan_cb(__wifiScanFinishedCb, this); _WIFI_ERROR_LOG(ret); } -void ctx::WifiLogger::wifi_set_device_state_changed_cb_request() +void ctx::WifiLogger::__wifiSetDeviceStateChangedCbRequest() { - int ret = wifi_set_device_state_changed_cb(wifi_device_state_changed_cb, this); + int ret = wifi_set_device_state_changed_cb(__wifiDeviceStateChangedCb, this); _WIFI_ERROR_LOG(ret); } -void ctx::WifiLogger::wifi_set_connection_state_changed_cb_request() +void ctx::WifiLogger::__wifiSetConnectionStateChangedCbRequest() { - int ret = wifi_set_connection_state_changed_cb(wifi_connection_state_changed_cb, this); + int ret = wifi_set_connection_state_changed_cb(__wifiConnectionStateChangedCb, this); _WIFI_ERROR_LOG(ret); } -int ctx::WifiLogger::wifi_ap_get_bssid_request(wifi_ap_h ap, char **bssid) +int ctx::WifiLogger::__wifiApGetBssidRequest(wifi_ap_h ap, char **bssid) { int ret = wifi_ap_get_bssid(ap, bssid); _WIFI_ERROR_LOG(ret); return ret; } -void ctx::WifiLogger::wifi_initialize_request() +void ctx::WifiLogger::__wifiInitializeRequest() { int ret = wifi_initialize(); _WIFI_ERROR_LOG(ret); } -void ctx::WifiLogger::wifi_deinitialize_request() +void ctx::WifiLogger::__wifiDeinitializeRequest() { int ret = wifi_deinitialize(); _WIFI_ERROR_LOG(ret); } -bool ctx::WifiLogger::check_timer_id(int id) +bool ctx::WifiLogger::__checkTimerId(int id) { - _D("id == %d, timer_id == %d", id, timer_id); - return id == timer_id; + _D("id == %d, __timerId == %d", id, __timerId); + return id == __timerId; } /* * Accepted time from last callback is >= than minimum interval */ -bool ctx::WifiLogger::check_timer_time(time_t now) +bool ctx::WifiLogger::__checkTimerTime(time_t now) { double seconds = 0; - if (last_timer_callback_time > 0) { - seconds = difftime(now, last_timer_callback_time); + if (__lasTimerCallbackTime > 0) { + seconds = difftime(now, __lasTimerCallbackTime); if (seconds < WIFI_LOGGER_ACTIVE_SCANNING_MIN_INTERVAL) { - _D("last == %d, now == %d, diff = %.1fs -> Incorrect timer callback", last_timer_callback_time, now, seconds); + _D("last == %d, now == %d, diff = %.1fs -> Incorrect timer callback", __lasTimerCallbackTime, now, seconds); return false; } else { - _D("last == %d, now == %d, diff = %.1fs -> Correct timer callback", last_timer_callback_time, now, seconds); + _D("last == %d, now == %d, diff = %.1fs -> Correct timer callback", __lasTimerCallbackTime, now, seconds); } } else { - _D("last == %d, now == %d -> First callback", last_timer_callback_time, now); + _D("last == %d, now == %d -> First callback", __lasTimerCallbackTime, now); } - last_timer_callback_time = now; + __lasTimerCallbackTime = now; return true; } @@ -342,132 +342,132 @@ bool ctx::WifiLogger::onTimerExpired(int id) { time_t now = time(nullptr); _D(""); - if (check_timer_id(id) == false) { + if (__checkTimerId(id) == false) { // Incorrect callback call return false; } - if (check_timer_time(now) == false) { + if (__checkTimerTime(now) == false) { // Prevention from double callback call bug - return timer_on; + return __timerOn; } - _D("connected_to_wifi_ap = %d, during_visit = %d, last_scans_pool.size() = %d", - static_cast(connected_to_wifi_ap), - static_cast(during_visit), - last_scans_pool.size()); + _D("__connectedToWifiAp = %d, __duringVisit = %d, __lastScansPool.size() = %d", + static_cast(__connectedToWifiAp), + static_cast(__duringVisit), + __lastScansPool.size()); if (WIFI_LOGGER_LOW_POWER_MODE - && during_visit - && connected_to_wifi_ap - && last_scans_pool.size() > 0) { + && __duringVisit + && __connectedToWifiAp + && __lastScansPool.size() > 0) { _D("trying to send fake scan"); - if (listener) { - _D("listener != false -> CORRECT"); - for (std::string bssid : last_scans_pool) { + if (__listener) { + _D("__listener != false -> CORRECT"); + for (std::string bssid : __lastScansPool) { Mac mac(bssid); - mac_event_s scan(now, mac); + MacEvent scan(now, mac); _D("send fake scan (%s)", bssid.c_str()); - listener->on_wifi_scan(scan); + __listener->onWifiScan(scan); } } } else { - wifi_scan_request(); + __wifiScanRequest(); } - return timer_on; + return __timerOn; } -void ctx::WifiLogger::start_logging() +void ctx::WifiLogger::startLogging() { _D(""); - started = true; - _start_logging(); + __started = true; + __startLogging(); } -void ctx::WifiLogger::_start_logging() +void ctx::WifiLogger::__startLogging() { _D(""); - if (!check_wifi_is_activated() || running) { + if (!__checkWifiIsActivated() || __running) { return; } - running = true; + __running = true; if (WIFI_LOGGER_ACTIVE_SCANNING) { - timer_start(interval_minutes); - wifi_scan_request(); + __timerStart(__intervalMinutes); + __wifiScanRequest(); } if (WIFI_LOGGER_PASSIVE_SCANNING) { - wifi_set_background_scan_cb_request(); + __wifiSetBackgroundScanCbRequest(); } } -void ctx::WifiLogger::stop_logging() +void ctx::WifiLogger::stopLogging() { _D(""); - started = false; - _stop_logging(); + __started = false; + __stopLogging(); } -void ctx::WifiLogger::_stop_logging() +void ctx::WifiLogger::__stopLogging() { _D(""); - if (!running) { + if (!__running) { return; } if (WIFI_LOGGER_ACTIVE_SCANNING) { // Unset timer - timer_on = false; + __timerOn = false; // Remove timer - __timerManager.remove(timer_id); + __timerManager.remove(__timerId); } if (WIFI_LOGGER_PASSIVE_SCANNING) { wifi_unset_background_scan_cb(); } - running = false; + __running = false; } -void ctx::WifiLogger::timer_start(time_t minutes) +void ctx::WifiLogger::__timerStart(time_t minutes) { - timer_on = true; - timer_id = __timerManager.setFor(minutes, this); - _D("%s (minutes=%d)", timer_id >= 0 ? "SUCCESS" : "ERROR", minutes); + __timerOn = true; + __timerId = __timerManager.setFor(minutes, this); + _D("%s (minutes=%d)", __timerId >= 0 ? "SUCCESS" : "ERROR", minutes); } -void ctx::WifiLogger::on_visit_start() +void ctx::WifiLogger::onVisitStart() { _D(""); - during_visit = true; + __duringVisit = true; } -void ctx::WifiLogger::on_visit_end() +void ctx::WifiLogger::onVisitEnd() { - _D("last_scans_pool.clear()"); - during_visit = false; - last_scans_pool.clear(); + _D("__lastScansPool.clear()"); + __duringVisit = false; + __lastScansPool.clear(); } -void ctx::WifiLogger::set_interval(place_recog_mode_e energy_mode) +void ctx::WifiLogger::__setInterval(place_recog_mode_e energyMode) { - switch (energy_mode) { + switch (energyMode) { case PLACE_RECOG_LOW_POWER_MODE: - interval_minutes = WIFI_LOGGER_INTERVAL_MINUTES_LOW_POWER; + __intervalMinutes = WIFI_LOGGER_INTERVAL_MINUTES_LOW_POWER; break; case PLACE_RECOG_HIGH_ACCURACY_MODE: - interval_minutes = WIFI_LOGGER_INTERVAL_MINUTES_HIGH_ACCURACY; + __intervalMinutes = WIFI_LOGGER_INTERVAL_MINUTES_HIGH_ACCURACY; break; default: _E("Incorrect energy mode"); } } -void ctx::WifiLogger::timer_restart() +void ctx::WifiLogger::__timerRestart() { - __timerManager.remove(timer_id); - timer_start(interval_minutes); + __timerManager.remove(__timerId); + __timerStart(__intervalMinutes); } -void ctx::WifiLogger::set_mode(place_recog_mode_e energy_mode) +void ctx::WifiLogger::setMode(place_recog_mode_e energyMode) { _D(""); - set_interval(energy_mode); - if (WIFI_LOGGER_ACTIVE_SCANNING && timer_on) { - timer_restart(); + __setInterval(energyMode); + if (WIFI_LOGGER_ACTIVE_SCANNING && __timerOn) { + __timerRestart(); } } diff --git a/src/place/recognition/user_places/wifi_logger.h b/src/place/recognition/user_places/wifi_logger.h index 6b9ecb6..029eee1 100644 --- a/src/place/recognition/user_places/wifi_logger.h +++ b/src/place/recognition/user_places/wifi_logger.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef __CONTEXT_PLACE_STATUS_WIFI_LOGGER_H__ -#define __CONTEXT_PLACE_STATUS_WIFI_LOGGER_H__ +#ifndef _CONTEXT_PLACE_RECOGNITION_WIFI_LOGGER_H_ +#define _CONTEXT_PLACE_RECOGNITION_WIFI_LOGGER_H_ #include #include @@ -50,65 +50,72 @@ namespace ctx { class WifiLogger : public ITimerListener, public IVisitListener { public: - WifiLogger(IWifiListener * listener_ = nullptr, + WifiLogger(IWifiListener * listener = nullptr, place_recog_mode_e mode = PLACE_RECOG_HIGH_ACCURACY_MODE, - bool test_mode_ = false); + bool testMode = false); ~WifiLogger(); - void start_logging(); - void stop_logging(); - void set_mode(place_recog_mode_e energy_mode); - - /* INPUT */ - void on_visit_start(); - void on_visit_end(); + void startLogging(); + void stopLogging(); + void setMode(place_recog_mode_e energyMode); private: - bool test_mode; - IWifiListener * const listener; - std::vector logs; - std::set last_scans_pool; - time_t last_scan_time; - time_t last_timer_callback_time; - bool timer_on; - int timer_id; - int interval_minutes; - bool during_visit; - bool connected_to_wifi_ap; - bool started; - bool running; - TimerManager __timerManager; - - void _start_logging(); - void _stop_logging(); - void set_interval(place_recog_mode_e energy_mode); + /* INPUT */ + void onVisitStart(); + void onVisitEnd(); - bool check_timer_id(int id); - bool check_timer_time(time_t now); bool onTimerExpired(int timerId); - static int create_table(); - int db_insert_logs(); - static void wifi_device_state_changed_cb(wifi_device_state_e state, void *user_data); - static void wifi_connection_state_changed_cb(wifi_connection_state_e state, wifi_ap_h ap, void *user_data); - static bool wifi_found_ap_cb(wifi_ap_h ap, void *user_data); - static void wifi_scan_finished_cb(wifi_error_e error_code, void *user_data); - static bool check_wifi_is_activated(); - void wifi_scan_request(); - static int wifi_foreach_found_aps_request(void *user_data); - static wifi_connection_state_e wifi_get_connection_state_request(); - void wifi_set_background_scan_cb_request(); - void wifi_set_device_state_changed_cb_request(); - void wifi_set_connection_state_changed_cb_request(); - static int wifi_ap_get_bssid_request(wifi_ap_h ap, char **bssid); - void wifi_initialize_request(); - void wifi_deinitialize_request(); - static const char* wifi_error_str(int error); - - void timer_start(time_t minutes); - void timer_restart(); + + /* TIMER */ + bool __timerOn; + int __timerId; + int __intervalMinutes; + TimerManager __timerManager; + void __setInterval(place_recog_mode_e energyMode); + bool __checkTimerId(int id); + bool __checkTimerTime(time_t now); + void __timerStart(time_t minutes); + void __timerRestart(); + + /* DATABASE */ + static int __dbCreateTable(); + int __dbInsertLogs(); + + /* SYSTEM CAPI WRAPPERS */ + void __wifiSetBackgroundScanCbRequest(); + void __wifiSetDeviceStateChangedCbRequest(); + void __wifiSetConnectionStateChangedCbRequest(); + static bool __checkWifiIsActivated(); + void __wifiScanRequest(); + static int __wifiForeachFoundApsRequest(void *user_data); + static wifi_connection_state_e __wifiGetConnectionStateRequest(); + static int __wifiApGetBssidRequest(wifi_ap_h ap, char **bssid); + void __wifiInitializeRequest(); + void __wifiDeinitializeRequest(); + + /* SYSTEM CAPI CALLBACKS */ + static void __wifiDeviceStateChangedCb(wifi_device_state_e state, void *user_data); + static void __wifiConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *user_data); + static bool __wifiFoundApCb(wifi_ap_h ap, void *user_data); + static void __wifiScanFinishedCb(wifi_error_e error_code, void *user_data); + + bool __testMode; + IWifiListener * const __listener; + std::vector __logs; + std::set __lastScansPool; + time_t __lastScanTime; + time_t __lasTimerCallbackTime; + bool __duringVisit; + bool __connectedToWifiAp; + bool __started; + bool __running; + + void __startLogging(); + void __stopLogging(); + static const char* __wifiError2Str(int error); }; /* class WifiLogger */ } /* namespace ctx */ -#endif /* __CONTEXT_PLACE_STATUS_WIFI_LOGGER_H__ */ +#endif /* End of _CONTEXT_PLACE_RECOGNITION_WIFI_LOGGER_H_ */ -- 2.7.4 From f9c4591fee76e7e536088d1d8c9512463104caa0 Mon Sep 17 00:00:00 2001 From: Marcin Masternak Date: Tue, 12 Apr 2016 17:23:35 +0200 Subject: [PATCH 12/16] Applying Tizen C++ coding style to place context provider(recognition) part 2. Change-Id: Ic8c198dc776eae2261ced0e48b0814ecd0419a5b Signed-off-by: Marcin Masternak --- src/place/PlaceContextProvider.cpp | 4 +- src/place/recognition/place_recognition.cpp | 32 ++-- src/place/recognition/place_recognition.h | 12 +- src/place/recognition/place_recognition_types.h | 4 +- src/place/recognition/user_places/gmap.cpp | 16 +- src/place/recognition/user_places/gmap.h | 6 +- src/place/recognition/user_places/graph.cpp | 14 +- .../recognition/user_places/location_logger.cpp | 98 +++++------ .../recognition/user_places/location_logger.h | 15 +- src/place/recognition/user_places/mahal.cpp | 6 +- src/place/recognition/user_places/mahal.h | 4 +- .../recognition/user_places/place_categer.cpp | 77 +++++---- src/place/recognition/user_places/place_categer.h | 10 +- .../recognition/user_places/places_detector.cpp | 184 ++++++++++----------- .../recognition/user_places/places_detector.h | 14 +- src/place/recognition/user_places/user_places.cpp | 24 +-- src/place/recognition/user_places/user_places.h | 4 +- .../recognition/user_places/user_places_types.cpp | 62 +++---- .../recognition/user_places/user_places_types.h | 66 ++++---- .../recognition/user_places/visit_categer.cpp | 79 +++++---- src/place/recognition/user_places/visit_categer.h | 30 ++-- .../recognition/user_places/visit_detector.cpp | 171 ++++++++++--------- src/place/recognition/user_places/visit_detector.h | 34 ++-- .../recognition/user_places/wifi_listener_iface.h | 2 +- src/place/recognition/user_places/wifi_logger.cpp | 72 ++++---- src/place/recognition/user_places/wifi_logger.h | 16 +- 26 files changed, 532 insertions(+), 524 deletions(-) diff --git a/src/place/PlaceContextProvider.cpp b/src/place/PlaceContextProvider.cpp index f168dd1..8eb7596 100644 --- a/src/place/PlaceContextProvider.cpp +++ b/src/place/PlaceContextProvider.cpp @@ -43,8 +43,8 @@ EXTAPI bool ctx::initPlaceContextProvider() PlaceGeofenceProvider::submitTriggerItem(); #ifndef _DISABLE_RECOG_ENGINE_ - place_recognition_provider::create(NULL); - registerProvider(PLACE_SUBJ_RECOGNITION, PLACE_PRIV_RECOGNITION); + PlaceRecognitionProvider::create(NULL); + registerProvider(PLACE_SUBJ_RECOGNITION, PLACE_PRIV_RECOGNITION); #endif /* _DISABLE_RECOG_ENGINE_ */ #endif /* _MOBILE_ */ diff --git a/src/place/recognition/place_recognition.cpp b/src/place/recognition/place_recognition.cpp index 60b174f..76c09e1 100644 --- a/src/place/recognition/place_recognition.cpp +++ b/src/place/recognition/place_recognition.cpp @@ -19,18 +19,18 @@ #include "place_recognition.h" #include "user_places/user_places.h" -ctx::place_recognition_provider *ctx::place_recognition_provider::__instance = NULL; +ctx::PlaceRecognitionProvider *ctx::PlaceRecognitionProvider::__instance = NULL; -ctx::ContextProviderBase *ctx::place_recognition_provider::create(void *data) +ctx::ContextProviderBase *ctx::PlaceRecognitionProvider::create(void *data) { IF_FAIL_RETURN(!__instance, __instance); - __instance = new(std::nothrow) place_recognition_provider(); + __instance = new(std::nothrow) PlaceRecognitionProvider(); IF_FAIL_RETURN_TAG(__instance, NULL, _E, "Memory allocation failed"); _I(BLUE("Created")); return __instance; } -void ctx::place_recognition_provider::destroy(void *data) +void ctx::PlaceRecognitionProvider::destroy(void *data) { IF_FAIL_VOID(__instance); delete __instance; @@ -38,40 +38,42 @@ void ctx::place_recognition_provider::destroy(void *data) _I(BLUE("Destroyed")); } -int ctx::place_recognition_provider::subscribe(const char *subject, ctx::Json option, ctx::Json* requestResult) +int ctx::PlaceRecognitionProvider::subscribe(const char *subject, ctx::Json option, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } -int ctx::place_recognition_provider::unsubscribe(const char *subject, ctx::Json option) +int ctx::PlaceRecognitionProvider::unsubscribe(const char *subject, ctx::Json option) { return ERR_NOT_SUPPORTED; } -int ctx::place_recognition_provider::read(const char *subject, ctx::Json option, ctx::Json* requestResult) +int ctx::PlaceRecognitionProvider::read(const char *subject, ctx::Json option, ctx::Json* requestResult) { _I(BLUE("Read")); _J("Option", option); - std::vector> places = engine.getPlaces(); + std::vector> places = __engine.getPlaces(); Json dataRead = UserPlaces::composeJson(places); - // The below function needs to be called once. - // It does not need to be called within this read() function. - // In can be called later, in another scope. - // Please just be sure that, the 2nd input parameter "option" should be the same to the - // "option" parameter received via ctx::place_recognition_provider::read(). + /* + * The below function needs to be called once. + * It does not need to be called within this read() function. + * In can be called later, in another scope. + * Please just be sure that, the 2nd input parameter "option" should be the same to the + * "option" parameter received via ctx::PlaceRecognitionProvider::read(). + */ ctx::context_manager::replyToRead(PLACE_SUBJ_RECOGNITION, option, ERR_NONE, dataRead); return ERR_NONE; } -int ctx::place_recognition_provider::write(const char *subject, ctx::Json data, ctx::Json* requestResult) +int ctx::PlaceRecognitionProvider::write(const char *subject, ctx::Json data, ctx::Json* requestResult) { return ERR_NOT_SUPPORTED; } -bool ctx::place_recognition_provider::isSupported() +bool ctx::PlaceRecognitionProvider::isSupported() { return true; } diff --git a/src/place/recognition/place_recognition.h b/src/place/recognition/place_recognition.h index f5de60e..545c953 100644 --- a/src/place/recognition/place_recognition.h +++ b/src/place/recognition/place_recognition.h @@ -23,7 +23,7 @@ namespace ctx { - class place_recognition_provider : public ContextProviderBase { + class PlaceRecognitionProvider : public ContextProviderBase { public: static ContextProviderBase *create(void *data); @@ -36,13 +36,13 @@ namespace ctx { int write(const char *subject, ctx::Json data, ctx::Json *requestResult); private: - static place_recognition_provider *__instance; - UserPlaces engine; + static PlaceRecognitionProvider *__instance; + UserPlaces __engine; - place_recognition_provider() : engine(PLACE_RECOG_HIGH_ACCURACY_MODE) {} - ~place_recognition_provider() {} + PlaceRecognitionProvider() : __engine(PLACE_RECOG_HIGH_ACCURACY_MODE) {} + ~PlaceRecognitionProvider() {} - }; /* class place_recognition_provider */ + }; /* class PlaceRecognitionProvider */ } /* namespace ctx */ diff --git a/src/place/recognition/place_recognition_types.h b/src/place/recognition/place_recognition_types.h index 435ea4a..9576331 100644 --- a/src/place/recognition/place_recognition_types.h +++ b/src/place/recognition/place_recognition_types.h @@ -81,9 +81,9 @@ enum PlaceCategId { PLACE_CATEG_ID_OTHER = 3 }; -typedef enum { +enum PlaceRecogMode { PLACE_RECOG_HIGH_ACCURACY_MODE = 0, PLACE_RECOG_LOW_POWER_MODE = 1 -} place_recog_mode_e; +}; #endif /* End of _CONTEXT_PLACE_RECOGNITION_TYPES_ */ diff --git a/src/place/recognition/user_places/gmap.cpp b/src/place/recognition/user_places/gmap.cpp index 99b155a..845b3cf 100644 --- a/src/place/recognition/user_places/gmap.cpp +++ b/src/place/recognition/user_places/gmap.cpp @@ -18,7 +18,7 @@ #include #include -const std::string ctx::Gmap::__htmlHeader = R"( +const std::string ctx::Gmap::__HTML_HEADER = R"( @@ -42,7 +42,7 @@ function initialize() { var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); )"; -const std::string ctx::Gmap::__htmlFooter = R"( +const std::string ctx::Gmap::__HTML_FOOTER = R"( } google.maps.event.addDomListener(window, 'load', initialize); @@ -55,9 +55,9 @@ google.maps.event.addDomListener(window, 'load', initialize); )"; -std::string ctx::Gmap::__iconForCategId(PlaceCategId categ_id) +std::string ctx::Gmap::__iconForCategId(PlaceCategId categId) { - switch (categ_id) { + switch (categId) { case PLACE_CATEG_ID_HOME: return "markerH.png"; case PLACE_CATEG_ID_WORK: return "markerW.png"; case PLACE_CATEG_ID_OTHER: return "markerO.png"; @@ -68,22 +68,22 @@ std::string ctx::Gmap::__iconForCategId(PlaceCategId categ_id) void ctx::Gmap::__placeMarker2Stream(const ctx::Place& place, std::ostream& out) { - if (place.location_valid) { + if (place.locationValid) { out << "new google.maps.Marker({" << std::endl; out << " position: new google.maps.LatLng(" << place.location.latitude << "," << place.location.longitude << ")," << std::endl; out << " map: map," << std::endl; - out << " icon: \"http://maps.google.com/mapfiles/" << __iconForCategId(place.categ_id)<< "\"" << std::endl; + out << " icon: \"http://maps.google.com/mapfiles/" << __iconForCategId(place.categId)<< "\"" << std::endl; out << "});" << std::endl; } } void ctx::Gmap::__html2Stream(const std::vector>& places, std::ostream& out) { - out << __htmlHeader; + out << __HTML_HEADER; for (std::shared_ptr place : places) { __placeMarker2Stream(*place, out); } - out << __htmlFooter; + out << __HTML_FOOTER; } void ctx::Gmap::writeMap(const std::vector>& places) diff --git a/src/place/recognition/user_places/gmap.h b/src/place/recognition/user_places/gmap.h index 5d1f885..29eacd2 100644 --- a/src/place/recognition/user_places/gmap.h +++ b/src/place/recognition/user_places/gmap.h @@ -31,9 +31,9 @@ namespace ctx { class Gmap { private: - const static std::string __htmlHeader; - const static std::string __htmlFooter; - static std::string __iconForCategId(PlaceCategId categ_id); + static const std::string __HTML_HEADER; + static const std::string __HTML_FOOTER; + static std::string __iconForCategId(PlaceCategId categId); static void __placeMarker2Stream(const Place& place, std::ostream& out); static void __html2Stream(const std::vector>& places, std::ostream& out); diff --git a/src/place/recognition/user_places/graph.cpp b/src/place/recognition/user_places/graph.cpp index b8bab27..53daeb3 100644 --- a/src/place/recognition/user_places/graph.cpp +++ b/src/place/recognition/user_places/graph.cpp @@ -32,17 +32,17 @@ std::shared_ptr ctx::graph::connectedComponents(Graph &g ccs->push_back(c); fringe.insert(i); while (!fringe.empty()) { - Node curr_node = *fringe.begin(); + Node currNode = *fringe.begin(); fringe.erase(fringe.begin()); - c->insert(curr_node); + c->insert(currNode); - std::shared_ptr curr_nhood = graph[curr_node]; - for (Node nhood_node : *curr_nhood) { - if (graph[nhood_node] && fringe.find(nhood_node) == fringe.end()) { - fringe.insert(nhood_node); + std::shared_ptr currNhood = graph[currNode]; + for (Node nhoodNode : *currNhood) { + if (graph[nhoodNode] && fringe.find(nhoodNode) == fringe.end()) { + fringe.insert(nhoodNode); } } - graph[curr_node].reset(); // removing current node + graph[currNode].reset(); // removing current node } } return ccs; diff --git a/src/place/recognition/user_places/location_logger.cpp b/src/place/recognition/user_places/location_logger.cpp index 47b5e37..ed9ea6f 100644 --- a/src/place/recognition/user_places/location_logger.cpp +++ b/src/place/recognition/user_places/location_logger.cpp @@ -24,7 +24,7 @@ #include "debug_utils.h" #ifdef TIZEN_ENGINEER_MODE -#define LOCATION_CREATE_TABLE_COLUMNS \ +#define __LOCATION_CREATE_TABLE_COLUMNS \ LOCATION_COLUMN_LATITUDE " REAL NOT NULL, "\ LOCATION_COLUMN_LONGITUDE " REAL NOT NULL, "\ LOCATION_COLUMN_ACCURACY " REAL, "\ @@ -32,14 +32,14 @@ LOCATION_COLUMN_TIMESTAMP_HUMAN " TEXT, "\ LOCATION_COLUMN_METHOD " INTEGER " #else /* TIZEN_ENGINEER_MODE */ -#define LOCATION_CREATE_TABLE_COLUMNS \ +#define __LOCATION_CREATE_TABLE_COLUMNS \ LOCATION_COLUMN_LATITUDE " REAL NOT NULL, "\ LOCATION_COLUMN_LONGITUDE " REAL NOT NULL, "\ LOCATION_COLUMN_ACCURACY " REAL, "\ LOCATION_COLUMN_TIMESTAMP " timestamp NOT NULL " #endif /* TIZEN_ENGINEER_MODE */ -#define _LOCATION_ERROR_LOG(error) { \ +#define __LOCATION_ERROR_LOG(error) { \ if (error != LOCATIONS_ERROR_NONE) { \ _E("ERROR == %s", __locationError2Str(error)); \ } else { \ @@ -47,9 +47,9 @@ } \ } -void ctx::LocationLogger::__locationServiceStateChangedCb(location_service_state_e state, void *user_data) +void ctx::LocationLogger::__locationServiceStateChangedCb(location_service_state_e state, void *userData) { - ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)user_data; + ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)userData; locationLogger->__locationServiceState = state; if (state == LOCATIONS_SERVICE_ENABLED) { _D("LOCATIONS_SERVICE_ENABLED"); @@ -73,9 +73,9 @@ void ctx::LocationLogger::__locationServiceStateChangedCb(location_service_state } } -void ctx::LocationLogger::__locationSettingChangedCb(location_method_e method, bool enable, void *user_data) +void ctx::LocationLogger::__locationSettingChangedCb(location_method_e method, bool enable, void *userData) { - ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)user_data; + ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)userData; locationLogger->__locationMethodState = enable; if (method == locationLogger->__locationMethod) { if (enable) { @@ -106,10 +106,10 @@ void ctx::LocationLogger::__locationSettingChangedCb(location_method_e method, b } void ctx::LocationLogger::__positionUpdatedCb(double latitude, double longitude, - double altitude, time_t timestamp, void *user_data) + double altitude, time_t timestamp, void *userData) { _D(""); - ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)user_data; + ctx::LocationLogger* locationLogger = (ctx::LocationLogger *)userData; double horizontal = locationLogger->__locationManagerGetHorizontalAccuracy(); #ifdef TIZEN_ENGINEER_MODE ctx::LocationEvent location(latitude, longitude, horizontal, timestamp, LOCATION_METHOD_REQUEST); @@ -121,10 +121,10 @@ void ctx::LocationLogger::__positionUpdatedCb(double latitude, double longitude, } void ctx::LocationLogger::__locationUpdatedCb(location_error_e error, double latitude, double longitude, - double altitude, time_t timestamp, double speed, double direction, double climb, void *user_data) + double altitude, time_t timestamp, double speed, double direction, double climb, void *userData) { _D(""); - __positionUpdatedCb(latitude, longitude, altitude, timestamp, user_data); + __positionUpdatedCb(latitude, longitude, altitude, timestamp, userData); } const char* ctx::LocationLogger::__locationError2Str(int error) @@ -175,26 +175,26 @@ void ctx::LocationLogger::__log(location_accessibility_state_e state) int ctx::LocationLogger::__dbCreateTable() { - bool ret = db_manager::create_table(0, LOCATION_TABLE_NAME, LOCATION_CREATE_TABLE_COLUMNS, NULL, NULL); + bool ret = db_manager::create_table(0, LOCATION_TABLE_NAME, __LOCATION_CREATE_TABLE_COLUMNS, NULL, NULL); _D("%s -> Table Creation Request", ret ? "SUCCESS" : "FAIL"); return 0; } -int ctx::LocationLogger::__dbInsertLog(LocationEvent location_event) +int ctx::LocationLogger::__dbInsertLog(LocationEvent locationEvent) { Json data; - data.set(NULL, LOCATION_COLUMN_LATITUDE, location_event.coordinates.latitude); - data.set(NULL, LOCATION_COLUMN_LONGITUDE, location_event.coordinates.longitude); - data.set(NULL, LOCATION_COLUMN_ACCURACY, location_event.coordinates.accuracy); - data.set(NULL, LOCATION_COLUMN_TIMESTAMP, static_cast(location_event.timestamp)); + data.set(NULL, LOCATION_COLUMN_LATITUDE, locationEvent.coordinates.latitude); + data.set(NULL, LOCATION_COLUMN_LONGITUDE, locationEvent.coordinates.longitude); + data.set(NULL, LOCATION_COLUMN_ACCURACY, locationEvent.coordinates.accuracy); + data.set(NULL, LOCATION_COLUMN_TIMESTAMP, static_cast(locationEvent.timestamp)); #ifdef TIZEN_ENGINEER_MODE - std::string time_human = DebugUtils::humanReadableDateTime(location_event.timestamp, "%F %T", 80); - data.set(NULL, LOCATION_COLUMN_TIMESTAMP_HUMAN, time_human); - data.set(NULL, LOCATION_COLUMN_METHOD, static_cast(location_event.method)); + std::string timeHuman = DebugUtils::humanReadableDateTime(locationEvent.timestamp, "%F %T", 80); + data.set(NULL, LOCATION_COLUMN_TIMESTAMP_HUMAN, timeHuman); + data.set(NULL, LOCATION_COLUMN_METHOD, static_cast(locationEvent.method)); #endif /* TIZEN_ENGINEER_MODE */ - int64_t row_id; - bool ret = db_manager::insert_sync(LOCATION_TABLE_NAME, data, &row_id); + int64_t rowId; + bool ret = db_manager::insert_sync(LOCATION_TABLE_NAME, data, &rowId); _D("%s -> DB: location table insert result", ret ? "SUCCESS" : "FAIL"); return ret; } @@ -243,46 +243,46 @@ ctx::LocationLogger::~LocationLogger() void ctx::LocationLogger::__locationManagerCreate() { int ret = location_manager_create(__locationMethod, &__locationManager); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); } void ctx::LocationLogger::__locationManagerDestroy() { int ret = location_manager_destroy(__locationManager); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); } void ctx::LocationLogger::__locationManagerSetServiceStateChangedCb() { int ret = location_manager_set_service_state_changed_cb(__locationManager, __locationServiceStateChangedCb, this); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); } void ctx::LocationLogger::__locationManagerUnsetServiceStateChangedCb() { int ret = location_manager_unset_service_state_changed_cb(__locationManager); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); } void ctx::LocationLogger::__locationManagerStart() { int ret = location_manager_start(__locationManager); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); __startServiceTimerStart(); } void ctx::LocationLogger::__locationManagerStop() { int ret = location_manager_stop(__locationManager); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); } double ctx::LocationLogger::__locationManagerGetHorizontalAccuracy() { - location_accuracy_level_e accuracy_level; + location_accuracy_level_e accuracyLevel; double horizontal, vertical; - int ret = location_manager_get_accuracy(__locationManager, &accuracy_level, &horizontal, &vertical); - _LOCATION_ERROR_LOG(ret); + int ret = location_manager_get_accuracy(__locationManager, &accuracyLevel, &horizontal, &vertical); + __LOCATION_ERROR_LOG(ret); return horizontal; } @@ -290,20 +290,20 @@ location_accessibility_state_e ctx::LocationLogger::__locationManagerGetAccessib { location_accessibility_state_e state; int ret = location_manager_get_accessibility_state(&state); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); return state; } void ctx::LocationLogger::__locationManagerSetSettingChangedCb() { int ret = location_manager_set_setting_changed_cb(__locationMethod, __locationSettingChangedCb, this); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); } void ctx::LocationLogger::__locationManagerUnsetSettingChangedCb() { int ret = location_manager_unset_setting_changed_cb(__locationMethod); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); } bool ctx::LocationLogger::__locationManagerRequestSingleLocation() @@ -321,7 +321,7 @@ bool ctx::LocationLogger::__locationManagerRequestSingleLocation() LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS, __locationCount, LOCATION_LOGGER_MAX_LOCATION_COUNT); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); __activeRequestAttempts++; __activeAttempts++; __allAttempts++; @@ -350,7 +350,7 @@ bool ctx::LocationLogger::__locationManagerGetLocation() LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS, __locationCount, LOCATION_LOGGER_MAX_LOCATION_COUNT); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); __activeAttempts++; __allAttempts++; if (ret == LOCATIONS_ERROR_NONE) { @@ -384,7 +384,7 @@ void ctx::LocationLogger::__locationManagerGetLastLocation() LOCATION_LOGGER_MAX_LOCATION_ATTEMPTS, __locationCount, LOCATION_LOGGER_MAX_LOCATION_COUNT); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); __allAttempts++; if (ret == LOCATIONS_ERROR_NONE) { #ifdef TIZEN_ENGINEER_MODE @@ -400,7 +400,7 @@ bool ctx::LocationLogger::__locationManagerIsEnabledMethod(location_method_e met { bool enable; int ret = location_manager_is_enabled_method(method, &enable); - _LOCATION_ERROR_LOG(ret); + __LOCATION_ERROR_LOG(ret); return enable; } @@ -425,19 +425,19 @@ bool ctx::LocationLogger::__checkActiveRequestLimits() void ctx::LocationLogger::__locationRequest() { _D(""); - bool request_single_location_ret = false; - bool get_location_ret = false; + bool requestSingleLocationRet = false; + bool getLocationRet = false; if (__checkGeneralLimits() && __checkActiveLimits() && __checkActiveRequestLimits()) { - request_single_location_ret = __locationManagerRequestSingleLocation(); + requestSingleLocationRet = __locationManagerRequestSingleLocation(); } - if (__checkGeneralLimits() && __checkActiveLimits() && !request_single_location_ret) { - get_location_ret = __locationManagerGetLocation(); + if (__checkGeneralLimits() && __checkActiveLimits() && !requestSingleLocationRet) { + getLocationRet = __locationManagerGetLocation(); } - if (__checkGeneralLimits() && !request_single_location_ret && !get_location_ret + if (__checkGeneralLimits() && !requestSingleLocationRet && !getLocationRet && __activeAttempts >= LOCATION_LOGGER_MAX_ACTIVE_LOCATION_ATTEMPTS) { __locationManagerGetLastLocation(); } - if (!request_single_location_ret) { + if (!requestSingleLocationRet) { __locationManagerStop(); __setNextTimer(); } @@ -477,15 +477,15 @@ void ctx::LocationLogger::__onActiveLocationSucceeded() __activeLocationSucceeded = true; } -void ctx::LocationLogger::__broadcast(ctx::LocationEvent location_event) +void ctx::LocationLogger::__broadcast(ctx::LocationEvent locationEvent) { _D(""); __locationCount++; if (__listener) { - __listener->onNewLocation(location_event); + __listener->onNewLocation(locationEvent); } if (LOCATION_LOGGER_DATABASE) { - __dbInsertLog(location_event); + __dbInsertLog(locationEvent); } } @@ -612,4 +612,4 @@ void ctx::LocationLogger::onVisitEnd() } } -#undef _LOCATION_ERROR_LOG +#undef __LOCATION_ERROR_LOG diff --git a/src/place/recognition/user_places/location_logger.h b/src/place/recognition/user_places/location_logger.h index caa1f21..ae4c9bd 100644 --- a/src/place/recognition/user_places/location_logger.h +++ b/src/place/recognition/user_places/location_logger.h @@ -65,8 +65,7 @@ namespace ctx { class LocationLogger : public ITimerListener, public IVisitListener { public: - LocationLogger(ILocationListener *listener = nullptr, - bool testMode = false); + LocationLogger(ILocationListener *listener = nullptr, bool testMode = false); ~LocationLogger(); private: @@ -76,7 +75,7 @@ namespace ctx { /* OUTPUT */ ILocationListener * const __listener; - void __broadcast(LocationEvent location_event); + void __broadcast(LocationEvent locationEvent); /* INTERNAL */ bool __testMode; @@ -115,7 +114,7 @@ namespace ctx { /* DATABASE */ static int __dbCreateTable(); - int __dbInsertLog(LocationEvent location_event); + int __dbInsertLog(LocationEvent locationEvent); /* DEBUG */ static const char* __locationError2Str(int error); @@ -131,7 +130,7 @@ namespace ctx { /* LOCATION MANAGER : LOCATION SERVICE STATE */ location_service_state_e __locationServiceState; - static void __locationServiceStateChangedCb(location_service_state_e state, void *user_data); + static void __locationServiceStateChangedCb(location_service_state_e state, void *userData); void __locationManagerSetServiceStateChangedCb(); void __locationManagerUnsetServiceStateChangedCb(); @@ -139,7 +138,7 @@ namespace ctx { location_method_e __locationMethod; bool __locationMethodState; bool __locationManagerIsEnabledMethod(location_method_e method); - static void __locationSettingChangedCb(location_method_e method, bool enable, void *user_data); + static void __locationSettingChangedCb(location_method_e method, bool enable, void *userData); void __locationManagerSetSettingChangedCb(); void __locationManagerUnsetSettingChangedCb(); @@ -152,10 +151,10 @@ namespace ctx { /* LOCATION MANAGER : LOCATION : ASYNCHRONOUS */ static void __positionUpdatedCb(double latitude, double longitude, - double altitude, time_t timestamp, void *user_data); + double altitude, time_t timestamp, void *userData); static void __locationUpdatedCb(location_error_e error, double latitude, double longitude, double altitude, time_t timestamp, double speed, - double direction, double climb, void *user_data); + double direction, double climb, void *userData); bool __locationManagerRequestSingleLocation(); }; /* class LocationLogger */ diff --git a/src/place/recognition/user_places/mahal.cpp b/src/place/recognition/user_places/mahal.cpp index f1bdae8..cd7ff78 100644 --- a/src/place/recognition/user_places/mahal.cpp +++ b/src/place/recognition/user_places/mahal.cpp @@ -18,7 +18,7 @@ #include #include -ctx::num_t ctx::MahalModel::dist_s(const std::vector &v1, const std::vector &v2, const std::vector &m) +ctx::num_t ctx::MahalModel::distance(const std::vector &v1, const std::vector &v2, const std::vector &m) { size_t n = v1.size(); if (m.size() != n * n) { @@ -40,7 +40,7 @@ ctx::num_t ctx::MahalModel::dist_s(const std::vector &v1, const std::vect return sqrt(dist2); } -ctx::num_t ctx::MahalModel::dist(const std::vector &v) +ctx::num_t ctx::MahalModel::distance(const std::vector &v) { - return dist_s(v, __mean, __sigma); + return distance(v, __mean, __sigma); } diff --git a/src/place/recognition/user_places/mahal.h b/src/place/recognition/user_places/mahal.h index 34093f2..9e733c7 100644 --- a/src/place/recognition/user_places/mahal.h +++ b/src/place/recognition/user_places/mahal.h @@ -32,11 +32,11 @@ namespace ctx { std::vector __sigma; // represents square matrix row-wise public: - static num_t dist_s(const std::vector &v1, const std::vector &v2, const std::vector &m); + static num_t distance(const std::vector &v1, const std::vector &v2, const std::vector &m); MahalModel(std::vector mean, std::vector sigma) : __mean(mean), __sigma(sigma) { } - num_t dist(const std::vector &v); + num_t distance(const std::vector &v); }; /* class MahalModel */ diff --git a/src/place/recognition/user_places/place_categer.cpp b/src/place/recognition/user_places/place_categer.cpp index 685f138..f71fe2c 100644 --- a/src/place/recognition/user_places/place_categer.cpp +++ b/src/place/recognition/user_places/place_categer.cpp @@ -22,74 +22,74 @@ #include #include -void ctx::PlaceCateger::reduceOutliers(ctx::visits_t &visits) +void ctx::PlaceCateger::reduceOutliers(ctx::Visits &visits) { int size = visits.size(); visits.erase(std::remove_if( visits.begin(), visits.end(), - [](Visit v) { + [](Visit v)->bool { return v.categs[PLACE_CATEG_ID_HOME] < PLACES_CATEGER_MIN_VISITS_SCORE && v.categs[PLACE_CATEG_ID_WORK] < PLACES_CATEGER_MIN_VISITS_SCORE && v.categs[PLACE_CATEG_ID_OTHER] < PLACES_CATEGER_MIN_VISITS_SCORE; }), visits.end()); - int new_size = visits.size(); - if (size != new_size) { - _D("Visits number from %d to %d (visits min scores checking)", size, new_size); + int newSize = visits.size(); + if (size != newSize) { + _D("Visits number from %d to %d (visits min scores checking)", size, newSize); } } /* * Change category if home or work has to few visits */ -bool ctx::PlaceCateger::__reduceCategory(const PlaceCategId &categ, const ctx::visits_t &visits) +bool ctx::PlaceCateger::__reduceCategory(const PlaceCategId &categId, const ctx::Visits &visits) { - return (categ == PLACE_CATEG_ID_HOME && visits.size() < PLACES_CATEGER_MIN_VISITS_PER_HOME) - || (categ == PLACE_CATEG_ID_WORK && visits.size() < PLACES_CATEGER_MIN_VISITS_PER_WORK); + return (categId == PLACE_CATEG_ID_HOME && visits.size() < PLACES_CATEGER_MIN_VISITS_PER_HOME) + || (categId == PLACE_CATEG_ID_WORK && visits.size() < PLACES_CATEGER_MIN_VISITS_PER_WORK); } -void ctx::PlaceCateger::categorize(ctx::visits_t &visits, ctx::Place &place) +void ctx::PlaceCateger::categorize(ctx::Visits &visits, ctx::Place &place) { reduceOutliers(visits); - place.categ_id = PLACE_CATEG_ID_NONE; - place.categ_confidence = 0.0; + place.categId = PLACE_CATEG_ID_NONE; + place.categConfidence = 0.0; if (!visits.empty()) { - const std::vector categ_ids = { + const std::vector categIds = { PLACE_CATEG_ID_HOME, PLACE_CATEG_ID_WORK, PLACE_CATEG_ID_OTHER }; - num_t sum_score = 0.0; - num_t max_score = 0.0; - for (PlaceCategId categ_id : categ_ids) { - std::vector categ_vector = categVectorFromVisits(visits, categ_id); - num_t score = median(categ_vector); - sum_score += score; - if (score > max_score) { - max_score = score; - place.categ_id = categ_id; + num_t sumScore = 0.0; + num_t maxScore = 0.0; + for (PlaceCategId categId : categIds) { + std::vector categVector = categVectorFromVisits(visits, categId); + num_t score = median(categVector); + sumScore += score; + if (score > maxScore) { + maxScore = score; + place.categId = categId; } } - if (sum_score > 0) { - place.categ_confidence = max_score / sum_score; + if (sumScore > 0) { + place.categConfidence = maxScore / sumScore; } - if (__reduceCategory(place.categ_id, visits)) { - place.categ_id = PLACE_CATEG_ID_OTHER; - place.categ_confidence = 0.0; + if (__reduceCategory(place.categId, visits)) { + place.categId = PLACE_CATEG_ID_OTHER; + place.categConfidence = 0.0; } } - place.name = categId2Name(place.categ_id); + place.name = categId2Name(place.categId); } -std::vector ctx::PlaceCateger::categVectorFromVisits(const ctx::visits_t &visits, PlaceCategId categ_id) +std::vector ctx::PlaceCateger::categVectorFromVisits(const ctx::Visits &visits, PlaceCategId categId) { std::vector vec; for (auto &visit : visits) { - auto search = visit.categs.find(categ_id); + auto search = visit.categs.find(categId); if (search != visit.categs.end()) { vec.push_back(search->second); } @@ -97,12 +97,17 @@ std::vector ctx::PlaceCateger::categVectorFromVisits(const ctx::visi return vec; } -std::string ctx::PlaceCateger::categId2Name(PlaceCategId categ_id) { - switch (categ_id) { - case PLACE_CATEG_ID_HOME: return "home"; - case PLACE_CATEG_ID_WORK: return "work"; - case PLACE_CATEG_ID_OTHER: return "other"; - case PLACE_CATEG_ID_NONE: return "none"; - default: return ""; +std::string ctx::PlaceCateger::categId2Name(PlaceCategId categId) { + switch (categId) { + case PLACE_CATEG_ID_HOME: + return "home"; + case PLACE_CATEG_ID_WORK: + return "work"; + case PLACE_CATEG_ID_OTHER: + return "other"; + case PLACE_CATEG_ID_NONE: + return "none"; + default: + return ""; } } diff --git a/src/place/recognition/user_places/place_categer.h b/src/place/recognition/user_places/place_categer.h index 05612f3..0d127b1 100644 --- a/src/place/recognition/user_places/place_categer.h +++ b/src/place/recognition/user_places/place_categer.h @@ -28,13 +28,13 @@ namespace ctx { class PlaceCateger { private: - static bool __reduceCategory(const PlaceCategId &categ, const ctx::visits_t &visits); + static bool __reduceCategory(const PlaceCategId &categId, const ctx::Visits &visits); public: - static void reduceOutliers(visits_t &visits); // TODO: move to private - static std::vector categVectorFromVisits(const ctx::visits_t &visits, PlaceCategId categ_id); // TODO: move to private - static void categorize(ctx::visits_t &visits, ctx::Place &place); - static std::string categId2Name(PlaceCategId categ_id); // TODO: move to private + static void reduceOutliers(Visits &visits); // TODO: move to private + static std::vector categVectorFromVisits(const ctx::Visits &visits, PlaceCategId categId); // TODO: move to private + static void categorize(ctx::Visits &visits, ctx::Place &place); + static std::string categId2Name(PlaceCategId categId); // TODO: move to private }; /* class PlaceCateger */ diff --git a/src/place/recognition/user_places/places_detector.cpp b/src/place/recognition/user_places/places_detector.cpp index 40faf67..88281cf 100644 --- a/src/place/recognition/user_places/places_detector.cpp +++ b/src/place/recognition/user_places/places_detector.cpp @@ -31,13 +31,13 @@ #include #include "user_places_params.h" -#define DELETE_PLACES_QUERY "DELETE FROM " PLACE_TABLE +#define __DELETE_PLACES_QUERY "DELETE FROM " PLACE_TABLE #ifdef TIZEN_ENGINEER_MODE -#define USER_PLACES_FILE "/opt/usr/media/Others/user_places.txt" // TODO: Only for debug purposes -> Remove in final solution +#define __USER_PLACES_FILE "/opt/usr/media/Others/user_places.txt" // TODO: Only for debug purposes -> Remove in final solution #endif /* TIZEN_ENGINEER_MODE */ -#define GET_VISITS_QUERY "SELECT "\ +#define __GET_VISITS_QUERY "SELECT "\ VISIT_COLUMN_END_TIME ", "\ VISIT_COLUMN_START_TIME ", "\ VISIT_COLUMN_WIFI_APS ", "\ @@ -49,7 +49,7 @@ VISIT_COLUMN_CATEG_OTHER \ " FROM " VISIT_TABLE -#define GET_PLACES_QUERY "SELECT "\ +#define __GET_PLACES_QUERY "SELECT "\ PLACE_COLUMN_CATEG_ID ", "\ PLACE_COLUMN_CATEG_CONFIDENCE ", "\ PLACE_COLUMN_NAME ", "\ @@ -60,7 +60,7 @@ PLACE_COLUMN_CREATE_DATE \ " FROM " PLACE_TABLE -#define PLACE_TABLE_COLUMNS \ +#define __PLACE_TABLE_COLUMNS \ PLACE_COLUMN_CATEG_ID " INTEGER, "\ PLACE_COLUMN_CATEG_CONFIDENCE " REAL, "\ PLACE_COLUMN_NAME " TEXT, "\ @@ -76,7 +76,7 @@ bool ctx::PlacesDetector::onTimerExpired(int timerId) __dbDeletePlaces(); __dbDeleteOldVisits(); std::vector records = __dbGetVisits(); - visits_t visits = __visitsFromJsons(records); + Visits visits = __visitsFromJsons(records); __processVisits(visits); return true; } @@ -84,7 +84,7 @@ bool ctx::PlacesDetector::onTimerExpired(int timerId) std::vector ctx::PlacesDetector::__dbGetVisits() { std::vector records; - bool ret = db_manager::execute_sync(GET_VISITS_QUERY, &records); + bool ret = db_manager::execute_sync(__GET_VISITS_QUERY, &records); _D("load visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); return records; } @@ -92,7 +92,7 @@ std::vector ctx::PlacesDetector::__dbGetVisits() std::vector ctx::PlacesDetector::__dbGetPlaces() { std::vector records; - bool ret = db_manager::execute_sync(GET_PLACES_QUERY, &records); + bool ret = db_manager::execute_sync(__GET_PLACES_QUERY, &records); _D("load places execute query result: %s", ret ? "SUCCESS" : "FAIL"); return records; } @@ -105,9 +105,9 @@ double ctx::PlacesDetector::__doubleValueFromJson(Json &row, const char* key) return value; } -ctx::categs_t ctx::PlacesDetector::__visitCategsFromJson(Json &row) +ctx::Categs ctx::PlacesDetector::__visitCategsFromJson(Json &row) { - categs_t categs; + Categs categs; categs[PLACE_CATEG_ID_HOME] = __doubleValueFromJson(row, VISIT_COLUMN_CATEG_HOME); categs[PLACE_CATEG_ID_WORK] = __doubleValueFromJson(row, VISIT_COLUMN_CATEG_WORK); categs[PLACE_CATEG_ID_OTHER] = __doubleValueFromJson(row, VISIT_COLUMN_CATEG_OTHER); @@ -116,27 +116,27 @@ ctx::categs_t ctx::PlacesDetector::__visitCategsFromJson(Json &row) ctx::Visit ctx::PlacesDetector::__visitFromJson(Json &row) { - int start_time; - int end_time; - std::string mac_set_string; - row.get(NULL, VISIT_COLUMN_START_TIME, &start_time); - row.get(NULL, VISIT_COLUMN_END_TIME, &end_time); - row.get(NULL, VISIT_COLUMN_WIFI_APS, &mac_set_string); + int startTime; + int endTime; + std::string str; + row.get(NULL, VISIT_COLUMN_START_TIME, &startTime); + row.get(NULL, VISIT_COLUMN_END_TIME, &endTime); + row.get(NULL, VISIT_COLUMN_WIFI_APS, &str); - std::stringstream mac_set_ss; - mac_set_ss << mac_set_string; - std::shared_ptr macSet = std::make_shared(); - mac_set_ss >> *macSet; + std::stringstream ss; + ss << str; + std::shared_ptr macSet = std::make_shared(); + ss >> *macSet; - Interval interval(start_time, end_time); - categs_t categs = __visitCategsFromJson(row); + Interval interval(startTime, endTime); + Categs categs = __visitCategsFromJson(row); Visit visit(interval, macSet, categs); { // location - int location_valid_int; - row.get(NULL, VISIT_COLUMN_LOCATION_VALID, &location_valid_int); - visit.location_valid = (bool) location_valid_int; + int locationValidInt; + row.get(NULL, VISIT_COLUMN_LOCATION_VALID, &locationValidInt); + visit.locationValid = (bool) locationValidInt; row.get(NULL, VISIT_COLUMN_LOCATION_LATITUDE, &(visit.location.latitude)); row.get(NULL, VISIT_COLUMN_LOCATION_LONGITUDE, &(visit.location.longitude)); } @@ -144,9 +144,9 @@ ctx::Visit ctx::PlacesDetector::__visitFromJson(Json &row) return visit; } -ctx::visits_t ctx::PlacesDetector::__visitsFromJsons(std::vector& records) +ctx::Visits ctx::PlacesDetector::__visitsFromJsons(std::vector& records) { - visits_t visits; + Visits visits; _D("db_result: number of all visits: %d", records.size()); for (Json &row : records) { @@ -161,27 +161,27 @@ std::shared_ptr ctx::PlacesDetector::__placeFromJson(Json &row) { std::shared_ptr place = std::make_shared(); { // category - int categ_id; - row.get(NULL, PLACE_COLUMN_CATEG_ID, &categ_id); + int categId; + row.get(NULL, PLACE_COLUMN_CATEG_ID, &categId); // This is due to the fact the JSON module API interface doesn't handle enum - place->categ_id = static_cast(categ_id); + place->categId = static_cast(categId); } row.get(NULL, PLACE_COLUMN_NAME, &(place->name)); - row.get(NULL, PLACE_COLUMN_WIFI_APS, &(place->wifi_aps)); + row.get(NULL, PLACE_COLUMN_WIFI_APS, &(place->wifiAps)); { // location - int location_valid_int; - row.get(NULL, PLACE_COLUMN_LOCATION_VALID, &location_valid_int); - place->location_valid = (bool) location_valid_int; + int locationValidInt; + row.get(NULL, PLACE_COLUMN_LOCATION_VALID, &locationValidInt); + place->locationValid = (bool) locationValidInt; row.get(NULL, PLACE_COLUMN_LOCATION_LATITUDE, &(place->location.latitude)); row.get(NULL, PLACE_COLUMN_LOCATION_LONGITUDE, &(place->location.longitude)); } - { // create_date - int create_date; - row.get(NULL, PLACE_COLUMN_CREATE_DATE, &(create_date)); + { // createDate + int createDate; + row.get(NULL, PLACE_COLUMN_CREATE_DATE, &(createDate)); // This is due to the fact the JSON module API interface doesn't handle time_t - place->create_date = static_cast(create_date); + place->createDate = static_cast(createDate); } - _D("db_result: categ_id: %d; place: name: %s; wifi_aps: %s; location_valid: %d; latitude: %lf, longitude: %lf, create_date: %d", place->categ_id, place->name.c_str(), place->wifi_aps.c_str(), place->location_valid, place->location.latitude, place->location.longitude, place->create_date); + _D("db_result: categId: %d; place: name: %s; wifiAps: %s; locationValid: %d; latitude: %lf, longitude: %lf, createDate: %d", place->categId, place->name.c_str(), place->wifiAps.c_str(), place->locationValid, place->location.latitude, place->location.longitude, place->createDate); return place; } @@ -198,25 +198,25 @@ std::vector> ctx::PlacesDetector::__placesFromJsons( return places; } -void ctx::PlacesDetector::reduceOutliers(ctx::visits_t &visits) +void ctx::PlacesDetector::reduceOutliers(ctx::Visits &visits) { int size = visits.size(); visits.erase(std::remove_if( visits.begin(), visits.end(), - [](Visit v) { + [](Visit v)->bool { int minutes = (v.interval.end - v.interval.start) / 60; return (minutes < PLACES_DETECTOR_MIN_VISIT_DURATION_MINUTES) || (minutes > PLACES_DETECTOR_MAX_VISIT_DURATION_MINUTES); }), visits.end()); - int new_size = visits.size(); - if (size != new_size) { - _D("Visits number from %d to %d (to short and to long reduction)", size, new_size); + int newSize = visits.size(); + if (size != newSize) { + _D("Visits number from %d to %d (to short and to long reduction)", size, newSize); } } -void ctx::PlacesDetector::__processVisits(ctx::visits_t &visits) +void ctx::PlacesDetector::__processVisits(ctx::Visits &visits) { reduceOutliers(visits); @@ -224,7 +224,7 @@ void ctx::PlacesDetector::__processVisits(ctx::visits_t &visits) auto components = __mergeVisits(visits); std::vector> newDetectedPlaces; #ifdef TIZEN_ENGINEER_MODE - std::vector places_visits; // TODO: remove from final solution. + std::vector placesVisits; // TODO: remove from final solution. #endif /* TIZEN_ENGINEER_MODE */ for (std::shared_ptr component : *components) { // Small places outliers reduction @@ -232,12 +232,12 @@ void ctx::PlacesDetector::__processVisits(ctx::visits_t &visits) continue; } - std::shared_ptr merged = std::make_shared(); + std::shared_ptr merged = std::make_shared(); for (graph::Node i : *component) { merged->push_back(visits[i]); } std::shared_ptr place = __placeFromMergedVisits(*merged); - if (place->categ_id == PLACE_CATEG_ID_NONE) { + if (place->categId == PLACE_CATEG_ID_NONE) { continue; } newDetectedPlaces.push_back(place); @@ -247,11 +247,11 @@ void ctx::PlacesDetector::__processVisits(ctx::visits_t &visits) #ifdef TIZEN_ENGINEER_MODE { // TODO: Only for debug -> remove in final solution - visits_t place_visits; + Visits placeVisits; for (graph::Node i : *component) { - place_visits.push_back(visits[i]); + placeVisits.push_back(visits[i]); } - places_visits.push_back(place_visits); + placesVisits.push_back(placeVisits); } #endif /* TIZEN_ENGINEER_MODE */ } @@ -260,12 +260,12 @@ void ctx::PlacesDetector::__processVisits(ctx::visits_t &visits) #ifdef TIZEN_ENGINEER_MODE { // Print to file TODO: Only for debug -> remove in final solution - std::ofstream out(USER_PLACES_FILE); + std::ofstream out(__USER_PLACES_FILE); for (size_t i = 0; i < newDetectedPlaces.size(); i++) { - newDetectedPlaces[i]->print_to_stream(out); - visits_t place_visits = places_visits[i]; - for (Visit visit : place_visits) { - visit.print_short_to_stream(out); + newDetectedPlaces[i]->print2Stream(out); + Visits placeVisits = placesVisits[i]; + for (Visit visit : placeVisits) { + visit.printShort2Stream(out); } } out.close(); @@ -277,47 +277,47 @@ void ctx::PlacesDetector::__processVisits(ctx::visits_t &visits) /* * Replace old places by new ones. */ -void ctx::PlacesDetector::__detectedPlacesUpdate(std::vector> &new_places) +void ctx::PlacesDetector::__detectedPlacesUpdate(std::vector> &newPlaces) { _D(""); // XXX: In case of thread safety issues use std::mutex to protect places list. - __detectedPlaces = new_places; + __detectedPlaces = newPlaces; } -void ctx::PlacesDetector::__mergeLocation(const visits_t &visits, Place &place) +void ctx::PlacesDetector::__mergeLocation(const Visits &visits, Place &place) { - place.location_valid = false; + place.locationValid = false; std::vector latitudes; std::vector longitudes; for (const Visit& visit : visits) { - if (visit.location_valid) { + if (visit.locationValid) { latitudes.push_back(visit.location.latitude); longitudes.push_back(visit.location.longitude); - place.location_valid = true; + place.locationValid = true; } } - if (place.location_valid) { + if (place.locationValid) { place.location.latitude = median(latitudes); place.location.longitude = median(longitudes); } } -std::shared_ptr ctx::PlacesDetector::__placeFromMergedVisits(visits_t &merged_visits) +std::shared_ptr ctx::PlacesDetector::__placeFromMergedVisits(Visits &mergedVisits) { std::shared_ptr place = std::make_shared(); - place->create_date = std::time(nullptr); - std::vector> macSets; - for (const Visit &visit : merged_visits) { + place->createDate = std::time(nullptr); + std::vector> macSets; + for (const Visit &visit : mergedVisits) { macSets.push_back(visit.macSet); } - std::shared_ptr all_macs = mac_sets_union(macSets); - std::stringstream all_macs_ss; - all_macs_ss << *all_macs; - place->wifi_aps = all_macs_ss.str(); + std::shared_ptr allMacs = macSetsUnion(macSets); + std::stringstream ss; + ss << *allMacs; + place->wifiAps = ss.str(); - __mergeLocation(merged_visits, *place); + __mergeLocation(mergedVisits, *place); - PlaceCateger::categorize(merged_visits, *place); + PlaceCateger::categorize(mergedVisits, *place); return place; } @@ -327,13 +327,13 @@ void ctx::PlacesDetector::reduceOutliers(std::shared_ptr int size = cc->size(); cc->erase(std::remove_if(cc->begin(), cc->end(), - [](std::shared_ptr &c) { + [](std::shared_ptr &c)->bool { return c->size() < PLACES_DETECTOR_MIN_VISITS_PER_PLACE; }), cc->end()); - int new_size = cc->size(); - if (size != new_size) { - _D("Connected components from %d to %d (min visit per place)", size, new_size); + int newSize = cc->size(); + if (size != newSize) { + _D("Connected components from %d to %d (min visit per place)", size, newSize); } } @@ -364,16 +364,16 @@ std::shared_ptr ctx::PlacesDetector::__graphFromVisits(const void ctx::PlacesDetector::__dbDeletePlaces() { std::vector records; - bool ret = db_manager::execute_sync(DELETE_PLACES_QUERY, &records); + bool ret = db_manager::execute_sync(__DELETE_PLACES_QUERY, &records); _D("delete places execute query result: %s", ret ? "SUCCESS" : "FAIL"); } void ctx::PlacesDetector::__dbDeleteOldVisits() { - time_t current_time; - time(¤t_time); - time_t threshold_time = current_time - PLACES_DETECTOR_RETENTION_SECONDS; - __dbDeleteOlderVisitsThan(threshold_time); + time_t currentTime; + time(¤tTime); + time_t thresholdTime = currentTime - PLACES_DETECTOR_RETENTION_SECONDS; + __dbDeleteOlderVisitsThan(thresholdTime); } void ctx::PlacesDetector::__dbDeleteOlderVisitsThan(time_t threshold) @@ -396,32 +396,32 @@ ctx::PlacesDetector::PlacesDetector(bool testMode) : } __dbCreateTable(); std::vector records = __dbGetPlaces(); - std::vector> db_places = __placesFromJsons(records); - __detectedPlacesUpdate(db_places); + std::vector> dbPlaces = __placesFromJsons(records); + __detectedPlacesUpdate(dbPlaces); } void ctx::PlacesDetector::__dbCreateTable() { - bool ret = db_manager::create_table(0, PLACE_TABLE, PLACE_TABLE_COLUMNS); + bool ret = db_manager::create_table(0, PLACE_TABLE, __PLACE_TABLE_COLUMNS); _D("db: place Table Creation Result: %s", ret ? "SUCCESS" : "FAIL"); } void ctx::PlacesDetector::__dbInsertPlace(const Place &place) { Json data; - data.set(NULL, PLACE_COLUMN_CATEG_ID, place.categ_id); - data.set(NULL, PLACE_COLUMN_CATEG_CONFIDENCE, place.categ_confidence); + data.set(NULL, PLACE_COLUMN_CATEG_ID, place.categId); + data.set(NULL, PLACE_COLUMN_CATEG_CONFIDENCE, place.categConfidence); data.set(NULL, PLACE_COLUMN_NAME, place.name); - data.set(NULL, PLACE_COLUMN_LOCATION_VALID, place.location_valid); + data.set(NULL, PLACE_COLUMN_LOCATION_VALID, place.locationValid); data.set(NULL, PLACE_COLUMN_LOCATION_LATITUDE, place.location.latitude); data.set(NULL, PLACE_COLUMN_LOCATION_LONGITUDE, place.location.longitude); - data.set(NULL, PLACE_COLUMN_WIFI_APS, place.wifi_aps); - data.set(NULL, PLACE_COLUMN_CREATE_DATE, static_cast(place.create_date)); + data.set(NULL, PLACE_COLUMN_WIFI_APS, place.wifiAps); + data.set(NULL, PLACE_COLUMN_CREATE_DATE, static_cast(place.createDate)); - int64_t row_id; - bool ret = db_manager::insert_sync(PLACE_TABLE, data, &row_id); + int64_t rowId; + bool ret = db_manager::insert_sync(PLACE_TABLE, data, &rowId); _D("insert place execute query result: %s", ret ? "SUCCESS" : "FAIL"); } diff --git a/src/place/recognition/user_places/places_detector.h b/src/place/recognition/user_places/places_detector.h index 7ad43fb..510aebe 100644 --- a/src/place/recognition/user_places/places_detector.h +++ b/src/place/recognition/user_places/places_detector.h @@ -32,9 +32,9 @@ namespace ctx { bool __testMode; double __doubleValueFromJson(Json &row, const char* key); - categs_t __visitCategsFromJson(Json &row); + Categs __visitCategsFromJson(Json &row); Visit __visitFromJson(Json &row); - visits_t __visitsFromJsons(std::vector& records); + Visits __visitsFromJsons(std::vector& records); std::shared_ptr __placeFromJson(Json &row); std::vector> __placesFromJsons(std::vector& records); @@ -48,18 +48,18 @@ namespace ctx { std::vector __dbGetPlaces(); void __dbInsertPlace(const Place &place); - std::shared_ptr __placeFromMergedVisits(visits_t &merged_visits); + std::shared_ptr __placeFromMergedVisits(Visits &mergedVisits); std::vector> __detectedPlaces; - void __detectedPlacesUpdate(std::vector> &new_places); - void __processVisits(visits_t &visits); - static void __mergeLocation(const visits_t &merged_visits, Place &place); + void __detectedPlacesUpdate(std::vector> &newPlaces); + void __processVisits(Visits &visits); + static void __mergeLocation(const Visits &mergedVisits, Place &place); std::shared_ptr __mergeVisits(const std::vector &visits); bool onTimerExpired(int timerId); public: PlacesDetector(bool testMode = false); - static void reduceOutliers(visits_t &visits); // TODO: move to private + static void reduceOutliers(Visits &visits); // TODO: move to private static void reduceOutliers(std::shared_ptr &cc); // TODO: move to private std::vector> getPlaces(); diff --git a/src/place/recognition/user_places/user_places.cpp b/src/place/recognition/user_places/user_places.cpp index c61cb2a..5357fa9 100644 --- a/src/place/recognition/user_places/user_places.cpp +++ b/src/place/recognition/user_places/user_places.cpp @@ -22,7 +22,7 @@ #include "../place_recognition_types.h" #include "db_mgr.h" -ctx::UserPlaces::UserPlaces(place_recog_mode_e energyMode): +ctx::UserPlaces::UserPlaces(PlaceRecogMode energyMode): __visitDetector(nullptr), __placesDetector(nullptr), __placesDetectorTimerId(-1) @@ -114,22 +114,22 @@ ctx::Json ctx::UserPlaces::composeJson(std::vector> place { ctx::Json data; for (std::shared_ptr place : places) { - ctx::Json place_j; - place_j.set(NULL, PLACE_CATEG_ID, place->categ_id); - place_j.set(NULL, PLACE_CATEG_CONFIDENCE, place->categ_confidence); - place_j.set(NULL, PLACE_NAME, place->name); - if (place->location_valid) { - place_j.set(NULL, PLACE_GEO_LATITUDE, place->location.latitude); - place_j.set(NULL, PLACE_GEO_LONGITUDE, place->location.longitude); + ctx::Json placeJson; + placeJson.set(NULL, PLACE_CATEG_ID, place->categId); + placeJson.set(NULL, PLACE_CATEG_CONFIDENCE, place->categConfidence); + placeJson.set(NULL, PLACE_NAME, place->name); + if (place->locationValid) { + placeJson.set(NULL, PLACE_GEO_LATITUDE, place->location.latitude); + placeJson.set(NULL, PLACE_GEO_LONGITUDE, place->location.longitude); } - place_j.set(NULL, PLACE_WIFI_APS, place->wifi_aps); - place_j.set(NULL, PLACE_CREATE_DATE, static_cast(place->create_date)); - data.append(NULL, DATA_READ, place_j); + placeJson.set(NULL, PLACE_WIFI_APS, place->wifiAps); + placeJson.set(NULL, PLACE_CREATE_DATE, static_cast(place->createDate)); + data.append(NULL, DATA_READ, placeJson); } return data; } -void ctx::UserPlaces::setMode(place_recog_mode_e energyMode) +void ctx::UserPlaces::setMode(PlaceRecogMode energyMode) { if (__visitDetector) { __visitDetector->setMode(energyMode); diff --git a/src/place/recognition/user_places/user_places.h b/src/place/recognition/user_places/user_places.h index d4275cb..1df6388 100644 --- a/src/place/recognition/user_places/user_places.h +++ b/src/place/recognition/user_places/user_places.h @@ -35,10 +35,10 @@ namespace ctx { TimerManager __timerManager; public: - UserPlaces(place_recog_mode_e energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE); + UserPlaces(PlaceRecogMode energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE); ~UserPlaces(); - void setMode(place_recog_mode_e energyMode); + void setMode(PlaceRecogMode energyMode); std::vector> getPlaces(); static Json composeJson(std::vector> places); diff --git a/src/place/recognition/user_places/user_places_types.cpp b/src/place/recognition/user_places/user_places_types.cpp index 9fafbc4..7efd948 100644 --- a/src/place/recognition/user_places/user_places_types.cpp +++ b/src/place/recognition/user_places/user_places_types.cpp @@ -24,8 +24,8 @@ #include "user_places_params.h" #include "debug_utils.h" -#define MAC_STRING_COMPONENTS_SEPARATOR ':' -#define MAC_SET_STRING_DELIMITER ',' +#define __MAC_STRING_COMPONENTS_SEPARATOR ':' +#define __MAC_SET_STRING_DELIMITER ',' ctx::Mac::Mac(const std::string& str) { @@ -59,7 +59,7 @@ std::istream& ctx::operator>>(std::istream &input, ctx::Mac &mac) break; } input >> colon; - if (colon != MAC_STRING_COMPONENTS_SEPARATOR) { + if (colon != __MAC_STRING_COMPONENTS_SEPARATOR) { throw std::runtime_error("Invalid MAC format"); } } @@ -77,7 +77,7 @@ std::ostream& ctx::operator<<(std::ostream &output, const ctx::Mac &mac) if (i >= Mac::MAC_SIZE) { break; } - output << MAC_STRING_COMPONENTS_SEPARATOR; + output << __MAC_STRING_COMPONENTS_SEPARATOR; } output << std::dec; return output; @@ -121,7 +121,7 @@ bool ctx::operator<(const Mac &m1, const Mac &m2) return false; // they are equal } -std::istream& ctx::operator>>(std::istream &input, ctx::mac_set_t &macSet) +std::istream& ctx::operator>>(std::istream &input, ctx::MacSet &macSet) { Mac mac; char delimeter; @@ -137,7 +137,7 @@ std::istream& ctx::operator>>(std::istream &input, ctx::mac_set_t &macSet) break; } delimeter = input.get(); - if (delimeter != MAC_SET_STRING_DELIMITER) { + if (delimeter != __MAC_SET_STRING_DELIMITER) { input.unget(); break; } @@ -145,18 +145,18 @@ std::istream& ctx::operator>>(std::istream &input, ctx::mac_set_t &macSet) return input; } -std::ostream& ctx::operator<<(std::ostream &output, const ctx::mac_set_t &macSet) +std::ostream& ctx::operator<<(std::ostream &output, const ctx::MacSet &macSet) { - std::vector mac_vec(macSet.size()); - std::copy(macSet.begin(), macSet.end(), mac_vec.begin()); - std::sort(mac_vec.begin(), mac_vec.end()); + std::vector macVec(macSet.size()); + std::copy(macSet.begin(), macSet.end(), macVec.begin()); + std::sort(macVec.begin(), macVec.end()); bool first = true; - for (auto &mac: mac_vec) { + for (auto &mac: macVec) { if (first) { first = false; } else { - output << MAC_SET_STRING_DELIMITER; + output << __MAC_SET_STRING_DELIMITER; } output << mac; } @@ -182,13 +182,13 @@ void ctx::LocationEvent::log() #endif /* TIZEN_ENGINEER_MODE */ } -void ctx::Visit::set_location(Location location_) +void ctx::Visit::setLocation(Location location_) { - location_valid = true; + locationValid = true; location = location_; } -void ctx::Visit::print_short_to_stream(std::ostream &out) const +void ctx::Visit::printShort2Stream(std::ostream &out) const { // print only valid visits if (interval.end != 0) { @@ -207,13 +207,13 @@ bool ctx::operator==(const ctx::Visit &v1, const ctx::Visit &v2) && v1.location.latitude == v2.location.latitude && v1.location.longitude == v2.location.longitude && v1.location.accuracy == v2.location.accuracy - && v1.location_valid == v2.location_valid + && v1.locationValid == v2.locationValid && v1.macSet == v2.macSet; } -ctx::mac_set_t ctx::mac_set_from_string(const std::string &str) +ctx::MacSet ctx::macSetFromString(const std::string &str) { - mac_set_t macSet; + MacSet macSet; std::stringstream ss; ss << str; ss >> macSet; @@ -225,22 +225,22 @@ bool ctx::operator>(const Mac &m1, const Mac &m2) return m2 < m1; } -std::shared_ptr ctx::mac_set_from_mac_counts(const mac_counts_t &mac_counts) +std::shared_ptr ctx::macSetFromMacs2Counts(const Macs2Counts &macs2Counts) { - std::shared_ptr macSet(std::make_shared()); - for (auto &c: mac_counts) { - macSet->insert(c.first); + std::shared_ptr macSet(std::make_shared()); + for (auto &macCount: macs2Counts) { + macSet->insert(macCount.first); } return macSet; } -std::shared_ptr ctx::mac_sets_union(const std::vector> &macSets) +std::shared_ptr ctx::macSetsUnion(const std::vector> &macSets) { - std::shared_ptr union_set = std::make_shared(); - for (std::shared_ptr macSet : macSets) { - union_set->insert(macSet->begin(), macSet->end()); + std::shared_ptr unionSet = std::make_shared(); + for (std::shared_ptr macSet : macSets) { + unionSet->insert(macSet->begin(), macSet->end()); } - return union_set; + return unionSet; } ctx::Interval::Interval(time_t start_, time_t end_) : start(start_), end(end_) { @@ -249,14 +249,14 @@ ctx::Interval::Interval(time_t start_, time_t end_) : start(start_), end(end_) { } } -void ctx::Place::print_to_stream(std::ostream &out) const +void ctx::Place::print2Stream(std::ostream &out) const { out << "PLACE:" << std::endl; out << "__CATEGORY: " << name << std::endl; - if (location_valid) { + if (locationValid) { out << "__LOCATION: lat=" << std::setprecision(GEO_LOCATION_PRECISION + 2) << location.latitude; out << ", lon=" << location.longitude << std::setprecision(5) << std::endl; } - out << "__WIFI:" << wifi_aps << std::endl; - out << "__CREATE_DATE: " << DebugUtils::humanReadableDateTime(create_date, "%F %T", 80) << std::endl; + out << "__WIFI:" << wifiAps << std::endl; + out << "__CREATE_DATE: " << DebugUtils::humanReadableDateTime(createDate, "%F %T", 80) << std::endl; } diff --git a/src/place/recognition/user_places/user_places_types.h b/src/place/recognition/user_places/user_places_types.h index a19c015..cdf7be4 100644 --- a/src/place/recognition/user_places/user_places_types.h +++ b/src/place/recognition/user_places/user_places_types.h @@ -78,22 +78,22 @@ namespace ctx { typedef float share_t; typedef int count_t; - typedef std::unordered_map mac_counts_t; - typedef std::unordered_map mac_shares_t; + typedef std::unordered_map Macs2Counts; + typedef std::unordered_map Macs2Shares; - typedef std::unordered_set mac_set_t; + typedef std::unordered_set MacSet; - std::istream &operator>>(std::istream &input, ctx::mac_set_t &macSet); - std::ostream &operator<<(std::ostream &output, const ctx::mac_set_t &macSet); - ctx::mac_set_t mac_set_from_string(const std::string &str); + std::istream &operator>>(std::istream &input, ctx::MacSet &macSet); + std::ostream &operator<<(std::ostream &output, const ctx::MacSet &macSet); + ctx::MacSet macSetFromString(const std::string &str); - std::shared_ptr mac_sets_union(const std::vector> &macSets); + std::shared_ptr macSetsUnion(const std::vector> &macSets); struct Interval { time_t start; time_t end; - Interval(time_t start_, time_t end_); + Interval(time_t start, time_t end); }; } /* namespace ctx */ @@ -116,7 +116,7 @@ namespace ctx { struct Frame { Interval interval; count_t numberOfTimestamps; - mac_counts_t macCountsMap; + Macs2Counts macs2Counts; Frame(Interval interval_) : interval(interval_), numberOfTimestamps(0) {}; }; @@ -131,7 +131,7 @@ namespace ctx { MacEvent(time_t timestamp_, Mac mac_) : timestamp(timestamp_), mac(mac_) {} }; - typedef std::map categs_t; // scores of categories + typedef std::map Categs; // scores of categories struct Location { double latitude; @@ -161,11 +161,13 @@ namespace ctx { #ifdef TIZEN_ENGINEER_MODE LocationSource method; - LocationEvent(double latitude_, double longitude_, double accuracy_, time_t timestamp_, LocationSource method_) - : coordinates(latitude_, longitude_, accuracy_), timestamp(timestamp_), method(method_) {} + LocationEvent(double latitude_, double longitude_, double accuracy_, time_t timestamp_, LocationSource method_) : + coordinates(latitude_, longitude_, accuracy_), + timestamp(timestamp_), method(method_) {} #else /* TIZEN_ENGINEER_MODE */ - LocationEvent(double latitude_, double longitude_, double accuracy_, time_t timestamp_) - : coordinates(latitude_, longitude_, accuracy_), timestamp(timestamp_) {} + LocationEvent(double latitude_, double longitude_, double accuracy_, time_t timestamp_) : + coordinates(latitude_, longitude_, accuracy_), + timestamp(timestamp_) {} #endif /* TIZEN_ENGINEER_MODE */ void log(); @@ -174,41 +176,41 @@ namespace ctx { struct Visit { Interval interval; - std::shared_ptr macSet; - categs_t categs; - bool location_valid; - Location location; // makes sense if location_valid == true; + std::shared_ptr macSet; + Categs categs; + bool locationValid; + Location location; // makes sense if locationValid == true; - Visit(Interval interval_, std::shared_ptr macSet_ = std::make_shared(), categs_t categs_ = categs_t()) : + Visit(Interval interval_, std::shared_ptr macSet_ = std::make_shared(), Categs categs_ = Categs()) : interval(interval_), macSet(macSet_), categs(categs_), - location_valid(false) {} - void set_location(Location location); - void print_short_to_stream(std::ostream &out) const; + locationValid(false) {} + void setLocation(Location location); + void printShort2Stream(std::ostream &out) const; }; /* struct Visit */ bool operator==(const Visit &v1, const Visit &v2); - typedef std::vector visits_t; - typedef std::vector mac_events; // used to store current interval logs + typedef std::vector Visits; + typedef std::vector MacEvents; // used to store current interval logs - std::shared_ptr mac_set_from_mac_counts(const mac_counts_t &macCountsMap); + std::shared_ptr macSetFromMacs2Counts(const Macs2Counts &macs2Counts); typedef float confidence_t; class Place { public: - PlaceCategId categ_id; // category of a place (work/home/other) - confidence_t categ_confidence; // confidence of the above category - between [0,1] + PlaceCategId categId; // category of a place (work/home/other) + confidence_t categConfidence; // confidence of the above category - between [0,1] std::string name; // for now: "work"/"home"/"other" - bool location_valid; - Location location; // makes sense if location_valid == true; - std::string wifi_aps; // WiFi APs MAC addresses separated by "," - time_t create_date; // The last update time of this place + bool locationValid; + Location location; // makes sense if locationValid == true; + std::string wifiAps; // WiFi APs MAC addresses separated by "," + time_t createDate; // The last update time of this place - void print_to_stream(std::ostream &out) const; + void print2Stream(std::ostream &out) const; }; /* class Place */ diff --git a/src/place/recognition/user_places/visit_categer.cpp b/src/place/recognition/user_places/visit_categer.cpp index c09dd01..7c6ab7d 100644 --- a/src/place/recognition/user_places/visit_categer.cpp +++ b/src/place/recognition/user_places/visit_categer.cpp @@ -314,12 +314,12 @@ ctx::TimeFeatures ctx::VisitCateger::timeFeatures(const time_t &time) }; } -int ctx::VisitCateger::weeksScope(const TimeFeatures &start_f, const Interval &interval) +int ctx::VisitCateger::weeksScope(const TimeFeatures &startF, const Interval &interval) { - int duration_minutes = (interval.end - interval.start) / 60; - int scope_minutes = start_f.minutesSinceBeginingOfTheWeek + duration_minutes; - int weeksScope = scope_minutes / MINUTES_IN_WEEK; - if (scope_minutes % MINUTES_IN_WEEK > 0) { + int durationMinutes = (interval.end - interval.start) / 60; + int scopeMinutes = startF.minutesSinceBeginingOfTheWeek + durationMinutes; + int weeksScope = scopeMinutes / __MINUTES_IN_WEEK; + if (scopeMinutes % __MINUTES_IN_WEEK > 0) { weeksScope++; } return weeksScope; @@ -327,10 +327,10 @@ int ctx::VisitCateger::weeksScope(const TimeFeatures &start_f, const Interval &i ctx::num_t ctx::VisitCateger::__sum(const std::vector model, const size_t &from, const size_t &to) { - size_t to_secure = to; + size_t toSecure = to; if (to >= model.size()) { _E("'to' exceeds model size"); - to_secure = model.size() - 1; + toSecure = model.size() - 1; } if (from > to) { @@ -338,7 +338,7 @@ ctx::num_t ctx::VisitCateger::__sum(const std::vector model, const size_t } num_t result = 0.0; - for (size_t i = from; i <= to_secure; i++) { + for (size_t i = from; i <= toSecure; i++) { result += model[i]; } @@ -346,20 +346,20 @@ ctx::num_t ctx::VisitCateger::__sum(const std::vector model, const size_t } ctx::num_t ctx::VisitCateger::__weekModelMeanValue(PlaceCategId categ, const Interval &interval, - const TimeFeatures &start_f, const TimeFeatures &end_f) + const TimeFeatures &startF, const TimeFeatures &endF) { num_t ret = 0.0; int minutes = 0; - int ws = weeksScope(start_f, interval); + int ws = weeksScope(startF, interval); for (int week = 1; week <= ws; week++) { - size_t start_index = (week == 1) - ? start_f.minutesSinceBeginingOfTheWeek + size_t startIndex = (week == 1) + ? startF.minutesSinceBeginingOfTheWeek : 0; - size_t end_index = (week == ws) - ? end_f.minutesSinceBeginingOfTheWeek - : MINUTES_IN_WEEK - 1; - ret += __sum(prob_features::weekModel[categ], start_index, end_index); - minutes += end_index - start_index + 1; + size_t endIndex = (week == ws) + ? endF.minutesSinceBeginingOfTheWeek + : __MINUTES_IN_WEEK - 1; + ret += __sum(prob_features::weekModel[categ], startIndex, endIndex); + minutes += endIndex - startIndex + 1; } if (minutes > 0) { return ret / minutes; @@ -367,12 +367,11 @@ ctx::num_t ctx::VisitCateger::__weekModelMeanValue(PlaceCategId categ, const Int return ret; } -ctx::categs_t ctx::VisitCateger::weekModelFeatures(const Interval &interval, const TimeFeatures &start_f, - const TimeFeatures &end_f) +ctx::Categs ctx::VisitCateger::weekModelFeatures(const Interval &interval, const TimeFeatures &startF, const TimeFeatures &endF) { - ctx::categs_t categs; + ctx::Categs categs; for (const auto &item : prob_features::weekModel) { - categs[item.first] = __weekModelMeanValue(item.first, interval, start_f, end_f); + categs[item.first] = __weekModelMeanValue(item.first, interval, startF, endF); } _D("categs: H=%.12f, W=%.12f, O=%.12f", categs[PLACE_CATEG_ID_HOME], @@ -381,20 +380,20 @@ ctx::categs_t ctx::VisitCateger::weekModelFeatures(const Interval &interval, con return categs; } -std::vector ctx::VisitCateger::intervalFeatures(const Interval &interval) +ctx::IntervalFeatures ctx::VisitCateger::intervalFeatures(const Interval &interval) { - num_t duration_minutes = 1.0 * (interval.end - interval.start) / 60; - TimeFeatures start_features = timeFeatures(interval.start); - TimeFeatures end_features = timeFeatures(interval.end); - categs_t week_features = weekModelFeatures(interval, start_features, end_features); + num_t durationMinutes = 1.0 * (interval.end - interval.start) / 60; + TimeFeatures startFeatures = timeFeatures(interval.start); + TimeFeatures endFeatures = timeFeatures(interval.end); + Categs weekFeatures = weekModelFeatures(interval, startFeatures, endFeatures); return { - duration_minutes, - (num_t) start_features.minutesSinceMidnight, - (num_t) end_features.minutesSinceMidnight, - (num_t) start_features.weekday, - week_features[PLACE_CATEG_ID_HOME], - week_features[PLACE_CATEG_ID_WORK], - week_features[PLACE_CATEG_ID_OTHER] + durationMinutes, + (num_t) startFeatures.minutesSinceMidnight, + (num_t) endFeatures.minutesSinceMidnight, + (num_t) startFeatures.weekday, + weekFeatures[PLACE_CATEG_ID_HOME], + weekFeatures[PLACE_CATEG_ID_WORK], + weekFeatures[PLACE_CATEG_ID_OTHER] }; } @@ -409,15 +408,15 @@ void ctx::VisitCateger::__normalize(std::vector &features) void ctx::VisitCateger::categorize(ctx::Visit &visit) { - std::vector features = intervalFeatures(visit.interval); + IntervalFeatures features = intervalFeatures(visit.interval); __normalize(features); - for (auto &model_pair : __models) { - int categ_i = model_pair.first; - MahalModel model = model_pair.second; + for (auto &modelPair : __models) { + int categId = modelPair.first; + MahalModel model = modelPair.second; - num_t mahal_dist = model.dist(features); - num_t prob = 1 - __chiApprox.value(mahal_dist); // sth like probability but not exactly - visit.categs[categ_i] = prob; + num_t distance = model.distance(features); + num_t probability = 1 - __chiApprox.value(distance); // sth like probability but not exactly + visit.categs[categId] = probability; } } diff --git a/src/place/recognition/user_places/visit_categer.h b/src/place/recognition/user_places/visit_categer.h index d7888bb..b9d4940 100644 --- a/src/place/recognition/user_places/visit_categer.h +++ b/src/place/recognition/user_places/visit_categer.h @@ -31,19 +31,21 @@ namespace ctx { bool weekend; }; + typedef std::vector IntervalFeatures; + /* * visit categorizer class */ class VisitCateger { private: - const static int MINUTES_IN_WEEK = 60 * 24 * 7; - const static std::map __models; - const static std::vector __featuresMean; - const static std::vector __featuresStd; + static const int __MINUTES_IN_WEEK = 60 * 24 * 7; + static const std::map __models; + static const std::vector __featuresMean; + static const std::vector __featuresStd; static num_t __sum(const std::vector model, const size_t &from, const size_t &to); static num_t __weekModelMeanValue(PlaceCategId categ, const Interval &interval, - const TimeFeatures &start_f, const TimeFeatures &end_f); + const TimeFeatures &startF, const TimeFeatures &endF); static void __normalize(std::vector &features); static PiecewiseLin __chiApprox; // tabled chi function approximator @@ -56,27 +58,27 @@ namespace ctx { */ static TimeFeatures timeFeatures(const time_t &time); - static int weeksScope(const TimeFeatures &start_f, const Interval &interval); + static int weeksScope(const TimeFeatures &startF, const Interval &interval); /** * Function interpret time interval input argument and calculates scores * that argument interval is home, work or other based on whole week model. * * @param interval time interval - * @param start_f start time features - * @param end_f end time features - * @return categs_t score that argument interval is home, work or other + * @param startF start time features + * @param endF end time features + * @return Categs score that argument interval is home, work or other */ - static categs_t weekModelFeatures(const Interval &interval, const TimeFeatures &start_f, - const TimeFeatures &end_f); + static Categs weekModelFeatures(const Interval &interval, const TimeFeatures &startF, + const TimeFeatures &endF); /** * Function interpret time interval input argument, * - * @param interval time interval - * @return std::vector vector with interpretations of input time interval + * @param interval time interval + * @return IntervalFeatures vector with interpretations of input time interval */ - static std::vector intervalFeatures(const Interval &interval); + static IntervalFeatures intervalFeatures(const Interval &interval); /** * Function categorize visit based on visits time interval and fill its categories values. diff --git a/src/place/recognition/user_places/visit_detector.cpp b/src/place/recognition/user_places/visit_detector.cpp index d0ee631..57383ca 100644 --- a/src/place/recognition/user_places/visit_detector.cpp +++ b/src/place/recognition/user_places/visit_detector.cpp @@ -30,7 +30,7 @@ #include "debug_utils.h" #ifdef TIZEN_ENGINEER_MODE -#define VISIT_TABLE_COLUMNS \ +#define __VISIT_TABLE_COLUMNS \ VISIT_COLUMN_WIFI_APS " TEXT, "\ VISIT_COLUMN_START_TIME " timestamp, "\ VISIT_COLUMN_END_TIME " timestamp, "\ @@ -43,7 +43,7 @@ VISIT_COLUMN_CATEG_WORK " REAL, "\ VISIT_COLUMN_CATEG_OTHER " REAL" #else /* TIZEN_ENGINEER_MODE */ -#define VISIT_TABLE_COLUMNS \ +#define __VISIT_TABLE_COLUMNS \ VISIT_COLUMN_WIFI_APS " TEXT, "\ VISIT_COLUMN_START_TIME " timestamp, "\ VISIT_COLUMN_END_TIME " timestamp, "\ @@ -55,11 +55,11 @@ VISIT_COLUMN_CATEG_OTHER " REAL" #endif /* TIZEN_ENGINEER_MODE */ -ctx::VisitDetector::VisitDetector(time_t t_start_scan, place_recog_mode_e energyMode, bool testMode) : +ctx::VisitDetector::VisitDetector(time_t startScan, PlaceRecogMode energyMode, bool testMode) : __testMode(testMode), __locationLogger(this, testMode), __wifiLogger(this, energyMode, testMode), - __currentInterval(t_start_scan, t_start_scan + VISIT_DETECTOR_PERIOD_SECONDS_HIGH_ACCURACY), + __currentInterval(startScan, startScan + VISIT_DETECTOR_PERIOD_SECONDS_HIGH_ACCURACY), __stableCounter(0), __tolerance(VISIT_DETECTOR_TOLERANCE_DEPTH), __entranceToPlace(false), @@ -68,12 +68,12 @@ ctx::VisitDetector::VisitDetector(time_t t_start_scan, place_recog_mode_e energy __departureTime(0) { __setPeriod(energyMode); - __currentInterval = Interval(t_start_scan, t_start_scan + __periodSeconds); - __currentLogger = std::make_shared(); - __stayMacs = std::make_shared(); + __currentInterval = Interval(startScan, startScan + __periodSeconds); + __currentMacEvents = std::make_shared(); + __stayMacs = std::make_shared(); if (__testMode) { - __detectedVisits = std::make_shared(); + __detectedVisits = std::make_shared(); return; } @@ -100,28 +100,28 @@ void ctx::VisitDetector::onWifiScan(ctx::MacEvent e) __processCurrentLogger(); __shiftCurrentInterval(); } - __currentLogger->push_back(e); + __currentMacEvents->push_back(e); } } void ctx::VisitDetector::__processCurrentLogger() { _D(""); - std::shared_ptr frame = __makeFrame(__currentLogger, __currentInterval); + std::shared_ptr frame = __makeFrame(__currentMacEvents, __currentInterval); __detectEntranceOrDeparture(frame); - __currentLogger->clear(); + __currentMacEvents->clear(); } -std::shared_ptr ctx::VisitDetector::__makeFrame(std::shared_ptr logger, ctx::Interval interval) +std::shared_ptr ctx::VisitDetector::__makeFrame(std::shared_ptr logger, ctx::Interval interval) { std::set timestamps; std::shared_ptr frame = std::make_shared(interval); for (auto log : *logger) { timestamps.insert(log.timestamp); - if (frame->macCountsMap.find(log.mac) == frame->macCountsMap.end()) { - frame->macCountsMap[log.mac] = 1; + if (frame->macs2Counts.find(log.mac) == frame->macs2Counts.end()) { + frame->macs2Counts[log.mac] = 1; } else { - frame->macCountsMap[log.mac] += 1; + frame->macs2Counts[log.mac] += 1; } } frame->numberOfTimestamps = timestamps.size(); @@ -139,20 +139,20 @@ void ctx::VisitDetector::__detectEntranceOrDeparture(std::shared_ptr __entranceToPlace ? __detectDeparture(frame) : __detectEntrance(frame); } -bool ctx::VisitDetector::__isDisjoint(const ctx::mac_counts_t &macCountsMap, const ctx::mac_set_t &macSet) +bool ctx::VisitDetector::__isDisjoint(const ctx::Macs2Counts &macs2Counts, const ctx::MacSet &macSet) { for (auto &mac : macSet) { - if (macCountsMap.find(mac) != macCountsMap.end()) { + if (macs2Counts.find(mac) != macs2Counts.end()) { return false; } } return true; } -bool ctx::VisitDetector::__protrudesFrom(const ctx::mac_counts_t &macCountsMap, const ctx::mac_set_t &macSet) +bool ctx::VisitDetector::__protrudesFrom(const ctx::Macs2Counts &macs2Counts, const ctx::MacSet &macSet) { - for (auto &m : macCountsMap) { - if (macSet.find(m.first) == macSet.end()) { + for (auto &macCount : macs2Counts) { + if (macSet.find(macCount.first) == macSet.end()) { return true; } } @@ -167,8 +167,8 @@ void ctx::VisitDetector::__detectDeparture(std::shared_ptr frame) } else { // __tolerance < VISIT_DETECTOR_TOLERANCE_DEPTH __bufferedFrames.push_back(frame); } - if (__isDisjoint(frame->macCountsMap, *__representativesMacs)) { - if (frame->macCountsMap.empty() || __protrudesFrom(frame->macCountsMap, *__stayMacs)) { + if (__isDisjoint(frame->macs2Counts, *__representativesMacs)) { + if (frame->macs2Counts.empty() || __protrudesFrom(frame->macs2Counts, *__stayMacs)) { __tolerance--; } else { // no new macs __bufferedFrames.clear(); @@ -230,15 +230,15 @@ void ctx::VisitDetector::__putLocationToVisit(ctx::Visit &visit) // TODO: remove small accuracy locations from vectors? std::vector latitudes; std::vector longitudes; - visit.location_valid = false; + visit.locationValid = false; for (LocationEvent location : __locationEvents) { if (location.timestamp >= __entranceTime && location.timestamp <= __departureTime) { latitudes.push_back(location.coordinates.latitude); longitudes.push_back(location.coordinates.longitude); - visit.location_valid = true; + visit.locationValid = true; } } - if (visit.location_valid) { + if (visit.locationValid) { visit.location.latitude = median(latitudes); visit.location.longitude = median(longitudes); _D("visit location set: lat=%.8f, lon=%.8f", visit.location.latitude, visit.location.longitude); @@ -262,29 +262,29 @@ void ctx::VisitDetector::__processBuffer(std::shared_ptr frame) } } -void ctx::VisitDetector::__detectEntrance(std::shared_ptr current_frame) +void ctx::VisitDetector::__detectEntrance(std::shared_ptr currentFrame) { - if (current_frame->macCountsMap.empty() || __historyFrames.empty()) { - __resetHistory(current_frame); + if (currentFrame->macs2Counts.empty() || __historyFrames.empty()) { + __resetHistory(currentFrame); return; } if (__stableCounter == 0) { - std::shared_ptr oldest_history_frame = __historyFrames[0]; - __stayMacs = mac_set_from_mac_counts(oldest_history_frame->macCountsMap); + std::shared_ptr oldestHistoryFrame = __historyFrames[0]; + __stayMacs = macSetFromMacs2Counts(oldestHistoryFrame->macs2Counts); } - std::shared_ptr current_beacons = mac_set_from_mac_counts(current_frame->macCountsMap); + std::shared_ptr currentBeacons = macSetFromMacs2Counts(currentFrame->macs2Counts); - if (similarity::overlapBiggerOverSmaller(*current_beacons, *__stayMacs) > VISIT_DETECTOR_OVERLAP) { + if (similarity::overlapBiggerOverSmaller(*currentBeacons, *__stayMacs) > VISIT_DETECTOR_OVERLAP) { __stableCounter++; - __historyFrames.push_back(current_frame); + __historyFrames.push_back(currentFrame); if (__stableCounter == VISIT_DETECTOR_STABLE_DEPTH) { // entrance detected __visitStartDetected(); } } else { - __resetHistory(current_frame); + __resetHistory(currentFrame); } return; } @@ -301,82 +301,81 @@ void ctx::VisitDetector::__resetHistory(std::shared_ptr frame) __historyFrames.push_back(frame); } -std::shared_ptr ctx::VisitDetector::__selectRepresentatives(const std::vector> &frames) +std::shared_ptr ctx::VisitDetector::__selectRepresentatives(const std::vector> &frames) { - mac_counts_t repr_counts; - count_t all_count = 0; + Macs2Counts reprs2Counts; + count_t allCount = 0; for (auto frame : frames) { - all_count += frame->numberOfTimestamps; - for (auto &c : frame->macCountsMap) { - repr_counts[c.first] += c.second; + allCount += frame->numberOfTimestamps; + for (auto &c : frame->macs2Counts) { + reprs2Counts[c.first] += c.second; } } - std::shared_ptr repr_shares = __macSharesFromCounts(repr_counts, all_count); + std::shared_ptr reprs2Shares = __macSharesFromCounts(reprs2Counts, allCount); - share_t max_share = __calcMaxShare(*repr_shares); - share_t threshold = max_share < VISIT_DETECTOR_REP_THRESHOLD ? - max_share : VISIT_DETECTOR_REP_THRESHOLD; + share_t maxShare = __calcMaxShare(*reprs2Shares); + share_t threshold = maxShare < VISIT_DETECTOR_REP_THRESHOLD ? maxShare : VISIT_DETECTOR_REP_THRESHOLD; - std::shared_ptr repr_mac_set = __macSetOfGreaterOrEqualShare(*repr_shares, threshold); + std::shared_ptr reprsMacSet = __macSetOfGreaterOrEqualShare(*reprs2Shares, threshold); - return repr_mac_set; + return reprsMacSet; } -ctx::share_t ctx::VisitDetector::__calcMaxShare(const ctx::mac_shares_t &mac_shares) +ctx::share_t ctx::VisitDetector::__calcMaxShare(const ctx::Macs2Shares &macs2Shares) { - ctx::share_t max_value = 0.0; - for (auto &ms : mac_shares) { - if (ms.second > max_value) { - max_value = ms.second; + ctx::share_t maxShare = 0.0; + for (auto &macShare : macs2Shares) { + if (macShare.second > maxShare) { + maxShare = macShare.second; } } - return max_value; + return maxShare; } -std::shared_ptr ctx::VisitDetector::__macSetOfGreaterOrEqualShare(const ctx::mac_shares_t &mac_shares, ctx::share_t threshold) +std::shared_ptr ctx::VisitDetector::__macSetOfGreaterOrEqualShare(const ctx::Macs2Shares &macs2Shares, ctx::share_t threshold) { - std::shared_ptr macSet = std::make_shared(); - for (auto &ms : mac_shares) { - if (ms.second >= threshold) { - macSet->insert(ms.first); + std::shared_ptr macSet = std::make_shared(); + for (auto &macShare : macs2Shares) { + if (macShare.second >= threshold) { + macSet->insert(macShare.first); } } return macSet; } -std::shared_ptr ctx::VisitDetector::__macSharesFromCounts(ctx::mac_counts_t const &macCountsMap, ctx::count_t denominator) +std::shared_ptr ctx::VisitDetector::__macSharesFromCounts(ctx::Macs2Counts const &macs2Counts, ctx::count_t denominator) { - std::shared_ptr mac_shares(std::make_shared()); - for (auto mac_count : macCountsMap) { - (*mac_shares)[mac_count.first] = (share_t) mac_count.second / denominator; + std::shared_ptr macs2Shares(std::make_shared()); + for (auto macCount : macs2Counts) { + (*macs2Shares)[macCount.first] = (share_t) macCount.second / denominator; } - return mac_shares; + return macs2Shares; } -std::shared_ptr ctx::VisitDetector::getVisits() +std::shared_ptr ctx::VisitDetector::getVisits() { return __detectedVisits; } void ctx::VisitDetector::__dbCreateTable() { - bool ret = db_manager::create_table(0, VISIT_TABLE, VISIT_TABLE_COLUMNS); + bool ret = db_manager::create_table(0, VISIT_TABLE, __VISIT_TABLE_COLUMNS); _D("db: visit Table Creation Result: %s", ret ? "SUCCESS" : "FAIL"); } -void ctx::VisitDetector::__putVisitCategToJson(const char* key, const categs_t &categs, int categ_type, Json &data) +void ctx::VisitDetector::__putVisitCategToJson(const char* key, const Categs &categs, int categType, Json &data) { - auto categ_p = categs.find(categ_type); - if (categ_p == categs.end()) { - _E("json_put_visit no type %d in categs", categ_type); + auto categ = categs.find(categType); + if (categ == categs.end()) { + _E("json_put_visit no type %d in categs", categType); } else { - data.set(NULL, key, categ_p->second); + data.set(NULL, key, categ->second); } } -void ctx::VisitDetector::__putVisitCategsToJson(const categs_t &categs, Json &data) +void ctx::VisitDetector::__putVisitCategsToJson(const Categs &categs, Json &data) { __putVisitCategToJson(VISIT_COLUMN_CATEG_HOME, categs, PLACE_CATEG_ID_HOME, data); __putVisitCategToJson(VISIT_COLUMN_CATEG_WORK, categs, PLACE_CATEG_ID_WORK, data); @@ -385,13 +384,13 @@ void ctx::VisitDetector::__putVisitCategsToJson(const categs_t &categs, Json &da int ctx::VisitDetector::__dbInsertVisit(Visit visit) { - std::stringstream macs_ss; - macs_ss << *visit.macSet; + std::stringstream ss; + ss << *visit.macSet; Json data; - data.set(NULL, VISIT_COLUMN_WIFI_APS, macs_ss.str().c_str()); + data.set(NULL, VISIT_COLUMN_WIFI_APS, ss.str().c_str()); - data.set(NULL, VISIT_COLUMN_LOCATION_VALID, visit.location_valid); + data.set(NULL, VISIT_COLUMN_LOCATION_VALID, visit.locationValid); data.set(NULL, VISIT_COLUMN_LOCATION_LATITUDE, visit.location.latitude); data.set(NULL, VISIT_COLUMN_LOCATION_LONGITUDE, visit.location.longitude); @@ -399,32 +398,32 @@ int ctx::VisitDetector::__dbInsertVisit(Visit visit) data.set(NULL, VISIT_COLUMN_END_TIME, static_cast(visit.interval.end)); #ifdef TIZEN_ENGINEER_MODE - std::string start_time_human = DebugUtils::humanReadableDateTime(visit.interval.start, "%F %T", 80); - std::string end_time_human = DebugUtils::humanReadableDateTime(visit.interval.end, "%F %T", 80); - data.set(NULL, VISIT_COLUMN_START_TIME_HUMAN, start_time_human.c_str()); - data.set(NULL, VISIT_COLUMN_END_TIME_HUMAN, end_time_human.c_str()); + std::string startTimeHuman = DebugUtils::humanReadableDateTime(visit.interval.start, "%F %T", 80); + std::string endTimeHuman = DebugUtils::humanReadableDateTime(visit.interval.end, "%F %T", 80); + data.set(NULL, VISIT_COLUMN_START_TIME_HUMAN, startTimeHuman.c_str()); + data.set(NULL, VISIT_COLUMN_END_TIME_HUMAN, endTimeHuman.c_str()); _D("db: visit table insert interval: (%d, %d): (%s, %s)", - visit.interval.start, visit.interval.end, start_time_human.c_str(), end_time_human.c_str()); + visit.interval.start, visit.interval.end, startTimeHuman.c_str(), endTimeHuman.c_str()); #else _D("db: visit table insert interval: (%d, %d)", visit.interval.start, visit.interval.end); #endif /* TIZEN_ENGINEER_MODE */ __putVisitCategsToJson(visit.categs, data); - int64_t row_id; - bool ret = db_manager::insert_sync(VISIT_TABLE, data, &row_id); + int64_t rowId; + bool ret = db_manager::insert_sync(VISIT_TABLE, data, &rowId); _D("db: visit table insert result: %s", ret ? "SUCCESS" : "FAIL"); return ret; } -void ctx::VisitDetector::onNewLocation(LocationEvent location_event) +void ctx::VisitDetector::onNewLocation(LocationEvent locationEvent) { _D(""); - location_event.log(); - __locationEvents.push_back(location_event); + locationEvent.log(); + __locationEvents.push_back(locationEvent); }; -void ctx::VisitDetector::__setPeriod(place_recog_mode_e energyMode) +void ctx::VisitDetector::__setPeriod(PlaceRecogMode energyMode) { switch (energyMode) { case PLACE_RECOG_LOW_POWER_MODE: @@ -438,7 +437,7 @@ void ctx::VisitDetector::__setPeriod(place_recog_mode_e energyMode) } } -void ctx::VisitDetector::setMode(place_recog_mode_e energyMode) +void ctx::VisitDetector::setMode(PlaceRecogMode energyMode) { _D(""); __setPeriod(energyMode); diff --git a/src/place/recognition/user_places/visit_detector.h b/src/place/recognition/user_places/visit_detector.h index a4c9b34..757774e 100644 --- a/src/place/recognition/user_places/visit_detector.h +++ b/src/place/recognition/user_places/visit_detector.h @@ -36,11 +36,11 @@ namespace ctx { private: bool __testMode; - std::shared_ptr __detectedVisits; // only used in test mode + std::shared_ptr __detectedVisits; // only used in test mode LocationLogger __locationLogger; WifiLogger __wifiLogger; std::vector __listeners; - std::shared_ptr __currentLogger; + std::shared_ptr __currentMacEvents; Interval __currentInterval; std::vector __locationEvents; std::vector> __historyFrames; // python: history_scans + history_times @@ -51,8 +51,8 @@ namespace ctx { int __periodSeconds; // fields that are used only in case of entrance detection - std::shared_ptr __representativesMacs; // macs that represent the current place - std::shared_ptr __stayMacs; // macs that can appear in the current place + std::shared_ptr __representativesMacs; // macs that represent the current place + std::shared_ptr __stayMacs; // macs that can appear in the current place time_t __entranceTime; time_t __departureTime; @@ -62,37 +62,37 @@ namespace ctx { void __detectEntrance(std::shared_ptr frame); void __detectDeparture(std::shared_ptr frame); void __processBuffer(std::shared_ptr frame); // python: buffer_analysing - std::shared_ptr __makeFrame(std::shared_ptr mac_events, Interval interval); // python: scans2fingerprint + std::shared_ptr __makeFrame(std::shared_ptr macEvents, Interval interval); // python: scans2fingerprint void __resetHistory(); void __resetHistory(std::shared_ptr frame); void __visitStartDetected(); void __visitEndDetected(); void __putLocationToVisit(Visit &visit); - std::shared_ptr __selectRepresentatives(const std::vector> &frames); - std::shared_ptr __macSetOfGreaterOrEqualShare(const mac_shares_t &mac_shares, share_t threshold); - std::shared_ptr __macSharesFromCounts(mac_counts_t const &mac_counts, count_t denominator); // python: response_rate - share_t __calcMaxShare(const mac_shares_t &mac_shares); - bool __isDisjoint(const mac_counts_t &mac_counts, const mac_set_t &macSet); - bool __protrudesFrom(const mac_counts_t &mac_counts, const mac_set_t &macSet); - void __setPeriod(place_recog_mode_e mode); + std::shared_ptr __selectRepresentatives(const std::vector> &frames); + std::shared_ptr __macSetOfGreaterOrEqualShare(const Macs2Shares &macs2Shares, share_t threshold); + std::shared_ptr __macSharesFromCounts(Macs2Counts const &macs2Counts, count_t denominator); // python: response_rate + share_t __calcMaxShare(const Macs2Shares &macs2Shares); + bool __isDisjoint(const Macs2Counts &macs2Counts, const MacSet &macSet); + bool __protrudesFrom(const Macs2Counts &macs2Counts, const MacSet &macSet); + void __setPeriod(PlaceRecogMode mode); void __processCurrentLogger(); /* DATABASE */ void __dbCreateTable(); int __dbInsertVisit(Visit visit); - void __putVisitCategToJson(const char* key, const categs_t &categs, int categ_type, Json &data); - void __putVisitCategsToJson(const categs_t &categs, Json &data); + void __putVisitCategToJson(const char* key, const Categs &categs, int categType, Json &data); + void __putVisitCategsToJson(const Categs &categs, Json &data); /* INPUT */ void onWifiScan(MacEvent event); void onNewLocation(LocationEvent location); public: - VisitDetector(time_t t_start_scan, place_recog_mode_e energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE, bool testMode = false); + VisitDetector(time_t startScan, PlaceRecogMode energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE, bool testMode = false); ~VisitDetector(); - std::shared_ptr getVisits(); // only used in test mode - void setMode(place_recog_mode_e energyMode); + std::shared_ptr getVisits(); // only used in test mode + void setMode(PlaceRecogMode energyMode); }; /* class VisitDetector */ diff --git a/src/place/recognition/user_places/wifi_listener_iface.h b/src/place/recognition/user_places/wifi_listener_iface.h index 8f91c22..3b883d3 100644 --- a/src/place/recognition/user_places/wifi_listener_iface.h +++ b/src/place/recognition/user_places/wifi_listener_iface.h @@ -25,7 +25,7 @@ namespace ctx { public: virtual ~IWifiListener() {}; - virtual void onWifiScan(ctx::MacEvent e) = 0; + virtual void onWifiScan(ctx::MacEvent macEvent) = 0; }; /* IWifiListener */ diff --git a/src/place/recognition/user_places/wifi_logger.cpp b/src/place/recognition/user_places/wifi_logger.cpp index 29dabd4..4c3742a 100644 --- a/src/place/recognition/user_places/wifi_logger.cpp +++ b/src/place/recognition/user_places/wifi_logger.cpp @@ -21,11 +21,11 @@ #include #include "debug_utils.h" -#define WIFI_CREATE_TABLE_COLUMNS \ +#define __WIFI_CREATE_TABLE_COLUMNS \ WIFI_COLUMN_TIMESTAMP " timestamp NOT NULL, "\ WIFI_COLUMN_BSSID " TEXT NOT NULL" -#define _WIFI_ERROR_LOG(error) { \ +#define __WIFI_ERROR_LOG(error) { \ if (error != WIFI_ERROR_NONE) { \ _E("ERROR == %s", __wifiError2Str(error)); \ } else { \ @@ -35,7 +35,7 @@ int ctx::WifiLogger::__dbCreateTable() { - bool ret = db_manager::create_table(0, WIFI_TABLE_NAME, WIFI_CREATE_TABLE_COLUMNS, NULL, NULL); + bool ret = db_manager::create_table(0, WIFI_TABLE_NAME, __WIFI_CREATE_TABLE_COLUMNS, NULL, NULL); _D("Table Creation Request: %s", ret ? "SUCCESS" : "FAIL"); return ret; } @@ -64,7 +64,7 @@ int ctx::WifiLogger::__dbInsertLogs() return 0; } -ctx::WifiLogger::WifiLogger(IWifiListener * listener, place_recog_mode_e energyMode, bool testMode) : +ctx::WifiLogger::WifiLogger(IWifiListener * listener, PlaceRecogMode energyMode, bool testMode) : __timerOn(false), __intervalMinutes(WIFI_LOGGER_INTERVAL_MINUTES_HIGH_ACCURACY), __testMode(testMode), @@ -107,9 +107,9 @@ ctx::WifiLogger::~WifiLogger() __wifiDeinitializeRequest(); } -void ctx::WifiLogger::__wifiDeviceStateChangedCb(wifi_device_state_e state, void *user_data) +void ctx::WifiLogger::__wifiDeviceStateChangedCb(wifi_device_state_e state, void *userData) { - ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)user_data; + ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)userData; switch (state) { case WIFI_DEVICE_STATE_DEACTIVATED: _D("WIFI setting OFF"); @@ -128,9 +128,9 @@ void ctx::WifiLogger::__wifiDeviceStateChangedCb(wifi_device_state_e state, void } } -void ctx::WifiLogger::__wifiConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *user_data) +void ctx::WifiLogger::__wifiConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *userData) { - ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)user_data; + ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)userData; switch (state) { case WIFI_CONNECTION_STATE_CONNECTED: _D("connected to AP"); @@ -145,9 +145,9 @@ void ctx::WifiLogger::__wifiConnectionStateChangedCb(wifi_connection_state_e sta // TODO: Check if AP bssid (MAC Address) will be helpful somehow in LOW_POWER mode } -bool ctx::WifiLogger::__wifiFoundApCb(wifi_ap_h ap, void *user_data) +bool ctx::WifiLogger::__wifiFoundApCb(wifi_ap_h ap, void *userData) { - ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)user_data; + ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)userData; char *bssid = NULL; int ret = __wifiApGetBssidRequest(ap, &bssid); @@ -215,9 +215,9 @@ const char* ctx::WifiLogger::__wifiError2Str(int error) } } -void ctx::WifiLogger::__wifiScanFinishedCb(wifi_error_e error_code, void *user_data) +void ctx::WifiLogger::__wifiScanFinishedCb(wifi_error_e errorCode, void *userData) { - ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)user_data; + ctx::WifiLogger* wifiLogger = (ctx::WifiLogger *)userData; time_t now = time(nullptr); #ifdef TIZEN_ENGINEER_MODE @@ -225,17 +225,17 @@ void ctx::WifiLogger::__wifiScanFinishedCb(wifi_error_e error_code, void *user_d if (wifiLogger->__lastScanTime > 0) { seconds = difftime(now, wifiLogger->__lastScanTime); } - std::string time_str = DebugUtils::humanReadableDateTime(now, "%T", 9); + std::string timeStr = DebugUtils::humanReadableDateTime(now, "%T", 9); _D("__connectedToWifiAp = %d, __duringVisit = %d, __lastScansPool.size() = %d -> scan %s (from last : %.1fs)", static_cast(wifiLogger->__connectedToWifiAp), static_cast(wifiLogger->__duringVisit), wifiLogger->__lastScansPool.size(), - time_str.c_str(), + timeStr.c_str(), seconds); #endif /* TIZEN_ENGINEER_MODE */ wifiLogger->__lastScanTime = now; - int ret = __wifiForeachFoundApsRequest(user_data); + int ret = __wifiForeachFoundApsRequest(userData); if (ret != WIFI_ERROR_NONE) { return; } @@ -246,69 +246,69 @@ void ctx::WifiLogger::__wifiScanFinishedCb(wifi_error_e error_code, void *user_d bool ctx::WifiLogger::__checkWifiIsActivated() { - bool wifi_activated = true; - int ret = wifi_is_activated(&wifi_activated); - _WIFI_ERROR_LOG(ret); - _D("Wi-Fi is %s", wifi_activated ? "ON" : "OFF"); - return wifi_activated; + bool wifiActivated = true; + int ret = wifi_is_activated(&wifiActivated); + __WIFI_ERROR_LOG(ret); + _D("Wi-Fi is %s", wifiActivated ? "ON" : "OFF"); + return wifiActivated; } void ctx::WifiLogger::__wifiScanRequest() { int ret = wifi_scan(__wifiScanFinishedCb, this); - _WIFI_ERROR_LOG(ret); + __WIFI_ERROR_LOG(ret); } -int ctx::WifiLogger::__wifiForeachFoundApsRequest(void *user_data) +int ctx::WifiLogger::__wifiForeachFoundApsRequest(void *userData) { - int ret = wifi_foreach_found_aps(__wifiFoundApCb, user_data); - _WIFI_ERROR_LOG(ret); + int ret = wifi_foreach_found_aps(__wifiFoundApCb, userData); + __WIFI_ERROR_LOG(ret); return ret; } wifi_connection_state_e ctx::WifiLogger::__wifiGetConnectionStateRequest() { - wifi_connection_state_e connection_state; - int ret = wifi_get_connection_state(&connection_state); - _WIFI_ERROR_LOG(ret); - return connection_state; + wifi_connection_state_e connectionState; + int ret = wifi_get_connection_state(&connectionState); + __WIFI_ERROR_LOG(ret); + return connectionState; } void ctx::WifiLogger::__wifiSetBackgroundScanCbRequest() { int ret = wifi_set_background_scan_cb(__wifiScanFinishedCb, this); - _WIFI_ERROR_LOG(ret); + __WIFI_ERROR_LOG(ret); } void ctx::WifiLogger::__wifiSetDeviceStateChangedCbRequest() { int ret = wifi_set_device_state_changed_cb(__wifiDeviceStateChangedCb, this); - _WIFI_ERROR_LOG(ret); + __WIFI_ERROR_LOG(ret); } void ctx::WifiLogger::__wifiSetConnectionStateChangedCbRequest() { int ret = wifi_set_connection_state_changed_cb(__wifiConnectionStateChangedCb, this); - _WIFI_ERROR_LOG(ret); + __WIFI_ERROR_LOG(ret); } int ctx::WifiLogger::__wifiApGetBssidRequest(wifi_ap_h ap, char **bssid) { int ret = wifi_ap_get_bssid(ap, bssid); - _WIFI_ERROR_LOG(ret); + __WIFI_ERROR_LOG(ret); return ret; } void ctx::WifiLogger::__wifiInitializeRequest() { int ret = wifi_initialize(); - _WIFI_ERROR_LOG(ret); + __WIFI_ERROR_LOG(ret); } void ctx::WifiLogger::__wifiDeinitializeRequest() { int ret = wifi_deinitialize(); - _WIFI_ERROR_LOG(ret); + __WIFI_ERROR_LOG(ret); } bool ctx::WifiLogger::__checkTimerId(int id) @@ -443,7 +443,7 @@ void ctx::WifiLogger::onVisitEnd() __lastScansPool.clear(); } -void ctx::WifiLogger::__setInterval(place_recog_mode_e energyMode) +void ctx::WifiLogger::__setInterval(PlaceRecogMode energyMode) { switch (energyMode) { case PLACE_RECOG_LOW_POWER_MODE: @@ -463,7 +463,7 @@ void ctx::WifiLogger::__timerRestart() __timerStart(__intervalMinutes); } -void ctx::WifiLogger::setMode(place_recog_mode_e energyMode) +void ctx::WifiLogger::setMode(PlaceRecogMode energyMode) { _D(""); __setInterval(energyMode); diff --git a/src/place/recognition/user_places/wifi_logger.h b/src/place/recognition/user_places/wifi_logger.h index 029eee1..9938a2c 100644 --- a/src/place/recognition/user_places/wifi_logger.h +++ b/src/place/recognition/user_places/wifi_logger.h @@ -51,13 +51,13 @@ namespace ctx { public: WifiLogger(IWifiListener * listener = nullptr, - place_recog_mode_e mode = PLACE_RECOG_HIGH_ACCURACY_MODE, + PlaceRecogMode energyMode = PLACE_RECOG_HIGH_ACCURACY_MODE, bool testMode = false); ~WifiLogger(); void startLogging(); void stopLogging(); - void setMode(place_recog_mode_e energyMode); + void setMode(PlaceRecogMode energyMode); private: /* INPUT */ @@ -71,7 +71,7 @@ namespace ctx { int __timerId; int __intervalMinutes; TimerManager __timerManager; - void __setInterval(place_recog_mode_e energyMode); + void __setInterval(PlaceRecogMode energyMode); bool __checkTimerId(int id); bool __checkTimerTime(time_t now); void __timerStart(time_t minutes); @@ -87,17 +87,17 @@ namespace ctx { void __wifiSetConnectionStateChangedCbRequest(); static bool __checkWifiIsActivated(); void __wifiScanRequest(); - static int __wifiForeachFoundApsRequest(void *user_data); + static int __wifiForeachFoundApsRequest(void *userData); static wifi_connection_state_e __wifiGetConnectionStateRequest(); static int __wifiApGetBssidRequest(wifi_ap_h ap, char **bssid); void __wifiInitializeRequest(); void __wifiDeinitializeRequest(); /* SYSTEM CAPI CALLBACKS */ - static void __wifiDeviceStateChangedCb(wifi_device_state_e state, void *user_data); - static void __wifiConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *user_data); - static bool __wifiFoundApCb(wifi_ap_h ap, void *user_data); - static void __wifiScanFinishedCb(wifi_error_e error_code, void *user_data); + static void __wifiDeviceStateChangedCb(wifi_device_state_e state, void *userData); + static void __wifiConnectionStateChangedCb(wifi_connection_state_e state, wifi_ap_h ap, void *userData); + static bool __wifiFoundApCb(wifi_ap_h ap, void *userData); + static void __wifiScanFinishedCb(wifi_error_e errorCode, void *userData); bool __testMode; IWifiListener * const __listener; -- 2.7.4 From 40f1bf7df060fe672e1645c225ffb52f29d43a8f Mon Sep 17 00:00:00 2001 From: Andrey Glushkov Date: Thu, 10 Mar 2016 10:58:15 +0900 Subject: [PATCH 13/16] Inactive Application detector engine add Change-Id: I409ec771a2287c66f406f7af3c4959a029e37079 Signed-off-by: Andrey Glushkov --- .../app_inactive_detector.cpp | 79 +++++++ .../app_inactive_detector/app_inactive_detector.h | 49 ++++ .../app_inactive_detector_types.h | 114 ++++++++++ .../app_inactive_detector/inactive_detector.cpp | 121 ++++++++++ .../app/app_inactive_detector/inactive_detector.h | 51 +++++ .../inactive_detector_classificator.cpp | 28 +++ .../inactive_detector_classificator.h | 37 +++ .../inactive_detector_classificator_kmeans.cpp | 174 ++++++++++++++ .../inactive_detector_classificator_kmeans.h | 49 ++++ .../inactive_detector_classificator_kmeans_types.h | 29 +++ .../inactive_detector_storage.cpp | 250 +++++++++++++++++++++ .../inactive_detector_storage.h | 62 +++++ .../inactive_detector_storage_queries.h | 192 ++++++++++++++++ .../inactive_detector_weight.cpp | 30 +++ .../inactive_detector_weight.h | 34 +++ 15 files changed, 1299 insertions(+) create mode 100644 src/statistics/app/app_inactive_detector/app_inactive_detector.cpp create mode 100644 src/statistics/app/app_inactive_detector/app_inactive_detector.h create mode 100644 src/statistics/app/app_inactive_detector/app_inactive_detector_types.h create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector.cpp create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector.h create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_classificator.cpp create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_classificator.h create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans.cpp create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans.h create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans_types.h create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_storage.cpp create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_storage.h create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_storage_queries.h create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_weight.cpp create mode 100644 src/statistics/app/app_inactive_detector/inactive_detector_weight.h diff --git a/src/statistics/app/app_inactive_detector/app_inactive_detector.cpp b/src/statistics/app/app_inactive_detector/app_inactive_detector.cpp new file mode 100644 index 0000000..3e36f7d --- /dev/null +++ b/src/statistics/app/app_inactive_detector/app_inactive_detector.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "app_inactive_detector.h" +#include "app_inactive_detector_types.h" +#include "inactive_detector.h" + + +ctx::app_inactive_detector_provider *ctx::app_inactive_detector_provider::__instance = NULL; + +ctx::app_inactive_detector_provider::app_inactive_detector_provider() +{ +} + +ctx::app_inactive_detector_provider::~app_inactive_detector_provider() +{ +} + +ctx::ContextProviderBase *ctx::app_inactive_detector_provider::create(void *data) +{ + IF_FAIL_RETURN(!__instance, __instance); + __instance = new(std::nothrow) app_inactive_detector_provider(); + IF_FAIL_RETURN_TAG(__instance, NULL, _E, "Memory allocation failed"); + _I(BLUE("Created")); + return __instance; +} + +void ctx::app_inactive_detector_provider::destroy(void *data) +{ + IF_FAIL_VOID(__instance); + delete __instance; + __instance = NULL; + _I(BLUE("Destroyed")); +} + +int ctx::app_inactive_detector_provider::subscribe(const char *subject, ctx::Json option, ctx::Json* request_result) +{ + return ERR_NOT_SUPPORTED; +} + +int ctx::app_inactive_detector_provider::unsubscribe(const char *subject, ctx::Json option) +{ + return ERR_NOT_SUPPORTED; +} + +int ctx::app_inactive_detector_provider::read(const char *subject, ctx::Json option, ctx::Json* request_result) +{ + _I(BLUE("Read")); + _J("Option", option); + + int error = engine->read(subject, option); + return error == ERR_NONE ? ERR_NONE : error; +} + +int ctx::app_inactive_detector_provider::write(const char *subject, ctx::Json data, ctx::Json* request_result) +{ + return ERR_NOT_SUPPORTED; +} + +bool ctx::app_inactive_detector_provider::is_supported() +{ + return true; +} diff --git a/src/statistics/app/app_inactive_detector/app_inactive_detector.h b/src/statistics/app/app_inactive_detector/app_inactive_detector.h new file mode 100644 index 0000000..94e5b83 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/app_inactive_detector.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_APP_INACTIVE_DETECTOR_H__ +#define __CONTEXT_APP_INACTIVE_DETECTOR_H__ + +#include +#include "app_inactive_detector_types.h" +#include "inactive_detector.h" + +namespace ctx { + + class app_inactive_detector_provider : public ContextProviderBase { + + public: + static ContextProviderBase *create(void *data); + static void destroy(void *data); + static bool is_supported(); + + int subscribe(const char *subject, ctx::Json option, ctx::Json *request_result); + int unsubscribe(const char *subject, ctx::Json option); + int read(const char *subject, ctx::Json option, ctx::Json *request_result); + int write(const char *subject, ctx::Json data, ctx::Json *request_result); + + private: + static app_inactive_detector_provider *__instance; + inactive_detector *engine; + + app_inactive_detector_provider(); + ~app_inactive_detector_provider(); + + }; /* class app_inactive_detector_provider */ + +} /* namespace ctx */ + +#endif /* __CONTEXT_APP_INACTIVE_DETECTOR_H__ */ \ No newline at end of file diff --git a/src/statistics/app/app_inactive_detector/app_inactive_detector_types.h b/src/statistics/app/app_inactive_detector/app_inactive_detector_types.h new file mode 100644 index 0000000..b058b54 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/app_inactive_detector_types.h @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_APP_INACTIVE_DETECTOR_TYPES__ +#define __CONTEXT_APP_INACTIVE_DETECTOR_TYPES__ + +#include + +// Context Items +//#define APP_INACTIVE_SUBJ_RECALCULATE "app/recalculate" +#define APP_INACTIVE_SUBJ_GET_APPS_INACTIVE "app/inactive" +#define APP_INACTIVE_SUBJ_GET_APPS_ACTIVE "app/active" +#define APP_INACTIVE_SUBJ_GET_APPS_WEIGHT "app/weight" +#define APP_INACTIVE_SUBJ_UPDATE_CLUSTERS "app/update" + +enum { + APP_INACTIVE_QUERY_ID_GET_APPS_WEIGHT = 1, + APP_INACTIVE_QUERY_ID_GET_APPS_INACTIVE = 2, + APP_INACTIVE_QUERY_ID_GET_APPS_ACTIVE = 3, + APP_INACTIVE_QUERY_ID_UPDATE_CLUSTERS = 4 +}; + +// Database +#define APP_INACTIVE_DETECTOR_APPINFO_TABLE "context_app_info" +#define APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "app_info" +#define APP_INACTIVE_DETECTOR_APPINFO_COLUMN_ID "_id" +#define APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME "package_name" +#define APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_TYPE "package_type" +#define APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_NODISPLAY "is_nodisplay" +#define APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ENABLED "is_enabled" +#define APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ATBOOT "is_atboot" +#define APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_PRELOADED "is_preloaded" +#define APP_INACTIVE_DETECTOR_APPINFO_COLUMN_TIMESTAMP "timestamp" + +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_TABLE "context_app_launch_log" +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_TABLE_ALIAS "app_launch_log" +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_ID "_id" +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_CONTEXT_APP_INFO_ID "context_app_info_id" +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_DURATION "duration" +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_SYSTEM_VOLUME "system_volume" +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_BSSID "bssid" +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_TIMESTAMP "timestamp" +#define APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_TIMESTAMP_UTC "timestamp_utc" + +#define APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE "context_app_activity_classified" +#define APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE_ALIAS "app_activity_classified" +#define APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_ID "_id" +#define APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_CONTEXT_APP_INFO_ID "context_app_info_id" +#define APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_ACTIVITY_RATE "activity_rate" +#define APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_TIMEFRAME "timeframe" +#define APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_IS_ACTIVE "is_active" + + +#define APP_INACTIVE_DETECTOR_VIRTUAL_TABLE_ALIAS "virtual_app_history" +#define APP_INACTIVE_DETECTOR_VIRTUAL_COLUMN_WEIGHT "weight" + +// Output Data Key +#define APP_INACTIVE_DETECTOR_DATA_READ "AppsList" +#define APP_INACTIVE_DETECTOR_DATA_TIMESTAMP_FROM "timestamp_from" +#define APP_INACTIVE_DETECTOR_ACTIVITY_RATE "activity_rate" +#define APP_INACTIVE_DETECTOR_DATA_TIMEFRAME "timeframe" +#define APP_INACTIVE_DETECTOR_DATA_ISACTIVE "is_active" + +//Other +#define APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMESTAMP "$timestamp" +#define APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_CLUSTER "$cluster" +#define APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMEFRAME "$timeframe" +#define APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_VALUES "$values" + +// Objects +struct app_t { + int id; + std::string package_name; + int is_nodisplay; + int is_enabled; + int is_atboot; + int is_preloaded; + double timestamp; + int weight; + int is_active; + int timeframe; +}; + + +#define APP_TYPE_INACTIVE_INACTIVE 1 +#define APP_TYPE_INACTIVE_ACTIVE 2 + + +#define APP_INACTIVE_TASK_START_HOUR 3 +#define APP_INACTIVE_TASK_START_MINUTE 0 + + +#define CONTEXT_HISTORY_FILTER_TIME_INTERVAL_ONEDAY 60*60*24 +#define CONTEXT_HISTORY_FILTER_TIME_INTERVAL_THREEDAYS 60*60*24*3 +#define CONTEXT_HISTORY_FILTER_TIME_INTERVAL_ONEWEEK 60*60*24*7 +#define CONTEXT_HISTORY_FILTER_TIME_INTERVAL_TWOWEEKS 60*60*24*14 +#define CONTEXT_HISTORY_FILTER_TIME_INTERVAL_ONEMONTH 60*60*24*31 + + + +#endif /* __CONTEXT_APP_INACTIVE_DETECTOR_TYPES__ */ \ No newline at end of file diff --git a/src/statistics/app/app_inactive_detector/inactive_detector.cpp b/src/statistics/app/app_inactive_detector/inactive_detector.cpp new file mode 100644 index 0000000..f6e82f9 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "inactive_detector.h" +#include "inactive_detector_weight.h" +#include "inactive_detector_storage.h" +#include "inactive_detector_classificator.h" +#include "TimerManager.h" + +ctx::inactive_detector::inactive_detector() +{ + timer_id = timer_mgr.setAt( // execute once every night + APP_INACTIVE_TASK_START_HOUR, + APP_INACTIVE_TASK_START_MINUTE, + DayOfWeek::EVERYDAY, + this); + if (timer_id < 0) { + _E("inactive_detector timer set FAIL"); + return; + } else { + update_clusters(); + _D("inactive_detector timer set SUCCESS"); + } + +} + +ctx::inactive_detector::~inactive_detector() +{ + if (timer_id >= 0) { + timer_mgr.remove(timer_id); + _D("inactive_detejctor timer removed"); + } + +} + +bool ctx::inactive_detector::onTimerExpired(int timerId) +{ + update_clusters(); + return true; +} + +int ctx::inactive_detector::update_clusters() +{ + // define timeframes stack + std::vector timeframes; + timeframes.push_back(CONTEXT_HISTORY_FILTER_TIME_INTERVAL_ONEDAY); + timeframes.push_back(CONTEXT_HISTORY_FILTER_TIME_INTERVAL_THREEDAYS); + timeframes.push_back(CONTEXT_HISTORY_FILTER_TIME_INTERVAL_ONEWEEK); + timeframes.push_back(CONTEXT_HISTORY_FILTER_TIME_INTERVAL_TWOWEEKS); + timeframes.push_back(CONTEXT_HISTORY_FILTER_TIME_INTERVAL_ONEMONTH); + + // recalculate weights + // foreach timeframe + for(std::vector::iterator timeframe = timeframes.begin(); + timeframe != timeframes.end(); timeframe++) + { + inactive_detector_weight i_detector_weight; + int error = i_detector_weight.request_weights(*timeframe); + _E("update_clusters request_weights:%d, error:%d", *timeframe, error); + } + + return ERR_NONE; +} + +void ctx::inactive_detector::on_cluster_update_finished(std::vector *apps_with_weight, int error) +{ + if (error == ERR_NONE) { + _I("on_cluster_update_finished success"); + } + // clean memory + delete apps_with_weight; +} + +int ctx::inactive_detector::read( + const char *subject, + ctx::Json option) +{ + ctx::inactive_detector_storage *handle = new(std::nothrow) ctx::inactive_detector_storage(); + IF_FAIL_RETURN_TAG(handle, ERR_OPERATION_FAILED, _E, "Memory allocation failed"); + + int err = handle->read(subject, option); + if (err != ERR_NONE) { + delete handle; + return err; + } + + return ERR_NONE; +} + +ctx::Json ctx::inactive_detector::to_json(std::vector *app_infos) +{ + ctx::Json data; + + for(std::vector::iterator app_info = app_infos->begin(); + app_info != app_infos->end(); app_info++) + { + ctx::Json app_j; + app_j.set(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME, app_info->package_name); + app_j.set(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_NODISPLAY, app_info->is_nodisplay); + app_j.set(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ENABLED, app_info->is_enabled); + app_j.set(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ATBOOT, app_info->is_atboot); + app_j.set(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_PRELOADED, app_info->is_preloaded); + app_j.set(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_TIMESTAMP, app_info->timestamp); + } + return data; +} diff --git a/src/statistics/app/app_inactive_detector/inactive_detector.h b/src/statistics/app/app_inactive_detector/inactive_detector.h new file mode 100644 index 0000000..62701d8 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_INACTIVE_DETECTOR_H__ +#define __CONTEXT_INACTIVE_DETECTOR_H__ + +#include +#include +#include +#include "app_inactive_detector_types.h" +#include + +namespace ctx { + + class inactive_detector : public ITimerListener { + private: + int timer_id; + TimerManager timer_mgr; + public: + inactive_detector(); + ~inactive_detector(); + + int read(const char *subject, + ctx::Json option); + + int update_clusters(); + void on_cluster_update_finished( + std::vector *apps_classified, + int error); + ctx::Json to_json(std::vector *apps); + + bool onTimerExpired(int timerId); + }; /* class inactive_detector */ + +} /* namespace ctx */ + + +#endif /* __CONTEXT_INACTIVE_DETECTOR_H__ */ diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_classificator.cpp b/src/statistics/app/app_inactive_detector/inactive_detector_classificator.cpp new file mode 100644 index 0000000..9f85f94 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_classificator.cpp @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "inactive_detector.h" +#include "app_inactive_detector_types.h" +#include "inactive_detector_classificator.h" +#include "inactive_detector_classificator_kmeans.h" + +int ctx::inactive_detector_classificator::classify(std::vector *apps_with_weights) +{ + inactive_detector_classificator_kmeans kmeans; + int error = kmeans.classify(apps_with_weights); + + return error; +} \ No newline at end of file diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_classificator.h b/src/statistics/app/app_inactive_detector/inactive_detector_classificator.h new file mode 100644 index 0000000..e5655d9 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_classificator.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_INACTIVE_DETECTOR_CLASSIFICATOR_H__ +#define __CONTEXT_INACTIVE_DETECTOR_CLASSIFICATOR_H__ + +#include +#include "app_inactive_detector_types.h" +#include + +namespace ctx { + + class inactive_detector_classificator + { + public: + inactive_detector_classificator(); + ~inactive_detector_classificator(); + + int classify(std::vector *apps_with_weights); + }; /* class inactive_detector_classificator */ + +} /* namespace ctx */ + +#endif /* __CONTEXT_INACTIVE_DETECTOR_CLASSIFICATOR_H__ */ diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans.cpp b/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans.cpp new file mode 100644 index 0000000..f020875 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans.cpp @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include +#include "app_inactive_detector_types.h" +#include "inactive_detector_classificator_kmeans.h" +#include "inactive_detector_classificator_kmeans_types.h" +#include +#include + +double ctx::inactive_detector_classificator_kmeans::randomf(double x) +{ + return x * rand() / (RAND_MAX - 1.); +} + +double ctx::inactive_detector_classificator_kmeans::glide_function(double x) +{ + double value = sqrt(log(x) + 1); + return (value > 0 ? value : 0); +} + +point_s *ctx::inactive_detector_classificator_kmeans::reproject_to_2d(std::vector *apps_with_weights) +{ + int distr_size = apps_with_weights->size(); + point_s *p = new point_s[distr_size]; + + int i=0; + for(std::vector::iterator apps_with_weight = apps_with_weights->begin(); + apps_with_weight != apps_with_weights->end(); apps_with_weight++) + { + point_s the_point; + + the_point.x = glide_function(apps_with_weight->weight); // normalize weight values + the_point.y = 0; //remove 3rd dimension of the data + the_point.origin_id = apps_with_weight->package_name; + + p[i] = the_point; + i++; + } + + return p; +} + +bool ctx::inactive_detector_classificator_kmeans::annotate_data(std::vector *apps_with_weights, point_s *c) +{ + int i=0, max_group=-1; + + for(std::vector::iterator apps_with_weight = apps_with_weights->begin(); + apps_with_weight != apps_with_weights->end(); apps_with_weight++) + { + apps_with_weight->is_active = c[i].group; + i++; + max_group = c[i].group > max_group ? c[i].group : max_group; + } + + return max_group == APP_INACTIVE_DETECTOR_KMEANS_CLUSTER_COUNT; +} + +double ctx::inactive_detector_classificator_kmeans::distance_to(point_s *p_from, + point_s *p_to) +{ + double x = p_from->x - p_to->x, y = p_from->y - p_to->y; + return x*x + y*y; +} + +int ctx::inactive_detector_classificator_kmeans::nearest(point_s *pt, + point_s *centers, + int cluster_number, + double *distance) +{ + int i; + int min_i = pt->group; + point_s *c; + + double d; + double min_d = HUGE_VAL; + + for_n { + if (min_d >(d = distance_to(c, pt))) { + min_d = d; min_i = i; + } + } + + if (distance) *distance = min_d; + return min_i; +} + +void ctx::inactive_detector_classificator_kmeans::kpp(point_s *points, int length, point_s *centers, int cluster_number) +{ + int j; + int n_cluster; + double sum; + double *d = new double[length]; + + point_s *p; + centers[0] = points[rand() % length]; + for (n_cluster = 1; n_cluster < cluster_number; n_cluster++) { + sum = 0; + for_len{ + nearest(p, centers, n_cluster, d + j); + sum += d[j]; + } + sum = randomf(sum); + for_len{ + if ((sum -= d[j]) > 0) continue; + centers[n_cluster] = points[j]; + break; + } + } + for_len p->group = nearest(p, centers, n_cluster, 0); + + delete d; +} + +point_s *ctx::inactive_detector_classificator_kmeans::lloyd(point_s *points, int length, int cluster_number) +{ + int i, j, min_i; + int changed; + + point_s *centers = new point_s; + point_s *p, *c; + + /* k++ init */ + kpp(points, length, centers, cluster_number); + + do { + /* group element for centroids are used as counters */ + for_n{ c->group = 0; c->x = c->y = 0; } + for_len{ + c = centers + p->group; + c->group++; + c->x += p->x; c->y += p->y; + } + for_n{ c->x /= c->group; c->y /= c->group; } + + changed = 0; + /* find closest centroid of each point */ + for_len{ + min_i = nearest(p, centers, cluster_number, 0); + if (min_i != p->group) { + changed++; + p->group = min_i; + } + } + } while (changed > (length >> 10)); /* stop when 99.9% of points are good */ + + for_n{ c->group = i; } + + return centers; +} + +int ctx::inactive_detector_classificator_kmeans::classify(std::vector *apps_with_weights) +{ + //array of generated points + point_s *v = reproject_to_2d(apps_with_weights); + //mark cluster for each point, output centers + point_s *c = lloyd(v, apps_with_weights->size(), APP_INACTIVE_DETECTOR_KMEANS_CLUSTER_COUNT); + //append the result to input data + bool classification_is_success = annotate_data(apps_with_weights, c); + + return classification_is_success ? ERR_NONE : ERR_OPERATION_FAILED; +} diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans.h b/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans.h new file mode 100644 index 0000000..dd99125 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_INACTIVE_DETECTOR_CLASSIFICATOR_KMEANS_H__ +#define __CONTEXT_INACTIVE_DETECTOR_CLASSIFICATOR_KMEANS_H__ + +#include +#include "inactive_detector_classificator_kmeans_types.h" +#include + +namespace ctx { + + #define for_n for (c = centers, i = 0; i < cluster_number; i++, c++) + #define for_len for (j = 0, p = points; j < length; j++, p++) + + class inactive_detector_classificator_kmeans + { + private: + double randomf(double x); + double glide_function(double x); + point_s *reproject_to_2d(std::vector *apps_with_weights); + bool annotate_data(std::vector *apps_with_weights, point_s *c); + + double distance_to(point_s *p_from, point_s *p_to); + int nearest(point_s *pt, point_s *centers, int cluster_number, double *distance); + void kpp(point_s *points, int length, point_s *centers, int centers_count); + point_s *lloyd(point_s *points, int length, int cluster_number); + public: + inactive_detector_classificator_kmeans(); + ~inactive_detector_classificator_kmeans(); + + int classify(std::vector *apps_with_weights); + }; /* class inactive_detector_classificator_kmeans */ +} /* namespace ctx */ + +#endif /* __CONTEXT_INACTIVE_DETECTOR_CLASSIFICATOR_KMEANS_H__ */ diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans_types.h b/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans_types.h new file mode 100644 index 0000000..8aa7270 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_classificator_kmeans_types.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_APP_INACTIVE_DETECTOR_CLASSIFICATOR_KMEANS_TYPES__ +#define __CONTEXT_APP_INACTIVE_DETECTOR_CLASSIFICATOR_KMEANS_TYPES__ + +#define APP_INACTIVE_DETECTOR_KMEANS_CLUSTER_COUNT 2 + +typedef struct { + std::string origin_id; + double x; + double y; + int group; +} point_s; + +#endif \ No newline at end of file diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_storage.cpp b/src/statistics/app/app_inactive_detector/inactive_detector_storage.cpp new file mode 100644 index 0000000..c2207a6 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_storage.cpp @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include "inactive_detector.h" +#include "inactive_detector_storage.h" +#include "inactive_detector_storage_queries.h" +#include "inactive_detector_classificator.h" +#include "app_inactive_detector_types.h" +#include "db_mgr.h" +#include + +/*int ctx::inactive_detector_storage::create_table() +{ + bool ret = db_manager::create_table(0, WIFI_TABLE_NAME, WIFI_CREATE_TABLE_COLUMNS, NULL, NULL); + _D("Table Creation Request: %s", ret ? "SUCCESS" : "FAIL"); + return ret; +}*/ + + + +// expected Json format example: {timeframe: 1; is_active: 0} +int ctx::inactive_detector_storage::read( + const char *subject, + ctx::Json filter) +{ + std::string query; + query = query_get_apps(subject, filter); + + IF_FAIL_RETURN(!query.empty(), ERR_OPERATION_FAILED); + + bool ret = db_manager::execute( + STR_EQ(subject, APP_INACTIVE_SUBJ_GET_APPS_INACTIVE) ? + APP_INACTIVE_QUERY_ID_GET_APPS_INACTIVE : + APP_INACTIVE_QUERY_ID_GET_APPS_ACTIVE, + query.c_str(), + this); + + IF_FAIL_RETURN(ret, ERR_OPERATION_FAILED); + + return ERR_NONE; +} + +std::string ctx::inactive_detector_storage::query_get_apps(const char *subject, ctx::Json filter) +{ + double timeframe; + int is_active; + + std::string query(GET_APP_INFO_INACTIVE_QUERY); + std::string placeholder_timeframe(APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMEFRAME); + std::string placeholder_is_active(APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_CLUSTER); + + filter.get(NULL, APP_INACTIVE_DETECTOR_DATA_TIMEFRAME, &timeframe); + filter.get(NULL, APP_INACTIVE_DETECTOR_DATA_ISACTIVE, &is_active); + + std::stringstream timeframe_stream; + timeframe_stream << timeframe; + + std::stringstream is_active_stream; + is_active_stream << is_active; + + inject_params(query, placeholder_timeframe, timeframe_stream.str()); + inject_params(query, placeholder_is_active, is_active_stream.str()); + + return query; +} + +std::string ctx::inactive_detector_storage::query_update_apps(std::vector *apps_with_weights) +{ + std::string delete_query(DELETE_APP_ACTIVITY_CLASSIFIED_BY_TIMEFRAME); + std::string insert_query(INSERT_APP_ACTIVITY_CLASSIFIED); + std::string placeholder_timeframe(APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMEFRAME); + std::string placeholder_values(APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_VALUES); + std::string placeholder_is_active(APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_CLUSTER); + + std::stringstream timeframe_stream; + timeframe_stream << apps_with_weights->front().timeframe; + + inject_params(delete_query, placeholder_timeframe, timeframe_stream.str()); + inject_params(insert_query, placeholder_values, subquery_form_values(apps_with_weights)); + + std::stringstream result; + result << delete_query << insert_query; + return result.str(); +} + +// foreach app_info id+cluster -> select for insert +std::string ctx::inactive_detector_storage::subquery_form_values(std::vector *apps_with_weights) +{ + std::stringstream select_elements; + + for(std::vector::iterator row = apps_with_weights->begin(); + row != apps_with_weights->end(); row++) + { + //SELECT 1 as is_active, 1 as timeframe, 3964 as context_app_info_id + std::stringstream select_element; + select_element << " SELECT " << row->is_active << " as "; + select_element << APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_IS_ACTIVE; + select_element << ", " << row->timeframe << " as "; + select_element << APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_TIMEFRAME; + select_element << ", " << row->id << " as "; + select_element << APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_CONTEXT_APP_INFO_ID; + + if ((row != apps_with_weights->end()) && (row == --apps_with_weights->end())) + select_element << " UNION "; + + select_elements << select_element; + } + + return select_elements.str(); +} + +void ctx::inactive_detector_storage::json_to_object(std::vector& records, + std::vector *apps_with_weights, bool result_mode) +{ + for(std::vector::iterator row = records.begin(); + row != records.end(); row++) + { + app_t app_with_weight; + if (result_mode) + { + row->get(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME, + &app_with_weight.package_name); + row->get(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_NODISPLAY, + &app_with_weight.is_nodisplay); + row->get(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ENABLED, + &app_with_weight.is_enabled); + row->get(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ATBOOT, + &app_with_weight.is_atboot); + row->get(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_PRELOADED, + &app_with_weight.is_preloaded); + row->get(NULL, APP_INACTIVE_DETECTOR_VIRTUAL_COLUMN_WEIGHT, + &app_with_weight.weight); + } + else + { + row->get(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_ID, + &app_with_weight.id); + row->get(NULL, APP_INACTIVE_DETECTOR_APPINFO_COLUMN_TIMESTAMP, + &app_with_weight.timestamp); + row->get(NULL, APP_INACTIVE_DETECTOR_VIRTUAL_COLUMN_WEIGHT, + &app_with_weight.weight); + row->get(NULL, APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_IS_ACTIVE, + &app_with_weight.is_active); + } + + apps_with_weights->push_back(app_with_weight); + } +} + +void ctx::inactive_detector_storage::on_query_result_received(unsigned int query_id, + int error, + std::vector& records) +{ + if (error != ERR_NONE) { + _E("on_query_result_received query_id:%d, error:%d", query_id, error); + return; + } + + std::vector *apps_with_weights = NULL; + if (query_id == APP_INACTIVE_QUERY_ID_GET_APPS_INACTIVE || + query_id == APP_INACTIVE_QUERY_ID_GET_APPS_ACTIVE) + { + json_to_object(records, apps_with_weights, TRUE); + } + else if (query_id == APP_INACTIVE_QUERY_ID_GET_APPS_WEIGHT) { + + json_to_object(records, apps_with_weights, FALSE); + + if (apps_with_weights->size() > 0) { + inactive_detector_classificator i_detector_classificator; + int _error = i_detector_classificator.classify(apps_with_weights); + + if(_error == ERR_NONE) + { + std::string query; + query = query_update_apps(apps_with_weights); + bool ret = db_manager::execute(APP_INACTIVE_QUERY_ID_UPDATE_CLUSTERS, + query.c_str(), + this); + _D("load visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); + } + else + { + _E("on_query_result_received/classification query_id:%d, error:%d", + query_id, _error); + } + } + } + else if (query_id == APP_INACTIVE_QUERY_ID_UPDATE_CLUSTERS) { + _D("UPDATE_CLUSTERS execute query id: %d", query_id); + } + else { + _E("on_query_result_received unknown query_id:%d", query_id); + } +} + +void ctx::inactive_detector_storage::inject_params(std::string& str, const std::string& from, const std::string& to) +{ + if(from.empty()) + return; + size_t start_pos = 0; + while((start_pos = str.find(from, start_pos)) != std::string::npos) { + str.replace(start_pos, from.length(), to); + start_pos += to.length(); + } +} + +// normalzie weights +int ctx::inactive_detector_storage::update_ranks() +{ + return ERR_NONE; +} + +int ctx::inactive_detector_storage::get_apps_info_w_weights( + double timestamp_from) +{ + std::stringstream timestamp_stream; + timestamp_stream << timestamp_from; + std::string timestamp_str = timestamp_stream.str(); + + std::string query(GET_APP_INFO_W_WEIGHT_QUERY); + std::string placeholder(APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMESTAMP); + + inject_params(query, placeholder, timestamp_str); + + bool ret = db_manager::execute(APP_INACTIVE_QUERY_ID_GET_APPS_WEIGHT, + query.c_str(), + this); + _D("load visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); + + return ERR_NONE ; +} diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_storage.h b/src/statistics/app/app_inactive_detector/inactive_detector_storage.h new file mode 100644 index 0000000..7b03c85 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_storage.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_INACTIVE_DETECTOR_STORAGE_H__ +#define __CONTEXT_INACTIVE_DETECTOR_STORAGE_H__ + +#include +#include "app_inactive_detector_types.h" +#include +#include + +namespace ctx { + + class inactive_detector_storage : public db_listener_iface + { + private: + //int type; //TODO: enum + void inject_params(std::string& str, + const std::string& from, + const std::string& to); + + void json_to_object(std::vector& records, + std::vector *apps_with_weights, bool result_mode); + + std::string query_get_apps(const char *subject, + ctx::Json filter); + + std::string query_update_apps(std::vector *apps_with_weights); + + std::string subquery_form_values(std::vector *apps_with_weights); + + void on_creation_result_received(unsigned int query_id, int error) {} + void on_insertion_result_received(unsigned int query_id, int error, int64_t row_id) {} + void on_query_result_received(unsigned int query_id, int error, std::vector& records);// {} + + public: + inactive_detector_storage(); + ~inactive_detector_storage(); + + int read(const char *subject, + ctx::Json filter); + + int update_ranks(); + int get_apps_info_w_weights(double timestamp_from); + }; /* class inactive_detector_storage */ + +} /* namespace ctx */ + +#endif /* __CONTEXT_INACTIVE_DETECTOR_STORAGE_H__ */ diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_storage_queries.h b/src/statistics/app/app_inactive_detector/inactive_detector_storage_queries.h new file mode 100644 index 0000000..469bd17 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_storage_queries.h @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_INACTIVE_DETECTOR_STORAGE_QUERIES_H__ +#define __CONTEXT_INACTIVE_DETECTOR_STORAGE_QUERIES_H__ + +#include +#include "app_inactive_detector_types.h" + +/* + +--1 calculate weights +SELECT + app_info._id, + app_info.package_name, + app_info.is_nodisplay, + app_info.is_enabled, + app_info.is_atboot, + app_info.is_preloaded, + app_info.timestamp, + + app_hist_g.weight as weight +FROM + context_app_info app_info + +INNER JOIN + + (SELECT + distinct package_name , + IFNULL((select count(package_name) from context_app_launch_log + where package_name == app_hist.package_name AND timestamp> 8640412900), 0 ) + * + IFNULL((select sum(duration) from context_app_launch_log + where package_name == app_hist.package_name AND timestamp> 8640412900) , 0) + as weight + + FROM context_app_launch_log app_hist +)app_hist_g + +ON app_hist_g.package_name += +app_info.package_name + +ORDER BY app_hist_g.weight + +*/ + +#define GET_APP_INFO_W_WEIGHT_QUERY "SELECT "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_ID ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_TYPE ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_NODISPLAY ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ENABLED ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ATBOOT ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_PRELOADED ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_TIMESTAMP ", "\ + ""\ + " " APP_INACTIVE_DETECTOR_VIRTUAL_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_VIRTUAL_COLUMN_WEIGHT \ + ""\ + " FROM " APP_INACTIVE_DETECTOR_APPINFO_TABLE " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS \ + ""\ + " INNER JOIN " \ + " (SELECT "\ + " DISTINCT " APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME "," \ + " IFNULL((SELECT COUNT(" APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME ")" \ + " FROM " APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_TABLE \ + " WHERE " APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME "==" APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME \ + " AND " \ + " " APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_TIMESTAMP " >= " APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMESTAMP \ + "), 0) " \ + " * " \ + " IFNULL((SELECT SUM(" APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_DURATION ")" \ + " FROM " APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_TABLE \ + " WHERE " APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME "==" APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME \ + " AND " \ + " " APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_COLUMN_TIMESTAMP " >= " APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMESTAMP \ + ""\ + "), 0) " \ + " as " APP_INACTIVE_DETECTOR_VIRTUAL_COLUMN_WEIGHT \ + " FROM " APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_TABLE " " APP_INACTIVE_DETECTOR_APPLAUNCH_LOG_TABLE_ALIAS \ + ") " APP_INACTIVE_DETECTOR_VIRTUAL_TABLE_ALIAS \ + " ON " APP_INACTIVE_DETECTOR_VIRTUAL_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME \ + " = " \ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME \ + " ORDER BY " APP_INACTIVE_DETECTOR_VIRTUAL_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_VIRTUAL_COLUMN_WEIGHT + +/* +--2 select inner join context_app_info +SELECT + app_info.package_name, + app_info.is_nodisplay, + app_info.is_enabled, + app_info.is_atboot, + app_info.is_preloaded, + + activity_classified.activity_rate + +FROM + context_activity_classified activity_classified +INNER JOIN + context_app_info app_info +ON activity_classified.context_app_info_id = app_info._id + +WHERE + activity_classified.is_active = 1 + AND + activity_classified.timeframe = 1 +*/ + +#define GET_APP_INFO_INACTIVE_QUERY "SELECT "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_ID ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_PACKAGE_NAME ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_NODISPLAY ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ENABLED ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_ATBOOT ", "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_IS_PRELOADED ", "\ + " "\ + " " APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_ACTIVITY_RATE " "\ + " FROM "\ + " " APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE " " APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE_ALIAS " "\ + " INNER JOIN "\ + " " APP_INACTIVE_DETECTOR_APPINFO_TABLE " " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS " "\ + " ON " APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_CONTEXT_APP_INFO_ID ""\ + " = " APP_INACTIVE_DETECTOR_APPINFO_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_APPINFO_COLUMN_ID " "\ + " WHERE "\ + APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_IS_ACTIVE ""\ + " = " APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_CLUSTER ""\ + " AND "\ + " " APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE_ALIAS "." APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_TIMEFRAME ""\ + " = " APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMEFRAME "" + +/* +--3 update ranks and clusters for each timeframe: delete all for each time frame, add new calculations for apps +DELETE FROM + context_activity_classified +WHERE + timeframe = 1 +*/ + +#define DELETE_APP_ACTIVITY_CLASSIFIED_BY_TIMEFRAME "DELETE FROM "\ + APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE \ + " WHERE "\ + " timeframe = " APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_TIMEFRAME + + +/*INSERT INTO + context_activity_classified + (is_active, + timeframe, + context_app_info_id) +SELECT + is_active, + timeframe, + context_app_info_id +FROM --make loop + ( + SELECT 1 as is_active, 1 as timeframe, 3964 as context_app_info_id + UNION + SELECT 0 as is_active, 1 as timeframe, 3964 as context_app_info_id + ) q +*/ + +#define INSERT_APP_ACTIVITY_CLASSIFIED " INSERT INTO "\ + APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_TABLE \ + "( " APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_IS_ACTIVE ", "\ + APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_TIMEFRAME ", "\ + APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_CONTEXT_APP_INFO_ID ")" \ +"SELECT " \ + APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_IS_ACTIVE "," \ + APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_TIMEFRAME ", "\ + APP_INACTIVE_DETECTOR_ACTIVITYCLASSIFIED_COLUMN_CONTEXT_APP_INFO_ID \ +"FROM"\ + "(" \ + APP_INACTIVE_DETECTOR_VALUE_PLACEHOLDER_VALUES \ + ") q" + + + +#endif /* __CONTEXT_INACTIVE_DETECTOR_STORAGE_QUERIES_H__ */ diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_weight.cpp b/src/statistics/app/app_inactive_detector/inactive_detector_weight.cpp new file mode 100644 index 0000000..5b21c1e --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_weight.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "inactive_detector_weight.h" +#include "inactive_detector_storage.h" + + +int ctx::inactive_detector_weight::request_weights( + double timestamp_from) +{ + inactive_detector_storage ids; + // query the database for the result + int error = ids.get_apps_info_w_weights(timestamp_from); + + return error; +} \ No newline at end of file diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_weight.h b/src/statistics/app/app_inactive_detector/inactive_detector_weight.h new file mode 100644 index 0000000..8e87473 --- /dev/null +++ b/src/statistics/app/app_inactive_detector/inactive_detector_weight.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2015 Samsung Electronics Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __CONTEXT_INACTIVE_DETECTOR_WEIGHT_H__ +#define __CONTEXT_INACTIVE_DETECTOR_WEIGHT_H__ + +// #include +// #include + +namespace ctx { + + class inactive_detector_weight { + public: + inactive_detector_weight() {}; + ~inactive_detector_weight() {}; + int request_weights(double timestamp_from);// {}; + }; /* class inactive_detector_weight */ + +} /* namespace ctx */ + +#endif /* __CONTEXT_INACTIVE_DETECTOR_WEIGHT_H__ */ \ No newline at end of file -- 2.7.4 From 759001f35c897966334cfc551ad358a89a93d39d Mon Sep 17 00:00:00 2001 From: Somin Kim Date: Fri, 8 Apr 2016 14:07:36 +0900 Subject: [PATCH 14/16] Modified GeofenceMonitorHandle, DeviceProviderBase to apply Tizen C++ coding style Change-Id: Ia3b663a0c1527a719d621053a35753f84a3fad9d Signed-off-by: Somin Kim --- src/device/DeviceProviderBase.cpp | 4 +-- src/place/geofence/GeofenceMonitorHandle.cpp | 44 ++++++++++++++-------------- src/place/geofence/GeofenceMonitorHandle.h | 2 ++ 3 files changed, 26 insertions(+), 24 deletions(-) diff --git a/src/device/DeviceProviderBase.cpp b/src/device/DeviceProviderBase.cpp index b3aab6e..db8e069 100644 --- a/src/device/DeviceProviderBase.cpp +++ b/src/device/DeviceProviderBase.cpp @@ -17,8 +17,8 @@ #include #include "DeviceProviderBase.h" -ctx::DeviceProviderBase::DeviceProviderBase() - : __beingSubscribed(false) +ctx::DeviceProviderBase::DeviceProviderBase() : + __beingSubscribed(false) { } diff --git a/src/place/geofence/GeofenceMonitorHandle.cpp b/src/place/geofence/GeofenceMonitorHandle.cpp index 52b4b07..cdb60ee 100644 --- a/src/place/geofence/GeofenceMonitorHandle.cpp +++ b/src/place/geofence/GeofenceMonitorHandle.cpp @@ -142,54 +142,54 @@ void ctx::GeofenceMonitorHandle::__updateState(int fenceId, geofence_state_e sta __geoStateMap[fenceId] = state; } -static const char* get_state_string(geofence_state_e state) -{ - switch (state) { - case GEOFENCE_STATE_IN: - return PLACE_GEOFENCE_IN; - case GEOFENCE_STATE_OUT: - return PLACE_GEOFENCE_OUT; - case GEOFENCE_STATE_UNCERTAIN: - return PLACE_GEOFENCE_UNCERTAIN; - default: - return PLACE_GEOFENCE_UNCERTAIN; - } -} - void ctx::GeofenceMonitorHandle::__emitStateChange() { - geofence_state_e current_state = GEOFENCE_STATE_UNCERTAIN; + geofence_state_e currentState = GEOFENCE_STATE_UNCERTAIN; int outCount = 0; for (auto it = __geoStateMap.begin(); it != __geoStateMap.end(); ++it) { if (it->second == GEOFENCE_STATE_IN) { - current_state = GEOFENCE_STATE_IN; + currentState = GEOFENCE_STATE_IN; break; } else if (it->second == GEOFENCE_STATE_OUT) { - ++ outCount; + ++outCount; } } - if (current_state != GEOFENCE_STATE_IN && outCount > 0) { - current_state = GEOFENCE_STATE_OUT; + if (currentState != GEOFENCE_STATE_IN && outCount > 0) { + currentState = GEOFENCE_STATE_OUT; } - if (current_state == __prevState) { + if (currentState == __prevState) { return; } - __prevState = current_state; + __prevState = currentState; Json option; option.set(NULL, PLACE_GEOFENCE_PLACE_ID, __placeId); Json data; data.set(NULL, PLACE_GEOFENCE_PLACE_ID, __placeId); - data.set(NULL, PLACE_GEOFENCE_EVENT, get_state_string(current_state)); + data.set(NULL, PLACE_GEOFENCE_EVENT, __getStateString(currentState)); context_manager::publish(PLACE_SUBJ_GEOFENCE, option, ERR_NONE, data); } +const char* ctx::GeofenceMonitorHandle::__getStateString(geofence_state_e state) +{ + switch (state) { + case GEOFENCE_STATE_IN: + return PLACE_GEOFENCE_IN; + case GEOFENCE_STATE_OUT: + return PLACE_GEOFENCE_OUT; + case GEOFENCE_STATE_UNCERTAIN: + return PLACE_GEOFENCE_UNCERTAIN; + default: + return PLACE_GEOFENCE_UNCERTAIN; + } +} + bool ctx::GeofenceMonitorHandle::__fenceListCb(int geofenceId, geofence_h fence, int fenceIndex, int fenceCount, void* userData) { _D("FenceID: %d, Index: %d, Count: %d", geofenceId, fenceIndex, fenceCount); diff --git a/src/place/geofence/GeofenceMonitorHandle.h b/src/place/geofence/GeofenceMonitorHandle.h index 3f15432..2dc17ff 100644 --- a/src/place/geofence/GeofenceMonitorHandle.h +++ b/src/place/geofence/GeofenceMonitorHandle.h @@ -45,6 +45,8 @@ namespace ctx { void __updateFence(int fenceId, geofence_manage_e manage); void __updateState(int fenceId, geofence_state_e state); + static const char* __getStateString(geofence_state_e state); + static bool __fenceListCb(int geofenceId, geofence_h fence, int fenceIndex, int fenceCount, void* userData); static void __fenceEventCb(int placeId, int geofenceId, geofence_manager_error_e error, geofence_manage_e manage, void* userData); static void __fenceStateCb(int geofenceId, geofence_state_e state, void* userData); -- 2.7.4 From 24fdf2e2ae3d016e904b7d3674907ce8f89312a2 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Thu, 14 Apr 2016 20:55:43 +0900 Subject: [PATCH 15/16] Replace db_manager with DatabaseManager Change-Id: Ifc736963fbe1a1cdce917c163f19c93ea01b0d5b Signed-off-by: Mu-Woong Lee --- src/custom/CustomContextProvider.cpp | 11 ++++++----- src/place/recognition/user_places/location_logger.cpp | 14 ++++++++------ src/place/recognition/user_places/places_detector.cpp | 13 ++++++------- src/place/recognition/user_places/places_detector.h | 9 +++++---- src/place/recognition/user_places/user_places.cpp | 1 - src/place/recognition/user_places/visit_detector.cpp | 5 ++--- src/place/recognition/user_places/visit_detector.h | 2 ++ src/place/recognition/user_places/wifi_logger.cpp | 12 +++++++----- src/statistics/app/active_window_monitor.cpp | 7 +++---- src/statistics/app/active_window_monitor.h | 2 ++ .../inactive_detector_storage.cpp | 12 +++++------- .../app_inactive_detector/inactive_detector_storage.h | 14 ++++++++------ src/statistics/app/db_handle.cpp | 1 - src/statistics/app/db_init.cpp | 19 ++++++++++--------- src/statistics/app/db_init.h | 12 +++++++----- src/statistics/app/install_monitor.cpp | 10 ++++++---- src/statistics/app/install_monitor.h | 9 ++++----- src/statistics/media/db_handle.cpp | 1 - src/statistics/media/media_content_monitor.cpp | 11 +++++------ src/statistics/media/media_content_monitor.h | 11 ++++++----- src/statistics/shared/db_handle_base.cpp | 9 ++++----- src/statistics/shared/db_handle_base.h | 11 ++++++----- src/statistics/social/db_handle.cpp | 1 - src/statistics/social/log_aggregator.cpp | 13 ++++++------- src/statistics/social/log_aggregator.h | 12 +++++++----- 25 files changed, 115 insertions(+), 107 deletions(-) diff --git a/src/custom/CustomContextProvider.cpp b/src/custom/CustomContextProvider.cpp index 286f28e..b6e251b 100644 --- a/src/custom/CustomContextProvider.cpp +++ b/src/custom/CustomContextProvider.cpp @@ -19,11 +19,12 @@ #include #include #include -#include +#include #include #include "CustomBase.h" static std::map __customMap; +static ctx::DatabaseManager __dbManager; static bool __isValidFact(std::string subject, ctx::Json& fact); static bool __checkValueInt(ctx::Json& tmpl, std::string key, int value); @@ -67,12 +68,12 @@ EXTAPI bool ctx::initCustomContextProvider() + "attributes TEXT DEFAULT '' NOT NULL, owner TEXT DEFAULT '' NOT NULL)"; std::vector record; - bool ret = db_manager::execute_sync(q.c_str(), &record); + bool ret = __dbManager.executeSync(q.c_str(), &record); IF_FAIL_RETURN_TAG(ret, false, _E, "Create template table failed"); // Register custom items std::string qSelect = "SELECT * FROM context_trigger_custom_template"; - ret = db_manager::execute_sync(qSelect.c_str(), &record); + ret = __dbManager.executeSync(qSelect.c_str(), &record); IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to query custom templates"); IF_FAIL_RETURN(record.size() > 0, true); @@ -123,7 +124,7 @@ EXTAPI int ctx::custom_context_provider::addItem(std::string subject, std::strin std::string q = "INSERT OR IGNORE INTO context_trigger_custom_template (subject, name, attributes, owner) VALUES ('" + subject + "', '" + name + "', '" + tmpl.str() + "', '" + owner + "'); "; std::vector record; - bool ret = db_manager::execute_sync(q.c_str(), &record); + bool ret = __dbManager.executeSync(q.c_str(), &record); IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to query custom templates"); } @@ -141,7 +142,7 @@ EXTAPI int ctx::custom_context_provider::removeItem(std::string subject) // Remove item from custom template db std::string q = "DELETE FROM context_trigger_custom_template WHERE subject = '" + subject + "'"; std::vector record; - bool ret = db_manager::execute_sync(q.c_str(), &record); + bool ret = __dbManager.executeSync(q.c_str(), &record); IF_FAIL_RETURN_TAG(ret, false, _E, "Failed to query custom templates"); return ERR_NONE; diff --git a/src/place/recognition/user_places/location_logger.cpp b/src/place/recognition/user_places/location_logger.cpp index ed9ea6f..193002c 100644 --- a/src/place/recognition/user_places/location_logger.cpp +++ b/src/place/recognition/user_places/location_logger.cpp @@ -14,14 +14,14 @@ * limitations under the License. */ -#include "location_logger.h" -#include -#include "../place_recognition_types.h" -#include #include +#include #include +#include +#include "../place_recognition_types.h" #include "user_places_params.h" #include "debug_utils.h" +#include "location_logger.h" #ifdef TIZEN_ENGINEER_MODE #define __LOCATION_CREATE_TABLE_COLUMNS \ @@ -175,7 +175,8 @@ void ctx::LocationLogger::__log(location_accessibility_state_e state) int ctx::LocationLogger::__dbCreateTable() { - bool ret = db_manager::create_table(0, LOCATION_TABLE_NAME, __LOCATION_CREATE_TABLE_COLUMNS, NULL, NULL); + ctx::DatabaseManager dbManager; + bool ret = dbManager.createTable(0, LOCATION_TABLE_NAME, __LOCATION_CREATE_TABLE_COLUMNS, NULL, NULL); _D("%s -> Table Creation Request", ret ? "SUCCESS" : "FAIL"); return 0; } @@ -193,8 +194,9 @@ int ctx::LocationLogger::__dbInsertLog(LocationEvent locationEvent) data.set(NULL, LOCATION_COLUMN_METHOD, static_cast(locationEvent.method)); #endif /* TIZEN_ENGINEER_MODE */ + ctx::DatabaseManager dbManager; int64_t rowId; - bool ret = db_manager::insert_sync(LOCATION_TABLE_NAME, data, &rowId); + bool ret = dbManager.insertSync(LOCATION_TABLE_NAME, data, &rowId); _D("%s -> DB: location table insert result", ret ? "SUCCESS" : "FAIL"); return ret; } diff --git a/src/place/recognition/user_places/places_detector.cpp b/src/place/recognition/user_places/places_detector.cpp index 88281cf..525fc43 100644 --- a/src/place/recognition/user_places/places_detector.cpp +++ b/src/place/recognition/user_places/places_detector.cpp @@ -16,7 +16,6 @@ #include #include -#include #include #include "similarity.h" #include "places_detector.h" @@ -84,7 +83,7 @@ bool ctx::PlacesDetector::onTimerExpired(int timerId) std::vector ctx::PlacesDetector::__dbGetVisits() { std::vector records; - bool ret = db_manager::execute_sync(__GET_VISITS_QUERY, &records); + bool ret = __dbManager.executeSync(__GET_VISITS_QUERY, &records); _D("load visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); return records; } @@ -92,7 +91,7 @@ std::vector ctx::PlacesDetector::__dbGetVisits() std::vector ctx::PlacesDetector::__dbGetPlaces() { std::vector records; - bool ret = db_manager::execute_sync(__GET_PLACES_QUERY, &records); + bool ret = __dbManager.executeSync(__GET_PLACES_QUERY, &records); _D("load places execute query result: %s", ret ? "SUCCESS" : "FAIL"); return records; } @@ -364,7 +363,7 @@ std::shared_ptr ctx::PlacesDetector::__graphFromVisits(const void ctx::PlacesDetector::__dbDeletePlaces() { std::vector records; - bool ret = db_manager::execute_sync(__DELETE_PLACES_QUERY, &records); + bool ret = __dbManager.executeSync(__DELETE_PLACES_QUERY, &records); _D("delete places execute query result: %s", ret ? "SUCCESS" : "FAIL"); } @@ -384,7 +383,7 @@ void ctx::PlacesDetector::__dbDeleteOlderVisitsThan(time_t threshold) query << " WHERE " << VISIT_COLUMN_END_TIME << " < " << threshold; // query << " AND 0"; // XXX: Always false condition. Uncomment it for not deleting any visit during development. std::vector records; - bool ret = db_manager::execute_sync(query.str().c_str(), &records); + bool ret = __dbManager.executeSync(query.str().c_str(), &records); _D("delete old visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); } @@ -402,7 +401,7 @@ ctx::PlacesDetector::PlacesDetector(bool testMode) : void ctx::PlacesDetector::__dbCreateTable() { - bool ret = db_manager::create_table(0, PLACE_TABLE, __PLACE_TABLE_COLUMNS); + bool ret = __dbManager.createTable(0, PLACE_TABLE, __PLACE_TABLE_COLUMNS); _D("db: place Table Creation Result: %s", ret ? "SUCCESS" : "FAIL"); } @@ -421,7 +420,7 @@ void ctx::PlacesDetector::__dbInsertPlace(const Place &place) data.set(NULL, PLACE_COLUMN_CREATE_DATE, static_cast(place.createDate)); int64_t rowId; - bool ret = db_manager::insert_sync(PLACE_TABLE, data, &rowId); + bool ret = __dbManager.insertSync(PLACE_TABLE, data, &rowId); _D("insert place execute query result: %s", ret ? "SUCCESS" : "FAIL"); } diff --git a/src/place/recognition/user_places/places_detector.h b/src/place/recognition/user_places/places_detector.h index 510aebe..6444539 100644 --- a/src/place/recognition/user_places/places_detector.h +++ b/src/place/recognition/user_places/places_detector.h @@ -17,12 +17,12 @@ #ifndef _CONTEXT_PLACE_RECOGNITION_PLACES_DETECTOR_ #define _CONTEXT_PLACE_RECOGNITION_PLACES_DETECTOR_ -#include "visit_detector.h" -#include +#include #include -#include "db_listener_iface.h" +#include +#include +#include "visit_detector.h" #include "user_places_types.h" -#include namespace ctx { @@ -30,6 +30,7 @@ namespace ctx { private: bool __testMode; + DatabaseManager __dbManager; double __doubleValueFromJson(Json &row, const char* key); Categs __visitCategsFromJson(Json &row); diff --git a/src/place/recognition/user_places/user_places.cpp b/src/place/recognition/user_places/user_places.cpp index 5357fa9..1b927c3 100644 --- a/src/place/recognition/user_places/user_places.cpp +++ b/src/place/recognition/user_places/user_places.cpp @@ -20,7 +20,6 @@ #include "user_places.h" #include "places_detector.h" #include "../place_recognition_types.h" -#include "db_mgr.h" ctx::UserPlaces::UserPlaces(PlaceRecogMode energyMode): __visitDetector(nullptr), diff --git a/src/place/recognition/user_places/visit_detector.cpp b/src/place/recognition/user_places/visit_detector.cpp index 57383ca..d63febf 100644 --- a/src/place/recognition/user_places/visit_detector.cpp +++ b/src/place/recognition/user_places/visit_detector.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include "../place_recognition_types.h" #include "visit_detector.h" @@ -361,7 +360,7 @@ std::shared_ptr ctx::VisitDetector::getVisits() void ctx::VisitDetector::__dbCreateTable() { - bool ret = db_manager::create_table(0, VISIT_TABLE, __VISIT_TABLE_COLUMNS); + bool ret = __dbManager.createTable(0, VISIT_TABLE, __VISIT_TABLE_COLUMNS); _D("db: visit Table Creation Result: %s", ret ? "SUCCESS" : "FAIL"); } @@ -411,7 +410,7 @@ int ctx::VisitDetector::__dbInsertVisit(Visit visit) __putVisitCategsToJson(visit.categs, data); int64_t rowId; - bool ret = db_manager::insert_sync(VISIT_TABLE, data, &rowId); + bool ret = __dbManager.insertSync(VISIT_TABLE, data, &rowId); _D("db: visit table insert result: %s", ret ? "SUCCESS" : "FAIL"); return ret; } diff --git a/src/place/recognition/user_places/visit_detector.h b/src/place/recognition/user_places/visit_detector.h index 757774e..ee6e7c2 100644 --- a/src/place/recognition/user_places/visit_detector.h +++ b/src/place/recognition/user_places/visit_detector.h @@ -24,6 +24,7 @@ #include #include "user_places_types.h" #include +#include #include "visit_listener_iface.h" #include "location_logger.h" #include "location_listener_iface.h" @@ -49,6 +50,7 @@ namespace ctx { int __tolerance; bool __entranceToPlace; int __periodSeconds; + DatabaseManager __dbManager; // fields that are used only in case of entrance detection std::shared_ptr __representativesMacs; // macs that represent the current place diff --git a/src/place/recognition/user_places/wifi_logger.cpp b/src/place/recognition/user_places/wifi_logger.cpp index 4c3742a..e1d1428 100644 --- a/src/place/recognition/user_places/wifi_logger.cpp +++ b/src/place/recognition/user_places/wifi_logger.cpp @@ -14,12 +14,12 @@ * limitations under the License. */ -#include "wifi_logger.h" +#include #include +#include #include "../place_recognition_types.h" -#include -#include #include "debug_utils.h" +#include "wifi_logger.h" #define __WIFI_CREATE_TABLE_COLUMNS \ WIFI_COLUMN_TIMESTAMP " timestamp NOT NULL, "\ @@ -35,7 +35,8 @@ int ctx::WifiLogger::__dbCreateTable() { - bool ret = db_manager::create_table(0, WIFI_TABLE_NAME, __WIFI_CREATE_TABLE_COLUMNS, NULL, NULL); + ctx::DatabaseManager dbManager; + bool ret = dbManager.createTable(0, WIFI_TABLE_NAME, __WIFI_CREATE_TABLE_COLUMNS, NULL, NULL); _D("Table Creation Request: %s", ret ? "SUCCESS" : "FAIL"); return ret; } @@ -43,6 +44,7 @@ int ctx::WifiLogger::__dbCreateTable() int ctx::WifiLogger::__dbInsertLogs() { if (__logs.size() > 0) { + ctx::DatabaseManager dbManager; std::stringstream query; const char* separator = " "; query << "BEGIN TRANSACTION; \ @@ -56,7 +58,7 @@ int ctx::WifiLogger::__dbInsertLogs() __logs.clear(); query << "; \ END TRANSACTION;"; - bool ret = ctx::db_manager::execute(0, query.str().c_str(), NULL); + bool ret = dbManager.execute(0, query.str().c_str(), NULL); _D("DB insert request: %s", ret ? "SUCCESS" : "FAIL"); return ret; } diff --git a/src/statistics/app/active_window_monitor.cpp b/src/statistics/app/active_window_monitor.cpp index f429a9c..2b7b1ee 100644 --- a/src/statistics/app/active_window_monitor.cpp +++ b/src/statistics/app/active_window_monitor.cpp @@ -18,7 +18,6 @@ #include #include -#include #include #include #include "../shared/system_info.h" @@ -99,7 +98,7 @@ void ctx::app_use_monitor::create_record(std::string app_id) if (ctx::system_info::get_wifi_bssid(bssid)) data.set(NULL, STATS_BSSID, bssid); - db_manager::insert(0, APP_TABLE_USAGE_LOG, data, NULL); + __dbManager.insert(0, APP_TABLE_USAGE_LOG, data, NULL); } void ctx::app_use_monitor::finish_record(std::string app_id) @@ -113,7 +112,7 @@ void ctx::app_use_monitor::finish_record(std::string app_id) "SELECT MAX(" STATS_COL_ROW_ID ") FROM " APP_TABLE_USAGE_LOG \ " WHERE " STATS_APP_ID " = '" << app_id << "'" \ " AND " STATS_DURATION " = 0)"; - db_manager::execute(0, query.str().c_str(), NULL); + __dbManager.execute(0, query.str().c_str(), NULL); } bool ctx::app_use_monitor::is_skippable(std::string app_id) @@ -145,5 +144,5 @@ void ctx::app_use_monitor::remove_expired() std::stringstream query; query << "DELETE FROM " APP_TABLE_USAGE_LOG " WHERE " \ STATS_UNIV_TIME " < strftime('%s', 'now') - " << LOG_RETENTION_PERIOD; - db_manager::execute(0, query.str().c_str(), NULL); + __dbManager.execute(0, query.str().c_str(), NULL); } diff --git a/src/statistics/app/active_window_monitor.h b/src/statistics/app/active_window_monitor.h index 7b5e3a0..d86a141 100644 --- a/src/statistics/app/active_window_monitor.h +++ b/src/statistics/app/active_window_monitor.h @@ -20,6 +20,7 @@ #include #include #include +#include namespace ctx { @@ -28,6 +29,7 @@ namespace ctx { int64_t signal_id; int last_cleanup_time; DBusSignalWatcher __dbusWatcher; + DatabaseManager __dbManager; bool start_logging(void); void stop_logging(void); diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_storage.cpp b/src/statistics/app/app_inactive_detector/inactive_detector_storage.cpp index c2207a6..0feb2b7 100644 --- a/src/statistics/app/app_inactive_detector/inactive_detector_storage.cpp +++ b/src/statistics/app/app_inactive_detector/inactive_detector_storage.cpp @@ -24,12 +24,10 @@ #include "inactive_detector_storage_queries.h" #include "inactive_detector_classificator.h" #include "app_inactive_detector_types.h" -#include "db_mgr.h" -#include /*int ctx::inactive_detector_storage::create_table() { - bool ret = db_manager::create_table(0, WIFI_TABLE_NAME, WIFI_CREATE_TABLE_COLUMNS, NULL, NULL); + bool ret = __dbManager.create_table(0, WIFI_TABLE_NAME, WIFI_CREATE_TABLE_COLUMNS, NULL, NULL); _D("Table Creation Request: %s", ret ? "SUCCESS" : "FAIL"); return ret; }*/ @@ -46,7 +44,7 @@ int ctx::inactive_detector_storage::read( IF_FAIL_RETURN(!query.empty(), ERR_OPERATION_FAILED); - bool ret = db_manager::execute( + bool ret = __dbManager.execute( STR_EQ(subject, APP_INACTIVE_SUBJ_GET_APPS_INACTIVE) ? APP_INACTIVE_QUERY_ID_GET_APPS_INACTIVE : APP_INACTIVE_QUERY_ID_GET_APPS_ACTIVE, @@ -165,7 +163,7 @@ void ctx::inactive_detector_storage::json_to_object(std::vector& records, } } -void ctx::inactive_detector_storage::on_query_result_received(unsigned int query_id, +void ctx::inactive_detector_storage::onExecuted(unsigned int query_id, int error, std::vector& records) { @@ -192,7 +190,7 @@ void ctx::inactive_detector_storage::on_query_result_received(unsigned int query { std::string query; query = query_update_apps(apps_with_weights); - bool ret = db_manager::execute(APP_INACTIVE_QUERY_ID_UPDATE_CLUSTERS, + bool ret = __dbManager.execute(APP_INACTIVE_QUERY_ID_UPDATE_CLUSTERS, query.c_str(), this); _D("load visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); @@ -241,7 +239,7 @@ int ctx::inactive_detector_storage::get_apps_info_w_weights( inject_params(query, placeholder, timestamp_str); - bool ret = db_manager::execute(APP_INACTIVE_QUERY_ID_GET_APPS_WEIGHT, + bool ret = __dbManager.execute(APP_INACTIVE_QUERY_ID_GET_APPS_WEIGHT, query.c_str(), this); _D("load visits execute query result: %s", ret ? "SUCCESS" : "FAIL"); diff --git a/src/statistics/app/app_inactive_detector/inactive_detector_storage.h b/src/statistics/app/app_inactive_detector/inactive_detector_storage.h index 7b03c85..6292768 100644 --- a/src/statistics/app/app_inactive_detector/inactive_detector_storage.h +++ b/src/statistics/app/app_inactive_detector/inactive_detector_storage.h @@ -20,11 +20,11 @@ #include #include "app_inactive_detector_types.h" #include -#include +#include namespace ctx { - class inactive_detector_storage : public db_listener_iface + class inactive_detector_storage : public IDatabaseListener { private: //int type; //TODO: enum @@ -42,10 +42,12 @@ namespace ctx { std::string subquery_form_values(std::vector *apps_with_weights); - void on_creation_result_received(unsigned int query_id, int error) {} - void on_insertion_result_received(unsigned int query_id, int error, int64_t row_id) {} - void on_query_result_received(unsigned int query_id, int error, std::vector& records);// {} - + void onTableCreated(unsigned int query_id, int error) {} + void onInserted(unsigned int query_id, int error, int64_t row_id) {} + void onExecuted(unsigned int query_id, int error, std::vector& records); + + DatabaseManager __dbManager; + public: inactive_detector_storage(); ~inactive_detector_storage(); diff --git a/src/statistics/app/db_handle.cpp b/src/statistics/app/db_handle.cpp index fdabb05..bddb70f 100644 --- a/src/statistics/app/db_handle.cpp +++ b/src/statistics/app/db_handle.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include "app_stats_types.h" #include "db_handle.h" diff --git a/src/statistics/app/db_init.cpp b/src/statistics/app/db_init.cpp index 1701585..1b2d0df 100644 --- a/src/statistics/app/db_init.cpp +++ b/src/statistics/app/db_init.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include "app_stats_types.h" #include "db_init.h" @@ -38,16 +37,16 @@ void ctx::app_db_initializer::create_table() static bool done = false; IF_FAIL_VOID(!done); - db_manager::create_table(0, APP_TABLE_USAGE_LOG, APP_TABLE_USAGE_LOG_COLUMNS, NULL, NULL); - db_manager::create_table(0, APP_TABLE_REMOVABLE_APP, APP_TABLE_REMOVABLE_APP_COLUMNS, NULL, NULL); - db_manager::execute(0, APP_TEMP_USAGE_FREQ_SQL, NULL); + __dbManager.createTable(0, APP_TABLE_USAGE_LOG, APP_TABLE_USAGE_LOG_COLUMNS, NULL, NULL); + __dbManager.createTable(0, APP_TABLE_REMOVABLE_APP, APP_TABLE_REMOVABLE_APP_COLUMNS, NULL, NULL); + __dbManager.execute(0, APP_TEMP_USAGE_FREQ_SQL, NULL); done = true; } void ctx::app_db_initializer::check_app_list() { - db_manager::execute(EMPTY_CHECKER_QID, "SELECT * FROM " APP_TABLE_REMOVABLE_APP " LIMIT 1", this); + __dbManager.execute(EMPTY_CHECKER_QID, "SELECT * FROM " APP_TABLE_REMOVABLE_APP " LIMIT 1", this); } void ctx::app_db_initializer::duplicate_app_list() @@ -79,19 +78,21 @@ bool ctx::app_db_initializer::package_info_cb(package_info_h package_info, void bool ctx::app_db_initializer::app_info_cb(package_info_app_component_type_e comp_type, const char *app_id, void *user_data) { Json data; + DatabaseManager dbManager; + data.set(NULL, STATS_APP_ID, app_id); - return db_manager::insert(0, APP_TABLE_REMOVABLE_APP, data, NULL); + return dbManager.insert(0, APP_TABLE_REMOVABLE_APP, data, NULL); } -void ctx::app_db_initializer::on_creation_result_received(unsigned int query_id, int error) +void ctx::app_db_initializer::onTableCreated(unsigned int query_id, int error) { } -void ctx::app_db_initializer::on_insertion_result_received(unsigned int query_id, int error, int64_t row_id) +void ctx::app_db_initializer::onInserted(unsigned int query_id, int error, int64_t row_id) { } -void ctx::app_db_initializer::on_query_result_received(unsigned int query_id, int error, std::vector& records) +void ctx::app_db_initializer::onExecuted(unsigned int query_id, int error, std::vector& records) { if (query_id != EMPTY_CHECKER_QID) { _E("Unknown Query ID: %d", query_id); diff --git a/src/statistics/app/db_init.h b/src/statistics/app/db_init.h index 2bd20ad..cd5b39e 100644 --- a/src/statistics/app/db_init.h +++ b/src/statistics/app/db_init.h @@ -18,23 +18,25 @@ #define __CONTEXT_APP_DB_INITIALIZER_H__ #include -#include +#include namespace ctx { - class app_db_initializer : public db_listener_iface { + class app_db_initializer : public IDatabaseListener { private: void create_table(); void check_app_list(); void duplicate_app_list(); - void on_creation_result_received(unsigned int query_id, int error); - void on_insertion_result_received(unsigned int query_id, int error, int64_t row_id); - void on_query_result_received(unsigned int query_id, int error, std::vector& records); + void onTableCreated(unsigned int query_id, int error); + void onInserted(unsigned int query_id, int error, int64_t row_id); + void onExecuted(unsigned int query_id, int error, std::vector& records); static bool package_info_cb(package_info_h package_info, void *user_data); static bool app_info_cb(package_info_app_component_type_e comp_type, const char *app_id, void *user_data); + DatabaseManager __dbManager; + public: app_db_initializer(); ~app_db_initializer(); diff --git a/src/statistics/app/install_monitor.cpp b/src/statistics/app/install_monitor.cpp index d4b92ce..4efbb09 100644 --- a/src/statistics/app/install_monitor.cpp +++ b/src/statistics/app/install_monitor.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include "app_stats_types.h" #include "install_monitor.h" @@ -80,13 +80,15 @@ void ctx::app_install_monitor::package_event_cb(const char *type, const char *pa bool ctx::app_install_monitor::app_info_cb(package_info_app_component_type_e comp_type, const char *app_id, void *user_data) { + DatabaseManager dbManager; + if (last_event_type == PACKAGE_MANAGER_EVENT_TYPE_INSTALL) { Json data; data.set(NULL, STATS_APP_ID, app_id); - db_manager::insert(0, APP_TABLE_REMOVABLE_APP, data, NULL); + dbManager.insert(0, APP_TABLE_REMOVABLE_APP, data, NULL); } else if (last_event_type == PACKAGE_MANAGER_EVENT_TYPE_UNINSTALL) { - db_manager::execute(0, create_deletion_query(APP_TABLE_REMOVABLE_APP, app_id).c_str(), NULL); - db_manager::execute(0, create_deletion_query(APP_TABLE_USAGE_LOG, app_id).c_str(), NULL); + dbManager.execute(0, create_deletion_query(APP_TABLE_REMOVABLE_APP, app_id).c_str(), NULL); + dbManager.execute(0, create_deletion_query(APP_TABLE_USAGE_LOG, app_id).c_str(), NULL); } return true; diff --git a/src/statistics/app/install_monitor.h b/src/statistics/app/install_monitor.h index cba445d..73b374d 100644 --- a/src/statistics/app/install_monitor.h +++ b/src/statistics/app/install_monitor.h @@ -18,20 +18,19 @@ #define __CONTEXT_APP_INSTALL_MONITOR_H__ #include -#include namespace ctx { - class app_install_monitor : public db_listener_iface { + class app_install_monitor : public IDatabaseListener { private: package_manager_h pkgmgr_h; bool start_monitoring(); void stop_monitoring(); - void on_creation_result_received(unsigned int query_id, int error) {} - void on_insertion_result_received(unsigned int query_id, int error, int64_t row_id) {} - void on_query_result_received(unsigned int query_id, int error, std::vector& records) {} + void onTableCreated(unsigned int query_id, int error) {} + void onInserted(unsigned int query_id, int error, int64_t row_id) {} + void onExecuted(unsigned int query_id, int error, std::vector& records) {} static std::string create_deletion_query(const char* table_name, const char* app_id); static void package_event_cb(const char *type, const char *package, package_manager_event_type_e event_type, package_manager_event_state_e event_state, int progress, package_manager_error_e error, void *user_data); diff --git a/src/statistics/media/db_handle.cpp b/src/statistics/media/db_handle.cpp index 81a1d80..9561f69 100644 --- a/src/statistics/media/db_handle.cpp +++ b/src/statistics/media/db_handle.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include "../shared/system_info.h" #include "media_stats_types.h" #include "db_handle.h" diff --git a/src/statistics/media/media_content_monitor.cpp b/src/statistics/media/media_content_monitor.cpp index 156d9b5..6ae9f13 100644 --- a/src/statistics/media/media_content_monitor.cpp +++ b/src/statistics/media/media_content_monitor.cpp @@ -16,7 +16,6 @@ #include #include -#include #include "../shared/system_info.h" #include "media_stats_types.h" #include "db_handle.h" @@ -29,8 +28,8 @@ ctx::media_content_monitor::media_content_monitor() : started(false) , last_cleanup_time(0) { - db_manager::create_table(0, MEDIA_TABLE_NAME, MEDIA_TABLE_COLUMNS, NULL, NULL); - db_manager::execute(0, MEDIA_PLAYCOUNT_TABLE_SCHEMA, NULL); + __dbManager.createTable(0, MEDIA_TABLE_NAME, MEDIA_TABLE_COLUMNS, NULL, NULL); + __dbManager.execute(0, MEDIA_PLAYCOUNT_TABLE_SCHEMA, NULL); started = start_monitoring(); } @@ -118,10 +117,10 @@ void ctx::media_content_monitor::update_play_count(const char *uuid, int type, i "SELECT MediaType FROM Log_MediaPlayCount" \ " WHERE UUID = '" << uuid << "' AND Diff > 0;"; - db_manager::execute(0, query.str().c_str(), this); + __dbManager.execute(0, query.str().c_str(), this); } -void ctx::media_content_monitor::on_query_result_received(unsigned int query_id, int error, std::vector& records) +void ctx::media_content_monitor::onExecuted(unsigned int query_id, int error, std::vector& records) { IF_FAIL_VOID(!records.empty()); @@ -146,5 +145,5 @@ void ctx::media_content_monitor::insert_log(int media_type) data.set(NULL, STATS_MEDIA_VOLUME, media_volume); } - db_manager::insert(0, MEDIA_TABLE_NAME, data, NULL); + __dbManager.insert(0, MEDIA_TABLE_NAME, data, NULL); } diff --git a/src/statistics/media/media_content_monitor.h b/src/statistics/media/media_content_monitor.h index 4bd97db..260f84f 100644 --- a/src/statistics/media/media_content_monitor.h +++ b/src/statistics/media/media_content_monitor.h @@ -19,14 +19,15 @@ #include #include -#include +#include namespace ctx { - class media_content_monitor : public db_listener_iface { + class media_content_monitor : public IDatabaseListener { private: bool started; int last_cleanup_time; + DatabaseManager __dbManager; bool start_monitoring(); void stop_monitoring(); @@ -35,9 +36,9 @@ namespace ctx { void update_play_count(const char *uuid, int type, int count); void insert_log(int media_type); - void on_creation_result_received(unsigned int query_id, int error) {} - void on_insertion_result_received(unsigned int query_id, int error, int64_t row_id) {} - void on_query_result_received(unsigned int query_id, int error, std::vector& records); + void onTableCreated(unsigned int query_id, int error) {} + void onInserted(unsigned int query_id, int error, int64_t row_id) {} + void onExecuted(unsigned int query_id, int error, std::vector& records); static void on_media_content_db_updated(media_content_error_e error, int pid, media_content_db_update_item_type_e update_item, diff --git a/src/statistics/shared/db_handle_base.cpp b/src/statistics/shared/db_handle_base.cpp index 159c5ca..e8d60d7 100644 --- a/src/statistics/shared/db_handle_base.cpp +++ b/src/statistics/shared/db_handle_base.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include "common_types.h" #include "db_handle_base.h" @@ -43,7 +42,7 @@ int ctx::stats_db_handle_base::generate_qid() bool ctx::stats_db_handle_base::execute_query(const char* subject, ctx::Json filter, const char* query) { - bool ret = db_manager::execute(generate_qid(), query, this); + bool ret = __dbManager.execute(generate_qid(), query, this); IF_FAIL_RETURN(ret, false); req_subject = subject; @@ -188,11 +187,11 @@ std::string ctx::stats_db_handle_base::create_sql_common_setting(ctx::Json filte return query.str(); } -void ctx::stats_db_handle_base::on_creation_result_received(unsigned int query_id, int error) +void ctx::stats_db_handle_base::onTableCreated(unsigned int query_id, int error) { } -void ctx::stats_db_handle_base::on_insertion_result_received(unsigned int query_id, int error, int64_t row_id) +void ctx::stats_db_handle_base::onInserted(unsigned int query_id, int error, int64_t row_id) { delete this; } @@ -207,7 +206,7 @@ void ctx::stats_db_handle_base::json_vector_to_array(std::vector &vec_json } } -void ctx::stats_db_handle_base::on_query_result_received(unsigned int query_id, int error, std::vector& records) +void ctx::stats_db_handle_base::onExecuted(unsigned int query_id, int error, std::vector& records) { if (is_trigger_item) { if (records.size() == 1) { diff --git a/src/statistics/shared/db_handle_base.h b/src/statistics/shared/db_handle_base.h index 7c88380..8c9a201 100644 --- a/src/statistics/shared/db_handle_base.h +++ b/src/statistics/shared/db_handle_base.h @@ -19,14 +19,15 @@ #include #include -#include +#include namespace ctx { - class stats_db_handle_base : public db_listener_iface { + class stats_db_handle_base : public IDatabaseListener { protected: bool is_trigger_item; std::string req_subject; ctx::Json req_filter; + DatabaseManager __dbManager; stats_db_handle_base(); ~stats_db_handle_base(); @@ -42,9 +43,9 @@ namespace ctx { private: void json_vector_to_array(std::vector &vec_json, ctx::Json &json_result); - void on_creation_result_received(unsigned int query_id, int error); - void on_insertion_result_received(unsigned int query_id, int error, int64_t row_id); - void on_query_result_received(unsigned int query_id, int error, std::vector& records); + void onTableCreated(unsigned int query_id, int error); + void onInserted(unsigned int query_id, int error, int64_t row_id); + void onExecuted(unsigned int query_id, int error, std::vector& records); }; } diff --git a/src/statistics/social/db_handle.cpp b/src/statistics/social/db_handle.cpp index 1199a32..6dfa677 100644 --- a/src/statistics/social/db_handle.cpp +++ b/src/statistics/social/db_handle.cpp @@ -18,7 +18,6 @@ #include #include #include -#include #include "social_stats_types.h" #include "db_handle.h" diff --git a/src/statistics/social/log_aggregator.cpp b/src/statistics/social/log_aggregator.cpp index fadd8cf..9d58c1a 100644 --- a/src/statistics/social/log_aggregator.cpp +++ b/src/statistics/social/log_aggregator.cpp @@ -16,7 +16,6 @@ #include #include -#include #include #include "social_stats_types.h" #include "log_aggregator.h" @@ -39,8 +38,8 @@ void ctx::contact_log_aggregator::create_table() static bool done = false; IF_FAIL_VOID(!done); - db_manager::create_table(0, SOCIAL_TABLE_CONTACT_LOG, SOCIAL_TABLE_CONTACT_LOG_COLUMNS, NULL, NULL); - db_manager::execute(0, SOCIAL_TEMP_CONTACT_FREQ_SQL, NULL); + __dbManager.createTable(0, SOCIAL_TABLE_CONTACT_LOG, SOCIAL_TABLE_CONTACT_LOG_COLUMNS, NULL, NULL); + __dbManager.execute(0, SOCIAL_TEMP_CONTACT_FREQ_SQL, NULL); done = true; } @@ -53,13 +52,13 @@ bool ctx::contact_log_aggregator::onTimerExpired(int timer) void ctx::contact_log_aggregator::aggregate_contact_log() { - db_manager::execute(0, + __dbManager.execute(0, "SELECT IFNULL(MAX(" STATS_UNIV_TIME "),0) AS " STATS_LAST_TIME \ ", (strftime('%s', 'now', 'localtime')) - (strftime('%s', 'now')) AS " TIME_DIFFERENCE \ " FROM " SOCIAL_TABLE_CONTACT_LOG, this); } -void ctx::contact_log_aggregator::on_query_result_received(unsigned int query_id, int error, std::vector& records) +void ctx::contact_log_aggregator::onExecuted(unsigned int query_id, int error, std::vector& records) { IF_FAIL_VOID_TAG(!records.empty(), _E, "Invalid query result"); @@ -154,7 +153,7 @@ void ctx::contact_log_aggregator::insert_contact_log_list(contacts_list_h list) data.set(NULL, STATS_UNIV_TIME, accesstime); data.set(NULL, STATS_LOCAL_TIME, accesstime + time_diff); - db_manager::insert(0, SOCIAL_TABLE_CONTACT_LOG, data, NULL); + __dbManager.insert(0, SOCIAL_TABLE_CONTACT_LOG, data, NULL); } while(contacts_list_next(list) == CONTACTS_ERROR_NONE); } @@ -164,5 +163,5 @@ void ctx::contact_log_aggregator::remove_expired_log() std::stringstream query; query << "DELETE FROM " SOCIAL_TABLE_CONTACT_LOG " WHERE " \ STATS_UNIV_TIME " < strftime('%s', 'now') - " << LOG_RETENTION_PERIOD; - db_manager::execute(0, query.str().c_str(), NULL); + __dbManager.execute(0, query.str().c_str(), NULL); } diff --git a/src/statistics/social/log_aggregator.h b/src/statistics/social/log_aggregator.h index 6f7583f..a73c44b 100644 --- a/src/statistics/social/log_aggregator.h +++ b/src/statistics/social/log_aggregator.h @@ -18,16 +18,18 @@ #define __CONTEXT_SOCIAL_CONTACT_LOG_AGGREGATOR_H__ #include -#include +#include #include namespace ctx { - class contact_log_aggregator : public db_listener_iface, public ITimerListener { + class contact_log_aggregator : public IDatabaseListener, public ITimerListener { private: int timer_id; int time_diff; TimerManager __timerManager; + DatabaseManager __dbManager; + void create_table(); void get_updated_contact_log_list(int last_time, contacts_list_h *list); void insert_contact_log_list(contacts_list_h list); @@ -40,9 +42,9 @@ namespace ctx { void aggregate_contact_log(); - void on_creation_result_received(unsigned int query_id, int error) {} - void on_insertion_result_received(unsigned int query_id, int error, int64_t row_id) {} - void on_query_result_received(unsigned int query_id, int error, std::vector& records); + void onTableCreated(unsigned int queryId, int error) {} + void onInserted(unsigned int queryId, int error, int64_t rowId) {} + void onExecuted(unsigned int query_id, int error, std::vector& records); bool onTimerExpired(int timer_id); }; /* class phone_contact_log_aggregator */ -- 2.7.4 From dc80947d59ea52c2ab8d04a914562ee94b6b54f9 Mon Sep 17 00:00:00 2001 From: Mu-Woong Lee Date: Fri, 15 Apr 2016 15:42:07 +0900 Subject: [PATCH 16/16] Remove unnecessary explicit dependency to libcontext-shared Change-Id: I93b403dd61a6febcd0717c7952e5366a883c0170 Signed-off-by: Mu-Woong Lee --- CMakeLists.txt | 2 +- packaging/context-provider.spec | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 42e2659..913174a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,7 @@ ADD_DEFINITIONS(-O2 -Wall -fPIC -fdata-sections -ffunction-sections -fvisibility SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fPIC -Wl,--as-needed -Wl,--gc-section -Wl,--print-gc-section") # Base Dependency -SET(dependencies libcontext-shared libcontext-server) +SET(dependencies libcontext-server) # Profiles IF("${PROFILE}" STREQUAL "mobile") diff --git a/packaging/context-provider.spec b/packaging/context-provider.spec index a259bde..7068f1e 100644 --- a/packaging/context-provider.spec +++ b/packaging/context-provider.spec @@ -11,7 +11,6 @@ Source0: %{name}-%{version}.tar.gz BuildRequires: cmake -BuildRequires: pkgconfig(libcontext-shared) BuildRequires: pkgconfig(libcontext-server) BuildRequires: pkgconfig(vconf) BuildRequires: pkgconfig(capi-system-info) -- 2.7.4