_I(BLUE("Read"));
_J("Option", option);
- std::vector<std::shared_ptr<ctx::Place>> places = engine.get_places();
- Json dataRead = UserPlaces::compose_json(places);
+ std::vector<std::shared_ptr<ctx::Place>> 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.
* 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 <ContextProviderBase.h>
#include "place_recognition_types.h"
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_RECOGNITION_H__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_H_ */
* 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"
#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_ */
#include "debug_utils.h"
#include <types_internal.h>
-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) {
* 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 <string>
#include <ctime>
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_ */
#include <iostream>
#include <fstream>
-const std::string ctx::Gmap::html_header = R"(
+const std::string ctx::Gmap::__htmlHeader = R"(
<!DOCTYPE html>
<html>
<head>
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);
</html>
)";
-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";
}
}
-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<std::shared_ptr<ctx::Place>>& places, std::ostream& out)
+void ctx::Gmap::__html2Stream(const std::vector<std::shared_ptr<ctx::Place>>& places, std::ostream& out)
{
- out << html_header;
+ out << __htmlHeader;
for (std::shared_ptr<ctx::Place> place : places) {
- place_marker_to_stream(*place, out);
+ __placeMarker2Stream(*place, out);
}
- out << html_footer;
+ out << __htmlFooter;
}
-void ctx::Gmap::write_map(const std::vector<std::shared_ptr<ctx::Place>>& places)
+void ctx::Gmap::writeMap(const std::vector<std::shared_ptr<ctx::Place>>& places)
{
std::ofstream out(GMAP_FILE);
- html_to_stream(places, out);
+ __html2Stream(places, out);
}
* 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"
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<std::shared_ptr<Place>>& 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<std::shared_ptr<Place>>& places, std::ostream& out);
public:
- static void write_map(const std::vector<std::shared_ptr<Place>>& places);
+ static void writeMap(const std::vector<std::shared_ptr<Place>>& places);
}; /* class Gmap */
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_STATUS_VISIT_GMAP_H__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_GMAP_H_ */
#include <queue>
#include "graph.h"
-std::shared_ptr<ctx::components_t> ctx::connected_components(graph_t &graph)
+std::shared_ptr<ctx::graph::Components> ctx::graph::connectedComponents(Graph &graph)
{
- std::shared_ptr<components_t> ccs = std::make_shared<components_t>();
+ std::shared_ptr<Components> ccs = std::make_shared<Components>();
std::set<int> fringe;
- for (node_t i = 0; i < static_cast<node_t>(graph.size()); i++) {
+ for (Node i = 0; i < static_cast<Node>(graph.size()); i++) {
if (!graph[i]) {
continue;
}
// neighbourhood of node i exists (was not removed)
- std::shared_ptr<component_t> c = std::make_shared<component_t>();
+ std::shared_ptr<Component> c = std::make_shared<Component>();
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<nhood_t> curr_nhood = graph[curr_node];
- for (node_t nhood_node : *curr_nhood) {
+ std::shared_ptr<NeighbourNodes> 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);
}
* 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 <memory>
#include <vector>
namespace ctx {
- typedef int node_t;
- typedef std::set<node_t> nhood_t; // neighbouring nodes
- typedef std::vector<std::shared_ptr<nhood_t>> graph_t;
- typedef std::set<node_t> component_t;
- typedef std::vector<std::shared_ptr<component_t>> components_t;
+namespace graph {
+
+ typedef int Node;
+ typedef std::set<Node> NeighbourNodes;
+ typedef std::vector<std::shared_ptr<NeighbourNodes>> Graph;
+ typedef std::set<Node> Component;
+ typedef std::vector<std::shared_ptr<Component>> Components;
/*
* make connected components of a given graph
* caution: the graph will be changed (its nodes will be cleared)
*/
- std::shared_ptr<components_t> connected_components(graph_t &graph);
+ std::shared_ptr<Components> connectedComponents(Graph &graph);
+
+} /* namespace graph */
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_STATUS_GRAPH_H__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_GRAPH_H_ */
* 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"
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_ */
#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:
}
} 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:
}
} 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:
}
-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
}
}
-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);
data.set(NULL, LOCATION_COLUMN_ACCURACY, location_event.coordinates.accuracy);
data.set(NULL, LOCATION_COLUMN_TIMESTAMP, static_cast<int>(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<int>(location_event.method));
#endif /* TIZEN_ENGINEER_MODE */
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);
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);
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();
}
}
* 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 <locations.h>
#include <TimerManager.h>
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_ */
ctx::num_t ctx::MahalModel::dist(const std::vector<ctx::num_t> &v)
{
- return dist_s(v, mean, sigma);
+ return dist_s(v, __mean, __sigma);
}
* 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 <vector>
#include "user_places_types.h"
class MahalModel {
private:
- std::vector<num_t> mean;
- std::vector<num_t> sigma; // represents square matrix row-wise
+ std::vector<num_t> __mean;
+ std::vector<num_t> __sigma; // represents square matrix row-wise
public:
static num_t dist_s(const std::vector<num_t> &v1, const std::vector<num_t> &v2, const std::vector<num_t> &m);
- MahalModel(std::vector<num_t> mean_, std::vector<num_t> sigma_) : mean(mean_), sigma(sigma_) { }
+ MahalModel(std::vector<num_t> mean, std::vector<num_t> sigma) :
+ __mean(mean),
+ __sigma(sigma) { }
num_t dist(const std::vector<num_t> &v);
}; /* class MahalModel */
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_STATUS_MAHAL_H__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_MAHAL_H_ */
* 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 <vector>
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_STATUS_MEDIAN__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_MEDIAN_ */
#include "piecewise_lin.h"
#include <types_internal.h>
-ctx::PiecewiseLin::PiecewiseLin(std::vector<num_t> _xs, std::vector<num_t> _vs)
- : n(0)
+ctx::PiecewiseLin::PiecewiseLin(std::vector<num_t> xs, std::vector<num_t> 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;
}
* 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"
class PiecewiseLin {
private:
- std::vector<num_t> xs; // nodes
- std::vector<num_t> vs; // values in nodes
- size_t n;
+ std::vector<num_t> __xs; // nodes
+ std::vector<num_t> __vs; // values in nodes
+ size_t __n;
public:
- PiecewiseLin(std::vector<num_t> _xs, std::vector<num_t> _vs);
- num_t val(num_t x);
+ PiecewiseLin(std::vector<num_t> xs, std::vector<num_t> vs);
+ num_t value(num_t x);
}; /* PiecewiseLin */
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_STATUS_PIECEWISE_LIN__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_PIECEWISE_LIN_ */
#include <algorithm>
#include <types_internal.h>
-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;
/*
* 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);
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<place_categ_id_e> categ_ids = {
+ const std::vector<PlaceCategId> 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<num_t> categ_vector = categ_vector_from_visits(visits, categ_id);
+ for (PlaceCategId categ_id : categ_ids) {
+ std::vector<num_t> categ_vector = categVectorFromVisits(visits, categ_id);
num_t score = median(categ_vector);
sum_score += score;
if (score > max_score) {
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::num_t> ctx::PlaceCateger::categ_vector_from_visits(const ctx::visits_t &visits, place_categ_id_e categ_id)
+std::vector<ctx::num_t> ctx::PlaceCateger::categVectorFromVisits(const ctx::visits_t &visits, PlaceCategId categ_id)
{
std::vector<ctx::num_t> vec;
for (auto &visit : visits) {
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";
* 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 <utility>
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<ctx::num_t> 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<ctx::num_t> 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_ */
#include <types_internal.h>
#include <db_mgr.h>
#include <Json.h>
-#include "similar.h"
+#include "similarity.h"
#include "places_detector.h"
#include "place_categer.h"
#include "graph.h"
bool ctx::PlacesDetector::onTimerExpired(int timerId)
{
_D("");
- db_delete_places();
- db_delete_old_visits();
- std::vector<Json> records = db_get_visits();
- visits_t visits = visits_from_jsons(records);
- process_visits(visits);
+ __dbDeletePlaces();
+ __dbDeleteOldVisits();
+ std::vector<Json> records = __dbGetVisits();
+ visits_t visits = __visitsFromJsons(records);
+ __processVisits(visits);
return true;
}
-std::vector<ctx::Json> ctx::PlacesDetector::db_get_visits()
+std::vector<ctx::Json> ctx::PlacesDetector::__dbGetVisits()
{
std::vector<Json> records;
bool ret = db_manager::execute_sync(GET_VISITS_QUERY, &records);
return records;
}
-std::vector<ctx::Json> ctx::PlacesDetector::db_get_places()
+std::vector<ctx::Json> ctx::PlacesDetector::__dbGetPlaces()
{
std::vector<Json> records;
bool ret = db_manager::execute_sync(GET_PLACES_QUERY, &records);
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;
std::stringstream mac_set_ss;
mac_set_ss << mac_set_string;
- std::shared_ptr<mac_set_t> mac_set = std::make_shared<mac_set_t>();
- mac_set_ss >> *mac_set;
+ std::shared_ptr<mac_set_t> macSet = std::make_shared<mac_set_t>();
+ 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;
return visit;
}
-ctx::visits_t ctx::PlacesDetector::visits_from_jsons(std::vector<Json>& records)
+ctx::visits_t ctx::PlacesDetector::__visitsFromJsons(std::vector<Json>& 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::Place> ctx::PlacesDetector::place_from_json(Json &row)
+std::shared_ptr<ctx::Place> ctx::PlacesDetector::__placeFromJson(Json &row)
{
std::shared_ptr<Place> place = std::make_shared<Place>();
{ // 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<place_categ_id_e>(categ_id);
+ place->categ_id = static_cast<PlaceCategId>(categ_id);
}
row.get(NULL, PLACE_COLUMN_NAME, &(place->name));
row.get(NULL, PLACE_COLUMN_WIFI_APS, &(place->wifi_aps));
return place;
}
-std::vector<std::shared_ptr<ctx::Place>> ctx::PlacesDetector::places_from_jsons(std::vector<Json>& records)
+std::vector<std::shared_ptr<ctx::Place>> ctx::PlacesDetector::__placesFromJsons(std::vector<Json>& records)
{
std::vector<std::shared_ptr<Place>> places;
_D("db_result: number of all places: %d", records.size());
for (Json &row : records) {
- std::shared_ptr<Place> place = place_from_json(row);
+ std::shared_ptr<Place> 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);
}
}
-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<std::shared_ptr<Place>> new_detected_places;
+ _D("__testMode = %d", __testMode);
+ auto components = __mergeVisits(visits);
+ std::vector<std::shared_ptr<Place>> newDetectedPlaces;
#ifdef TIZEN_ENGINEER_MODE
std::vector<visits_t> places_visits; // TODO: remove from final solution.
#endif /* TIZEN_ENGINEER_MODE */
- for (std::shared_ptr<component_t> component : *components) {
+ for (std::shared_ptr<graph::Component> 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<visits_t> merged = std::make_shared<visits_t>();
- for (node_t i : *component) {
+ for (graph::Node i : *component) {
merged->push_back(visits[i]);
}
- std::shared_ptr<Place> place = place_from_merged(*merged);
+ std::shared_ptr<Place> 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);
#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 */
}
/*
* Replace old places by new ones.
*/
-void ctx::PlacesDetector::detected_places_update(std::vector<std::shared_ptr<Place>> &new_places)
+void ctx::PlacesDetector::__detectedPlacesUpdate(std::vector<std::shared_ptr<Place>> &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<double> latitudes;
std::vector<double> 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);
}
}
-std::shared_ptr<ctx::Place> ctx::PlacesDetector::place_from_merged(visits_t &merged_visits)
+std::shared_ptr<ctx::Place> ctx::PlacesDetector::__placeFromMergedVisits(visits_t &merged_visits)
{
std::shared_ptr<Place> place = std::make_shared<Place>();
place->create_date = std::time(nullptr);
- std::vector<std::shared_ptr<mac_set_t>> mac_sets;
- for (const visit_s &visit : merged_visits) {
- mac_sets.push_back(visit.mac_set);
+ std::vector<std::shared_ptr<mac_set_t>> macSets;
+ for (const Visit &visit : merged_visits) {
+ macSets.push_back(visit.macSet);
}
- std::shared_ptr<mac_set_t> all_macs = mac_sets_union(mac_sets);
+ std::shared_ptr<mac_set_t> 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<ctx::components_t> &cc)
+void ctx::PlacesDetector::reduceOutliers(std::shared_ptr<ctx::graph::Components> &cc)
{
int size = cc->size();
cc->erase(std::remove_if(cc->begin(),
cc->end(),
- [](std::shared_ptr<component_t> &c) {
+ [](std::shared_ptr<graph::Component> &c) {
return c->size() < PLACES_DETECTOR_MIN_VISITS_PER_PLACE;
}),
cc->end());
}
}
-std::shared_ptr<ctx::components_t> ctx::PlacesDetector::merge_visits(const std::vector<visit_s> &visits)
+std::shared_ptr<ctx::graph::Components> ctx::PlacesDetector::__mergeVisits(const std::vector<Visit> &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::graph_t> ctx::PlacesDetector::graph_from_visits(const std::vector<visit_s> &visits)
+std::shared_ptr<ctx::graph::Graph> ctx::PlacesDetector::__graphFromVisits(const std::vector<Visit> &visits)
{
- std::shared_ptr<graph_t> graph = std::make_shared<graph_t>();
+ std::shared_ptr<graph::Graph> graph = std::make_shared<graph::Graph>();
graph->resize(visits.size());
for (size_t i = 0; i < visits.size(); i++) {
- (*graph)[i] = std::make_shared<nhood_t>();
+ (*graph)[i] = std::make_shared<graph::NeighbourNodes>();
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);
}
return graph;
}
-void ctx::PlacesDetector::db_delete_places()
+void ctx::PlacesDetector::__dbDeletePlaces()
{
std::vector<Json> 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;
_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<Json> records = db_get_places();
- std::vector<std::shared_ptr<Place>> db_places = places_from_jsons(records);
- detected_places_update(db_places);
+ __dbCreateTable();
+ std::vector<Json> records = __dbGetPlaces();
+ std::vector<std::shared_ptr<Place>> 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);
_D("insert place execute query result: %s", ret ? "SUCCESS" : "FAIL");
}
-std::vector<std::shared_ptr<ctx::Place>> ctx::PlacesDetector::get_places()
+std::vector<std::shared_ptr<ctx::Place>> ctx::PlacesDetector::getPlaces()
{
// XXX: In case of thread safety issues use std::mutex to protect places list.
- return detected_places;
+ return __detectedPlaces;
}
* 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 <ITimerListener.h>
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<Json>& records);
- std::shared_ptr<ctx::Place> place_from_json(Json &row);
- std::vector<std::shared_ptr<Place>> places_from_jsons(std::vector<Json>& records);
- std::shared_ptr<graph_t> graph_from_visits(const std::vector<visit_s> &visits);
- void db_create_table();
- void db_delete_places();
- void db_delete_old_visits();
- void db_delete_older_visits(time_t threshold);
- std::vector<Json> db_get_visits();
- std::vector<Json> db_get_places();
- void db_insert_place(const Place &place);
- std::shared_ptr<Place> place_from_merged(visits_t &merged_visits);
- std::vector<std::shared_ptr<Place>> detected_places;
- void detected_places_update(std::vector<std::shared_ptr<Place>> &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<Json>& records);
+ std::shared_ptr<ctx::Place> __placeFromJson(Json &row);
+ std::vector<std::shared_ptr<Place>> __placesFromJsons(std::vector<Json>& records);
+
+ std::shared_ptr<graph::Graph> __graphFromVisits(const std::vector<Visit> &visits);
+
+ void __dbCreateTable();
+ void __dbDeletePlaces();
+ void __dbDeleteOldVisits();
+ void __dbDeleteOlderVisitsThan(time_t threshold);
+ std::vector<Json> __dbGetVisits();
+ std::vector<Json> __dbGetPlaces();
+ void __dbInsertPlace(const Place &place);
+
+ std::shared_ptr<Place> __placeFromMergedVisits(visits_t &merged_visits);
+ std::vector<std::shared_ptr<Place>> __detectedPlaces;
+ void __detectedPlacesUpdate(std::vector<std::shared_ptr<Place>> &new_places);
+ void __processVisits(visits_t &visits);
+ static void __mergeLocation(const visits_t &merged_visits, Place &place);
+ std::shared_ptr<graph::Components> __mergeVisits(const std::vector<Visit> &visits);
- public:
- static void reduce_outliers(visits_t &visits);
- static void reduce_outliers(std::shared_ptr<components_t> &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<components_t> merge_visits(const std::vector<visit_s> &visits);
- std::vector<std::shared_ptr<Place>> get_places();
+
+ public:
+ PlacesDetector(bool testMode = false);
+ static void reduceOutliers(visits_t &visits); // TODO: move to private
+ static void reduceOutliers(std::shared_ptr<graph::Components> &cc); // TODO: move to private
+ std::vector<std::shared_ptr<Place>> getPlaces();
}; /* class PlacesDetector */
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_STATUS_PLACES_DETECTOR__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_PLACES_DETECTOR_ */
* 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 <monday ÷ sunday> 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<place_categ_id_e, std::vector<num_t>> week_model {
+ std::map<PlaceCategId, std::vector<num_t>> weekModel {
{ PLACE_CATEG_ID_HOME,
{
0.9824561403508770,
}
};
+} /* namespace prob_features */
+
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_PROB_FEATURES_MODEL_H__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_FEATURES_MODEL_H_ */
* 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 <class T> ctx::share_t overlap_first_over_second(const T &s1, const T &s2)
+ template <class T> ctx::share_t overlap1stOver2nd(const T &s1, const T &s2)
{
if (s2.empty()) {
return 0;
return (ctx::share_t) count / s2.size();
}
- template <class T> ctx::share_t overlap_bigger_over_smaller(const T &s1, const T &s2)
+ template <class T> 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 <class T> bool is_joint(const T &s1, const T &s2)
+ template <class T> bool isJoint(const T &s1, const T &s2)
{
for (auto e : s2) {
if (s1.find(e) != s1.end()) {
return false;
}
+} /* namespace similarity */
+
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_STATUS_SIMILAR_H__ */
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_SIMILAR_H_ */
#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 {
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<std::shared_ptr<ctx::Place>> ctx::UserPlaces::get_places()
+std::vector<std::shared_ptr<ctx::Place>> ctx::UserPlaces::getPlaces()
{
- if (places_detector) {
- return places_detector->get_places();
+ if (__placesDetector) {
+ return __placesDetector->getPlaces();
} else {
return std::vector<std::shared_ptr<ctx::Place>>();
}
* ]
* }
*/
-ctx::Json ctx::UserPlaces::compose_json(std::vector<std::shared_ptr<Place>> places)
+ctx::Json ctx::UserPlaces::composeJson(std::vector<std::shared_ptr<Place>> places)
{
ctx::Json data;
for (std::shared_ptr<ctx::Place> place : places) {
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);
}
}
* 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 <vector>
#include <Json.h>
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<std::shared_ptr<Place>> get_places();
- static Json compose_json(std::vector<std::shared_ptr<Place>> places);
+ void setMode(place_recog_mode_e energyMode);
+ std::vector<std::shared_ptr<Place>> getPlaces();
+ static Json composeJson(std::vector<std::shared_ptr<Place>> places);
}; /* class UserPlaces */
} /* namespace ctx */
-#endif /* __CONTEXT_PLACE_STATUS_USER_PLACES_ENGINE_H__ */
-
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_USER_PLACES_H_ */
* 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.
*/
#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_ */
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;
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;
}
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> mac_vec(mac_set.size());
- std::copy(mac_set.begin(), mac_set.end(), mac_vec.begin());
+ std::vector<Mac> mac_vec(macSet.size());
+ std::copy(macSet.begin(), macSet.end(), mac_vec.begin());
std::sort(mac_vec.begin(), mac_vec.end());
bool first = true;
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,
#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
&& 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)
std::shared_ptr<ctx::mac_set_t> ctx::mac_set_from_mac_counts(const mac_counts_t &mac_counts)
{
- std::shared_ptr<mac_set_t> mac_set(std::make_shared<mac_set_t>());
+ std::shared_ptr<mac_set_t> macSet(std::make_shared<mac_set_t>());
for (auto &c: mac_counts) {
- mac_set->insert(c.first);
+ macSet->insert(c.first);
}
- return mac_set;
+ return macSet;
}
-std::shared_ptr<ctx::mac_set_t> ctx::mac_sets_union(const std::vector<std::shared_ptr<mac_set_t>> &mac_sets)
+std::shared_ptr<ctx::mac_set_t> ctx::mac_sets_union(const std::vector<std::shared_ptr<mac_set_t>> &macSets)
{
std::shared_ptr<mac_set_t> union_set = std::make_shared<mac_set_t>();
- for (std::shared_ptr<mac_set_t> mac_set : mac_sets) {
- union_set->insert(mac_set->begin(), mac_set->end());
+ for (std::shared_ptr<mac_set_t> 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_);
}
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;
}
* 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 <memory>
#include <vector>
typedef std::unordered_set<ctx::Mac> 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_set_t> mac_sets_union(const std::vector<std::shared_ptr<mac_set_t>> &mac_sets);
+ std::shared_ptr<mac_set_t> mac_sets_union(const std::vector<std::shared_ptr<mac_set_t>> &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<ctx::interval_s> {
- size_t operator()(const ctx::interval_s & interval) const {
+ template <> struct hash<ctx::Interval> {
+ size_t operator()(const ctx::Interval & interval) const {
return interval.end * interval.start;
}
};
/*
* 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<int, num_t> 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_t> mac_set;
+ struct Visit {
+ Interval interval;
+ std::shared_ptr<mac_set_t> 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_t> mac_set_ = std::make_shared<mac_set_t>(), categs_t categs_ = categs_t()) :
+ Visit(Interval interval_, std::shared_ptr<mac_set_t> macSet_ = std::make_shared<mac_set_t>(), 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<visit_s> visits_t;
- typedef std::vector<mac_event_s> mac_events; // used to store current interval logs
+ bool operator==(const Visit &v1, const Visit &v2);
+ typedef std::vector<Visit> visits_t;
+ typedef std::vector<MacEvent> mac_events; // used to store current interval logs
- std::shared_ptr<mac_set_t> mac_set_from_mac_counts(const mac_counts_t &mac_counts);
+ std::shared_ptr<mac_set_t> 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
} /* namespace ctx */
-#endif /*__CONTEXT_PLACE_STATUS_USER_PLACES_TYPES_H__*/
+#endif /* End of _CONTEXT_PLACE_RECOGNITION_USER_PLACES_TYPES_H_ */
#include <types_internal.h>
// categorizer model parameters trained offline (implemented in python):
-const std::map<int, ctx::MahalModel> ctx::VisitCateger::models({
+const std::map<int, ctx::MahalModel> ctx::VisitCateger::__models({
{
PLACE_CATEG_ID_HOME,
ctx::MahalModel(
})
}});
-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,
} // this is chi cdf for 7 degrees of freedom (because we have 7 features)
);
-const std::vector<ctx::num_t> ctx::VisitCateger::features_mean(
+const std::vector<ctx::num_t> ctx::VisitCateger::__featuresMean(
{
344.542975696503,
894.178423236515,
0.139583453187
});
-const std::vector<ctx::num_t> ctx::VisitCateger::features_std(
+const std::vector<ctx::num_t> ctx::VisitCateger::__featuresStd(
{
416.061437196941,
301.401812101781,
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<num_t> model, const size_t &from, const size_t &to)
+ctx::num_t ctx::VisitCateger::__sum(const std::vector<num_t> model, const size_t &from, const size_t &to)
{
size_t to_secure = to;
if (to >= model.size()) {
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) {
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],
return categs;
}
-std::vector<ctx::num_t> ctx::VisitCateger::interval_features(const interval_s &interval)
+std::vector<ctx::num_t> 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],
};
}
-void ctx::VisitCateger::normalize(std::vector<ctx::num_t> &features)
+void ctx::VisitCateger::__normalize(std::vector<ctx::num_t> &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<ctx::num_t> features = interval_features(visit.interval);
- normalize(features);
+ std::vector<ctx::num_t> 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;
}
}
* 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"
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;
};
private:
const static int MINUTES_IN_WEEK = 60 * 24 * 7;
- const static std::map<int, MahalModel> models;
- const static std::vector<num_t> features_mean;
- const static std::vector<num_t> features_std;
- static num_t sum(const std::vector<num_t> 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<num_t> &features);
+ const static std::map<int, MahalModel> __models;
+ const static std::vector<num_t> __featuresMean;
+ const static std::vector<num_t> __featuresStd;
+ static num_t __sum(const std::vector<num_t> 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<num_t> &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
* @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,
* @param interval time interval
* @return std::vector<num_t> vector with interpretations of input time interval
*/
- static std::vector<num_t> interval_features(const interval_s &interval);
+ static std::vector<num_t> 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_ */
#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"
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<mac_events>();
- stay_macs = std::make_shared<mac_set_t>();
+ __setPeriod(energyMode);
+ __currentInterval = Interval(t_start_scan, t_start_scan + __periodSeconds);
+ __currentLogger = std::make_shared<mac_events>();
+ __stayMacs = std::make_shared<mac_set_t>();
- if (test_mode) {
- detected_visits = std::make_shared<ctx::visits_t>();
+ if (__testMode) {
+ __detectedVisits = std::make_shared<ctx::visits_t>();
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<ctx::frame_s> frame = make_frame(this->current_logger, this->current_interval);
- detect_entrance_or_departure(frame);
- current_logger->clear();
+ std::shared_ptr<ctx::Frame> frame = __makeFrame(__currentLogger, __currentInterval);
+ __detectEntranceOrDeparture(frame);
+ __currentLogger->clear();
}
-std::shared_ptr<ctx::frame_s> ctx::VisitDetector::make_frame(std::shared_ptr<ctx::mac_events> logger, ctx::interval_s interval)
+std::shared_ptr<ctx::Frame> ctx::VisitDetector::__makeFrame(std::shared_ptr<ctx::mac_events> logger, ctx::Interval interval)
{
std::set<time_t> timestamps;
- std::shared_ptr<frame_s> frame = std::make_shared<frame_s>(interval);
+ std::shared_ptr<Frame> frame = std::make_shared<Frame>(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<ctx::frame_s> frame)
+void ctx::VisitDetector::__detectEntranceOrDeparture(std::shared_ptr<ctx::Frame> 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<ctx::frame_s> frame)
+void ctx::VisitDetector::__detectDeparture(std::shared_ptr<ctx::Frame> 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<double> latitudes;
std::vector<double> 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;
}
}
-void ctx::VisitDetector::buffer_processing(std::shared_ptr<ctx::frame_s> frame)
+void ctx::VisitDetector::__processBuffer(std::shared_ptr<ctx::Frame> 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<ctx::frame_s> current_frame)
+void ctx::VisitDetector::__detectEntrance(std::shared_ptr<ctx::Frame> 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<frame_s> oldest_history_frame = history_frames[0];
- stay_macs = mac_set_from_mac_counts(oldest_history_frame->mac_counts);
+ if (__stableCounter == 0) {
+ std::shared_ptr<Frame> oldest_history_frame = __historyFrames[0];
+ __stayMacs = mac_set_from_mac_counts(oldest_history_frame->macCountsMap);
}
- std::shared_ptr<mac_set_t> current_beacons = mac_set_from_mac_counts(current_frame->mac_counts);
+ std::shared_ptr<mac_set_t> 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_s> frame)
+void ctx::VisitDetector::__resetHistory(std::shared_ptr<Frame> frame)
{
- history_reset();
- history_frames.push_back(frame);
+ __resetHistory();
+ __historyFrames.push_back(frame);
}
-std::shared_ptr<ctx::mac_set_t> ctx::VisitDetector::select_representatives(const std::vector<std::shared_ptr<frame_s>> &frames)
+std::shared_ptr<ctx::mac_set_t> ctx::VisitDetector::__selectRepresentatives(const std::vector<std::shared_ptr<Frame>> &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<mac_shares_t> repr_shares = mac_shares_from_counts(repr_counts, all_count);
+ std::shared_ptr<mac_shares_t> 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<mac_set_t> repr_mac_set = mac_set_of_greater_or_equal_share(*repr_shares, threshold);
+ std::shared_ptr<mac_set_t> 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) {
return max_value;
}
-std::shared_ptr<ctx::mac_set_t> ctx::VisitDetector::mac_set_of_greater_or_equal_share(const ctx::mac_shares_t &mac_shares, ctx::share_t threshold)
+std::shared_ptr<ctx::mac_set_t> ctx::VisitDetector::__macSetOfGreaterOrEqualShare(const ctx::mac_shares_t &mac_shares, ctx::share_t threshold)
{
- std::shared_ptr<mac_set_t> mac_set = std::make_shared<mac_set_t>();
+ std::shared_ptr<mac_set_t> macSet = std::make_shared<mac_set_t>();
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::mac_shares_t> ctx::VisitDetector::mac_shares_from_counts(ctx::mac_counts_t const &mac_counts, ctx::count_t denominator)
+std::shared_ptr<ctx::mac_shares_t> ctx::VisitDetector::__macSharesFromCounts(ctx::mac_counts_t const &macCountsMap, ctx::count_t denominator)
{
std::shared_ptr<mac_shares_t> mac_shares(std::make_shared<mac_shares_t>());
- 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::visits_t> ctx::VisitDetector::get_visits()
+std::shared_ptr<ctx::visits_t> 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()) {
}
}
-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());
data.set(NULL, VISIT_COLUMN_END_TIME, static_cast<int>(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);
}
* 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 <memory>
#include <vector>
class VisitDetector : public IWifiListener, ILocationListener {
private:
- bool test_mode;
- std::shared_ptr<visits_t> detected_visits; // only used in test mode
- LocationLogger location_logger;
- WifiLogger wifi_logger;
- std::vector<IVisitListener*> listeners;
-
- std::shared_ptr<mac_events> current_logger;
- interval_s current_interval;
-
- std::vector<std::shared_ptr<frame_s>> history_frames; // python: history_scans + history_times
- std::vector<std::shared_ptr<frame_s>> buffered_frames; // python: buffered_scans + buffered_times
-
- int stable_counter;
- int tolerance;
- bool entrance_to_place;
- int period_seconds;
+ bool __testMode;
+ std::shared_ptr<visits_t> __detectedVisits; // only used in test mode
+ LocationLogger __locationLogger;
+ WifiLogger __wifiLogger;
+ std::vector<IVisitListener*> __listeners;
+ std::shared_ptr<mac_events> __currentLogger;
+ Interval __currentInterval;
+ std::vector<LocationEvent> __locationEvents;
+ std::vector<std::shared_ptr<Frame>> __historyFrames; // python: history_scans + history_times
+ std::vector<std::shared_ptr<Frame>> __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<mac_set_t> rep_macs; // mac that represent the current place
- std::shared_ptr<mac_set_t> stay_macs; // macs that can appear in the current place
- time_t entrance_time;
- time_t departure_time;
-
- std::vector<location_event_s> locations;
-
- bool is_valid(const Mac &mac);
- void shift_current_interval();
- void detect_entrance_or_departure(std::shared_ptr<frame_s> frame);
- void detect_entrance(std::shared_ptr<frame_s> frame);
- void detect_departure(std::shared_ptr<frame_s> frame);
- void buffer_processing(std::shared_ptr<frame_s> frame); // python: buffer_anaysing
- std::shared_ptr<frame_s> make_frame(std::shared_ptr<mac_events> mac_events, interval_s interval); // python: scans2fingerprint
- void history_reset();
- void history_reset(std::shared_ptr<frame_s> frame);
- void visit_start_detected();
- void visit_end_detected();
- void put_visit_location(visit_s &visit);
- std::shared_ptr<mac_set_t> select_representatives(const std::vector<std::shared_ptr<frame_s>> &frames);
- std::shared_ptr<mac_set_t> mac_set_of_greater_or_equal_share(const mac_shares_t &mac_shares, share_t threshold);
- std::shared_ptr<mac_shares_t> 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<mac_set_t> __representativesMacs; // macs that represent the current place
+ std::shared_ptr<mac_set_t> __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> frame);
+ void __detectEntrance(std::shared_ptr<Frame> frame);
+ void __detectDeparture(std::shared_ptr<Frame> frame);
+ void __processBuffer(std::shared_ptr<Frame> frame); // python: buffer_analysing
+ std::shared_ptr<Frame> __makeFrame(std::shared_ptr<mac_events> mac_events, Interval interval); // python: scans2fingerprint
+ void __resetHistory();
+ void __resetHistory(std::shared_ptr<Frame> frame);
+ void __visitStartDetected();
+ void __visitEndDetected();
+ void __putLocationToVisit(Visit &visit);
+ std::shared_ptr<mac_set_t> __selectRepresentatives(const std::vector<std::shared_ptr<Frame>> &frames);
+ std::shared_ptr<mac_set_t> __macSetOfGreaterOrEqualShare(const mac_shares_t &mac_shares, share_t threshold);
+ std::shared_ptr<mac_shares_t> __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<visits_t> 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<visits_t> 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_ */
* 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 {
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_ */
* 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"
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_ */
#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<mac_event_s>();
+ __logs = std::vector<MacEvent>();
- 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<int>(connected_to_wifi_ap),
- static_cast<int>(during_visit));
+ wifi_connection_state_e state = __wifiGetConnectionStateRequest();
+ __connectedToWifiAp = (state == WIFI_CONNECTION_STATE_CONNECTED);
+ _D("__connectedToWifiAp = %d, __duringVisit = %d IN CONSTRUCTOR",
+ static_cast<int>(__connectedToWifiAp),
+ static_cast<int>(__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:
}
}
-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;
}
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:
}
}
-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<int>(wifi_logger_p->connected_to_wifi_ap),
- static_cast<int>(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<int>(wifiLogger->__connectedToWifiAp),
+ static_cast<int>(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);
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);
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;
}
{
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<int>(connected_to_wifi_ap),
- static_cast<int>(during_visit),
- last_scans_pool.size());
+ _D("__connectedToWifiAp = %d, __duringVisit = %d, __lastScansPool.size() = %d",
+ static_cast<int>(__connectedToWifiAp),
+ static_cast<int>(__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();
}
}
* 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 <wifi.h>
#include <time.h>
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<mac_event_s> logs;
- std::set<std::string> 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<MacEvent> __logs;
+ std::set<std::string> __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_ */