Initial source code 76/214076/3
authorKichan Kwon <k_c.kwon@samsung.com>
Wed, 18 Sep 2019 00:51:21 +0000 (09:51 +0900)
committerDewal Agarwal <d1.agarwal@samsung.com>
Wed, 18 Sep 2019 05:54:41 +0000 (11:24 +0530)
- Bring from devel repo : PR #76

Change-Id: Ie9a7218ab1b21338fd600a6f5f8e5dd88d315183
Signed-off-by: Kichan Kwon <k_c.kwon@samsung.com>
27 files changed:
CMakeLists.txt [new file with mode: 0644]
LICENSE [new file with mode: 0644]
NOTICE [new file with mode: 0644]
config/bm_power_profile_params.json [new file with mode: 0644]
include/bm_common.h [new file with mode: 0644]
include/bm_config_parser.h [new file with mode: 0644]
include/bm_dbg.h [new file with mode: 0644]
include/bm_plugin_interface.h [new file with mode: 0644]
include/bm_plugin_manager.h [new file with mode: 0644]
include/bm_power_engine.h [new file with mode: 0644]
include/bm_private.h [new file with mode: 0644]
include/bm_server.h [new file with mode: 0644]
include/bm_server_db.h [new file with mode: 0644]
include/bm_util.h [new file with mode: 0644]
packaging/battery-monitor.xml [new file with mode: 0644]
packaging/batterymonitor.manifest [new file with mode: 0644]
packaging/batterymonitor.service [new file with mode: 0644]
packaging/batterymonitor.spec [new file with mode: 0644]
packaging/org.tizen.battery.monitor.conf [new file with mode: 0644]
packaging/org.tizen.battery.monitor.service [new file with mode: 0644]
src/bm_callback_handler.c [new file with mode: 0644]
src/bm_config_parser.c [new file with mode: 0644]
src/bm_plugin_manager.c [new file with mode: 0644]
src/bm_power_engine.c [new file with mode: 0644]
src/bm_server.c [new file with mode: 0644]
src/bm_server_db.c [new file with mode: 0644]
src/bm_util.c [new file with mode: 0644]

diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..ec86a72
--- /dev/null
@@ -0,0 +1,61 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(batterymonitor-svcd C)
+
+SET(DAEMON batterymonitor-svcd)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(pkgs REQUIRED
+       dlog
+       gio-2.0
+       gio-unix-2.0
+       libtzplatform-config
+       sqlite3
+       db-util
+       capi-system-info
+       cynara-client
+       cynara-session
+       cynara-creds-gdbus
+       json-c
+       capi-appfw-job-scheduler
+       capi-system-device
+)
+
+ADD_CUSTOM_COMMAND(
+       WORKING_DIRECTORY
+       OUTPUT battery_monitor_stub.c
+       COMMAND gdbus-codegen --interface-prefix org.tizen.
+       --generate-c-code battery_monitor_stub packaging/battery-monitor.xml
+       COMMENT "Generating Battery-Monitor Client  GDBus .c/.h")
+
+FOREACH(flag ${pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag} -Wall")
+ENDFOREACH(flag)
+
+SET(SRCS
+       ./battery_monitor_stub.c
+       src/bm_config_parser.c
+       src/bm_power_engine.c
+       src/bm_plugin_manager.c
+       src/bm_callback_handler.c
+       src/bm_server_db.c
+       src/bm_util.c
+       src/bm_server.c
+)
+
+INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include)
+
+INSTALL(FILES ${CMAKE_SOURCE_DIR}/battery_monitor_stub.h DESTINATION include)
+
+SET(RELO_FLAGS "-D_FORTIFY_SOURCE=2 -Wl,-z,relro")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} ${RELO_FLAGS} -fPIE -fPIC -Wall -Werror")
+SET(CMAKE_C_FLAGS_DEBUG "-O0 -g")
+SET(CMAKE_C_FLAGS_RELEASE "-O2")
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed -pie")
+
+ADD_EXECUTABLE(${DAEMON} ${SRCS})
+
+TARGET_LINK_LIBRARIES(${DAEMON} ${pkgs_LDFLAGS} -ldl)
+
+INSTALL(TARGETS ${DAEMON} DESTINATION bin)
+
+TARGET_LINK_LIBRARIES(${DAEMON} -ldl)
diff --git a/LICENSE b/LICENSE
new file mode 100644 (file)
index 0000000..7ae2595
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,204 @@
+Copyright (c) 2015 - 2017 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+
diff --git a/NOTICE b/NOTICE
new file mode 100644 (file)
index 0000000..ccdad52
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,3 @@
+Copyright (c) Samsung Electronics Co., Ltd. All rights reserved.
+Except as noted, this software is licensed under Apache License, Version 2.
+Please, see the LICENSE file for Apache License terms and conditions.
diff --git a/config/bm_power_profile_params.json b/config/bm_power_profile_params.json
new file mode 100644 (file)
index 0000000..81efaae
--- /dev/null
@@ -0,0 +1,49 @@
+{
+       "wifi": {
+               "p_wifi_rssi_0": 10,
+               "p_wifi_rssi_1": 20,
+               "p_wifi_rssi_2": 30,
+               "p_wifi_rssi_3": 40,
+               "p_wifi_rssi_4": 50,
+               "p_wifi_scan": 60,
+               "p_wifi_idle": 70,
+               "p_wifi_rx": 80,
+               "p_wifi_tx": 90
+       },
+       "bluetooth": {
+               "p_bt_idle": 100,
+               "p_bt_scan": 120,
+               "p_bt_connected": 130,
+               "p_bt_rx": 140,
+               "p_bt_tx": 150
+       },
+       "device_network": {
+               "p_dnw_sig_strength_0": 200,
+               "p_dnw_sig_strength_1": 210,
+               "p_dnw_sig_strength_2": 220,
+               "p_dnw_sig_strength_3": 230,
+               "p_dnw_sig_strength_4": 240,
+               "p_dnw_sig_strength_5": 250,
+               "p_dnw_sig_strength_6": 260,
+               "p_dnw_rx": 210,
+               "p_dnw_tx": 220
+       },
+       "display": {
+               "p_dp_high": 300,
+               "p_dp_medium": 310,
+               "p_dp_low": 320
+       },
+       "gps_sensor": {
+               "p_gps_inuse": 400
+       },
+       "hrm_Sensor": {
+               "p_hrm_inuse": 500
+       },
+       "cpu": {
+               "p_cpu_fg": 600,
+               "p_cpu_bg": 610
+       },
+       "battery": {
+               "p_battery": 700
+       }
+}
diff --git a/include/bm_common.h b/include/bm_common.h
new file mode 100644 (file)
index 0000000..6ea4ecd
--- /dev/null
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_COMMON_H__
+#define __BM_COMMON_H__
+
+#include <stdlib.h>
+#include <glib.h>
+#include <gio/gio.h>
+#include <tzplatform_config.h>
+#include <tizen_error.h>
+
+#include "bm_dbg.h"
+
+#ifndef TIZEN_ERROR_BATTERY_MONITOR
+#define TIZEN_ERROR_BATTERY_MONITOR    0x91000000
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief      Enumeration for error codes for battery monitor
+ * @since_tizen  5.5
+ */
+typedef enum {
+       BATTERY_MONITOR_ERROR_NONE = TIZEN_ERROR_NONE,                                  /**< Successful */
+       BATTERY_MONITOR_ERROR_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY,                /**< Out of memory */
+       BATTERY_MONITOR_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER,        /**< Invalid parameter */
+       BATTERY_MONITOR_ERROR_DUPLICATED = TIZEN_ERROR_BATTERY_MONITOR | 0x01,          /**< Same user name exists in your application */
+       BATTERY_MONITOR_ERROR_NO_DATA = TIZEN_ERROR_NO_DATA,                            /**< Empty data */
+       BATTERY_MONITOR_ERROR_NOT_INITIALIZED = TIZEN_ERROR_BATTERY_MONITOR | 0x02,     /**< Not initialized */
+       BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND = TIZEN_ERROR_BATTERY_MONITOR | 0x03,    /**< Related record does not exist */
+       BATTERY_MONITOR_ERROR_DB_FAILED = TIZEN_ERROR_BATTERY_MONITOR | 0x04,           /**< DB operation failed */
+       BATTERY_MONITOR_ERROR_DB_NOT_OPENED = TIZEN_ERROR_BATTERY_MONITOR | 0x05,       /**< DB is not connected */
+       BATTERY_MONITOR_ERROR_QUERY_SYNTAX_ERROR = TIZEN_ERROR_BATTERY_MONITOR | 0x06,  /**< DB query syntax error */
+       BATTERY_MONITOR_ERROR_ITERATOR_END = TIZEN_ERROR_BATTERY_MONITOR | 0x07,        /**< Iterator has reached the end */
+       BATTERY_MONITOR_ERROR_NOTI_FAILED = TIZEN_ERROR_BATTERY_MONITOR | 0x08,         /**< Notification failed */
+       BATTERY_MONITOR_ERROR_PERMISSION_DENIED = TIZEN_ERROR_PERMISSION_DENIED,        /**< Permission denied */
+       BATTERY_MONITOR_ERROR_NULL_POINTER = TIZEN_ERROR_BATTERY_MONITOR | 0x0a,        /**< NULL Pointer Value */
+       BATTERY_MONITOR_ERROR_INTERNAL = TIZEN_ERROR_BATTERY_MONITOR | 0x0b,            /**< Internal error for generic use */
+       BATTERY_MONITOR_ERROR_PLUGIN_ADD = TIZEN_ERROR_BATTERY_MONITOR | 0x0c,          /**< Plugin add error */
+       BATTERY_MONITOR_ERROR_PLUGIN_AVAILABLE = TIZEN_ERROR_BATTERY_MONITOR | 0x0d,    /**< Plugin already added */
+       BATTERY_MONITOR_ERROR_NOT_SUPPORTED = TIZEN_ERROR_BATTERY_MONITOR | 0x0e,       /**< Not supported */
+       BATTERY_MONITOR_ERROR_DATABASE_BUSY = TIZEN_ERROR_BATTERY_MONITOR | 0x10,       /**< SQLite busy handler expired */
+} battery_monitor_error_e;
+
+/* dbus macros*/
+#define BATTERY_MONITOR_DBUS_NAME              "org.tizen.battery.monitor"
+#define BATTERY_MONITOR_DBUS_PATH              "/org/tizen/battery/monitor"
+
+/* plugin macros */
+#define BATTERY_MONITOR_PLUGIN_DIR             "/usr/lib/batterymonitor/plugins"
+#define BATTERY_MONITOR_PLUGIN_SYMBOL          "bm_plugin"
+#define BATTERY_MONITOR_PLUGINS_MAX            7
+#define BATTERY_MONITOR_CALLBACKS_MAX          7
+#define BATTERY_MONITOR_VERSION                        "0.1"
+#define BM_ENUM_ID_TO_STR(x)                   case (x): EXIT; return (#x);
+#define BM_RESOURCE_ID_TO_STR(x, y)            case (x): EXIT; return (#y);
+
+/* job-scheduler macros */
+#define BATTERY_MONITOR_GET_DATA_JOB_PERIOD    180000          /* (3*60*1000) interval of 3mins */
+#define BATTERY_MONITOR_DELETE_DB_JOB_PERIOD   86400000        /* (24*60*60*1000) interval of 24hrs */
+
+#define BM_PLUGIN_CONST_BATTERY                        7
+
+/* power-param config file macro */
+#define BATTERY_MONITOR_CONFIG_FILE_PATH       "/usr/etc/batterymonitor/config/bm_power_profile_params.json"
+
+/* privilege macro */
+#define BATTERY_MONITOR_PRIVILEGE              "http://tizen.org/privilege/systemmonitor"
+
+/* error macros */
+#define BATTERY_MONITOR_SVC_ERROR_DOMAIN       "batterymonitor-svc"
+#define BATTERY_MONITOR_SVC_ERROR_PREFIX       "org.tizen.battery.monitor.Error"
+
+/* free-desktop macros */
+#define FREE_DESKTOP_BUS_NAME                  "org.freedesktop.DBus"
+#define FREE_DESKTOP_OBJECT_PATH               "/org/freedesktop/DBus"
+#define FREE_DESKTOP_INTERFACE_NAME            "org.freedesktop.DBus"
+#define FREE_DESKTOP_METHOD_NAME               "GetConnectionUnixProcessID"
+
+/* Macros for serialize data */
+#define BATTERY_MONITOR_BLE_DATA_ID            "ble"
+#define BATTERY_MONITOR_WIFI_DATA_ID           "wifi"
+#define BATTERY_MONITOR_CPU_DATA_ID            "cpu"
+#define BATTERY_MONITOR_DP_DATA_ID             "display"
+#define BATTERY_MONITOR_DN_DATA_ID             "device-network"
+#define BATTERY_MONITOR_GPS_DATA_ID            "gps"
+#define BATTERY_MONITOR_HRM_DATA_ID            "hrm"
+#define BATTERY_MONITOR_BATTERY_DATA_ID                "battery"
+
+/* Macros for Resource ID */
+#define BM_RID_BLE                             BATTERY_MONITOR_BLE_DATA_ID
+#define BM_RID_WIFI                            BATTERY_MONITOR_WIFI_DATA_ID
+#define BM_RID_CPU                             BATTERY_MONITOR_CPU_DATA_ID
+#define BM_RID_DISP                            BATTERY_MONITOR_DP_DATA_ID
+#define BM_RID_DNTW                            BATTERY_MONITOR_DN_DATA_ID
+#define BM_RID_GPS                             BATTERY_MONITOR_GPS_DATA_ID
+#define BM_RID_HRM                             BATTERY_MONITOR_HRM_DATA_ID
+#define BM_RID_BAT                             BATTERY_MONITOR_BATTERY_DATA_ID
+
+
+/* database macros */
+/* #define GLOBAL_USER tzplatform_getuid(TZ_SYS_GLOBALAPP_USER) */
+
+#define BATTERY_MONITOR_GET_DB_PATH(dest, size) \
+       do { \
+               snprintf(dest, size-1, "%s", tzplatform_mkpath(TZ_SYS_DB, "/.battery-monitor.db")); \
+       } while (0)
+
+#define BATTERY_MONITOR_GET_JN_PATH(dest, size) \
+       do { \
+               snprintf(dest, size-1, "%s", tzplatform_mkpath(TZ_SYS_DB, "/.battery-monitor.db-journal")); \
+       } while (0)
+
+/* validating expression */
+#define BM_CHECK_EXPR(expr) \
+       do { \
+               if (expr) { \
+                       _ERR("(%s) return", #expr); \
+                       return; \
+               } \
+} while (0)
+
+/* validating input param - return error */
+#define BM_CHECK_INPUT_PARAM(arg) \
+       do { \
+               if (NULL == arg) { \
+                       _ERR("invalid input param"); \
+                       return BATTERY_MONITOR_ERROR_INVALID_PARAMETER; \
+               } \
+       } while (0)
+
+/* warning */
+#define BM_CHECK_VAL(eval, X) \
+       do { \
+               if (!(eval)) { \
+                       _WARN("improper value - [%s]", #X); \
+               } \
+       } while (0)
+
+/* validating return value */
+#define BM_RETURN_VAL(eval, expr, ret_val, X) \
+       if (!(eval)) { \
+               expr; \
+               return ret_val; \
+       } else {}
+
+/* snprintf wrapper */
+#define BM_SNPRINTF(dest, size, format, arg...) \
+       do { \
+               snprintf(dest, size-1, format, ##arg); \
+       } while (0)
+
+/* memset wrapper */
+#define BM_MEMSET(dest, value, size) \
+       do { \
+               memset(dest, value, size); \
+       } while (0)
+
+/* memcpy wrapper */
+#define BM_MEMCPY(dest, value, size) \
+       do { \
+               memcpy(dest, value, size); \
+       } while (0)
+
+/* error & catch */
+#define BM_CATCH_ERROR(eval, expr, error_val, X) \
+       if (!(eval)) { \
+               expr; \
+               error_code = (error_val); \
+               goto CATCH; \
+       } else {}
+
+/* error & catch for pointer */
+#define BM_CATCH_ERROR_P(eval, expr, error_val, X) \
+       if (!(eval)) { \
+               expr; \
+               *error_code = (error_val); \
+               goto CATCH; \
+       } else { }
+
+/* setting free memory using C-API */
+#define BM_FREE(ptr) \
+       if (ptr != NULL) { \
+               free(ptr); \
+               ptr = NULL; \
+       } \
+
+/* setting free memory using glib-API */
+#define BM_GFREE(ptr) \
+       if (ptr != NULL) { \
+               g_free(ptr); \
+               ptr = NULL; \
+       } \
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_COMMON_H__ */
+
diff --git a/include/bm_config_parser.h b/include/bm_config_parser.h
new file mode 100644 (file)
index 0000000..99e2281
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_CONFIG_PARSER_H__
+#define __BM_CONFIG_PARSER_H__
+
+#include <glib.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <json-c/json.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int bm_get_wifi_power_params(int *rssi_l0, int *rssi_l1, int *rssi_l2, int *rssi_l3, int *rssi_l4,
+                                       int *scan, int *idle, int *rx, int *tx);
+
+int bm_get_blutooth_power_params(int *idle, int *scan, int *connected, int *rx, int *tx);
+
+int bm_get_device_network_power_params(int *signal_strength0, int *signal_strength1, int *signal_strength2,
+                                               int *signal_strength3, int *signal_strength4, int *signal_strength5,
+                                                       int *signal_strength6, int *rx, int *tx);
+
+int bm_get_display_power_params(int *high, int *medium, int *low);
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+int bm_get_gps_sensor_power_params(int *gps_use);
+
+int bm_get_hrm_sensor_power_params(int *hrm_use);
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+int bm_get_cpu_power_params(int *fg, int *bg);
+
+int bm_get_battery_power_params(int *battery);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_CONFIG_PARSER_H__ */
diff --git a/include/bm_dbg.h b/include/bm_dbg.h
new file mode 100644 (file)
index 0000000..c7e17e9
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_DBG_H__
+#define __BM_DBG_H__
+
+#include <tizen.h>
+#include <dlog.h>
+#include "bm_common.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#ifdef  LOG_TAG
+#undef  LOG_TAG
+#endif
+#define LOG_TAG "BMSERVER"
+
+#ifndef _BME
+#define _ERR(fmt, args...) LOGE("[%s:%d] "fmt"\n", __func__, __LINE__, ##args)
+#endif
+
+#ifndef _BMD
+#define _DBG(fmt, args...) LOGD("[%s:%d] "fmt"\n", __func__, __LINE__, ##args)
+#endif
+
+#ifndef _BMI
+#define _INFO(fmt, args...) LOGI("[%s:%d] "fmt"\n", __func__, __LINE__, ##args)
+#endif
+
+#ifndef _BMW
+#define _WARN(fmt, args...) LOGW("[%s:%d] "fmt"\n", __func__, __LINE__, ##args)
+#endif
+
+#define BM_SLOGD(fmt, arg...) SECURE_LOGD(": " fmt "\n", ##arg);
+
+#define BM_SLOGI(fmt, arg...) SECURE_LOGI(": " fmt "\n", ##arg);
+
+#define BM_SLOGE(fmt, arg...) SECURE_LOGE(": " fmt "\n", ##arg);
+
+#define ENTER dlog_print(DLOG_DEBUG, LOG_TAG, "%s : %s(%d) >>>>>>>> CALLED", rindex(__FILE__, '/') + 1, __func__, __LINE__)
+
+#define EXIT  dlog_print(DLOG_DEBUG, LOG_TAG, "%s : %s(%d) <<<<<<<< ENDED", rindex(__FILE__, '/') + 1, __func__, __LINE__)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_DBG_H__ */
+
diff --git a/include/bm_plugin_interface.h b/include/bm_plugin_interface.h
new file mode 100644 (file)
index 0000000..7afe7ab
--- /dev/null
@@ -0,0 +1,285 @@
+/*
+ * Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_PLUGIN_INTERFACE_H__
+#define __BM_PLUGIN_INTERFACE_H__
+
+#include <stdio.h>
+#include <gmodule.h>
+#include <time.h>
+#include <tizen.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef unsigned int   uint;
+typedef unsigned char  uchar;
+
+#define BM_DATA_TYPE_MAX       (BM_DATA_TYPE_HRM_SENSOR + 1)
+#define BM_PLUGIN_ID_MAX       (BM_PLUGIN_ID_HRM_SENSOR + 1)
+#define BM_DURATION_TYPE_MAX   (BM_DURATION_TYPE_1WEEK + 1)
+
+typedef enum {
+       BM_PLUGIN_ERROR_NONE = TIZEN_ERROR_NONE,                                /**< Successful */
+       BM_PLUGIN_ERROR_NO_DATA = TIZEN_ERROR_NO_DATA,                          /**< No data */
+       BM_PLUGIN_ERROR_INVALID_PARAMETER = TIZEN_ERROR_INVALID_PARAMETER,      /**< Invalid parameter */
+       BM_PLUGIN_ERROR_OUT_OF_MEMORY = TIZEN_ERROR_OUT_OF_MEMORY,              /**< Out of memory */
+       BM_PLUGIN_ERROR_NOT_SUPPORTED = TIZEN_ERROR_NOT_SUPPORTED,              /**< Not supported */
+       BM_PLUGIN_ERROR_SERVICE_UNAVAILABLE = TIZEN_ERROR_UNKNOWN - 1           /**< Service unavailable */
+} bm_plugin_error_e;
+
+/*
+ * enum for plugin identifier
+ */
+typedef enum {
+       BM_PLUGIN_ID_BLE = 0,           /**< plugin id for Bluetooth Low Energy */
+       BM_PLUGIN_ID_WIFI,              /**< plugin id for Wi-Fi */
+       BM_PLUGIN_ID_CPU,               /**< plugin id for CPU */
+       BM_PLUGIN_ID_DISPLAY,           /**< plugin id for Display */
+       BM_PLUGIN_ID_DEVICE_NETWORK,    /**< plugin id for Network */
+       BM_PLUGIN_ID_GPS_SENSOR,        /**< plugin id for GPS */
+       BM_PLUGIN_ID_HRM_SENSOR,        /**< plugin id for Heart Rate Monitor */
+} bm_plugin_id_e;
+
+/*
+ * enum for feature data collection period
+ */
+typedef enum {
+       BM_DURATION_TYPE_1DAY = 0,      /**< Set the period from a day ago to now */
+       BM_DURATION_TYPE_1WEEK          /**< Set the period from a week ago to now */
+} bm_duration_type_e;
+
+/*
+ * enum for feature data type
+ */
+typedef enum {
+       BM_DATA_TYPE_BLE = 0,           /**< Bluetooth Low Energy */
+       BM_DATA_TYPE_WIFI,              /**< Wi-Fi */
+       BM_DATA_TYPE_CPU,               /**< CPU */
+       BM_DATA_TYPE_DISPLAY,           /**< Display */
+       BM_DATA_TYPE_DEVICE_NETWORK,    /**< Network */
+       BM_DATA_TYPE_GPS_SENSOR,        /**< GPS */
+       BM_DATA_TYPE_HRM_SENSOR,        /**< Heart Rate Monitor */
+} bm_plugin_data_type_e;
+
+/*
+ * common structure for application time map.
+ */
+typedef struct {
+       char *app_id;           /**< application id */
+       uint time;              /**< total duration for which application as active */
+} app_time_map_st1;
+
+typedef struct {
+       char *app_id;           /**< application id */
+       uint time;              /**< total duration for which application as active */
+       uint rx;                /**< Total Bytes received by the application during runtime */
+       uint tx;                /**< Total Bytes transmitted by the application during runtime */
+} app_time_map_st2;
+
+/*
+ * structure for "display" feature data.
+ */
+typedef struct {
+       uint high;                      /**< total time in milliseconds during which brightness intensity was high */
+       uint low;                       /**< total time in milliseconds during which brightness intensity was low */
+       uint med;                       /**< total time in milliseconds during which brightness intensity was medium */
+       time_t start;                   /**< start time of feature data collection session */
+       time_t stop;                    /**< stop time of feature data collection session */
+       GSList *atm_list;               /**< application time map('app_time_map_st1') list for all active applications between start & stop */
+       GSList *display_list;           /**< list of nodes of 'bm_display_st' for next consecutive sessions */
+} bm_display_st;
+
+/*
+ * structure for "cpu" feature data.
+ */
+typedef struct {
+       uint cpuTicks;                  /**< CPU Usage during the session */
+       uint cpuTimeBackground;         /**< Time spent in Background State average operating frequency will be used to calculate the power */
+       uint cpuTimeForeground;         /**< Time spent in Foreground state average operating frequency will be used to calculate the power */
+       GSList *atm_list;               /**< application time map('app_time_map_st1') list for all active applications between start & stop */
+       GSList *cpu_data_list;          /**< list of nodes of 'bm_cpu_st' for next consecutive sessions */
+} bm_cpu_st;
+
+/*
+ * structure for "device_network" feature data.
+ */
+typedef struct {
+       uint time_level_0;              /**< Total time in milliseconds during which signal_strength was on level 0 */
+       uint time_level_1;              /**< Total time in milliseconds during which signal_strength was on level 1 */
+       uint time_level_2;              /**< Total time in milliseconds during which signal_strength was on level 2 */
+       uint time_level_3;              /**< Total time in milliseconds during which signal_strength was on level 3 */
+       uint time_level_4;              /**< Total time in milliseconds during which signal_strength was on level 4 */
+       uint time_level_5;              /**< Total time in milliseconds during which signal_strength was on level 5 */
+       uint time_level_6;              /**< Total time in milliseconds during which signal_strength was on level 6 */
+       GSList *atm_list;               /**< application time map('app_time_map_st2') list for all active applications between start & stop */
+       GSList *dn_data_list;           /**< list of nodes of 'bm_device_network_st' for next consecutive sessions */
+} bm_device_network_st;
+
+/*
+ * structure for "Wi-Fi" feature data.
+ */
+typedef struct {
+       uint time_level_0;              /**< Total time in milliseconds during which rssi was on level 0 */
+       uint time_level_1;              /**< Total time in milliseconds during which rssi was on level 1 */
+       uint time_level_2;              /**< Total time in milliseconds during which rssi was on level 2 */
+       uint time_level_3;              /**< Total time in milliseconds during which rssi was on level 3 */
+       uint time_level_4;              /**< Total time in milliseconds during which rssi was on level 4 */
+       time_t startTime;               /**< start time of feature data collection session */
+       time_t endTime;                 /**< end time of feature data collection session */
+       uint scanTime;                  /**< Total time spent by the resource in (scan) mode during the session */
+       GSList *atm_list;               /**< application time map('app_time_map_st2') list for all active applications between start & stop */
+       GSList *wifi_data_list;         /**< list of nodes of 'bm_wifi_st' for next consecutive sessions */
+} bm_wifi_st;
+
+/*
+ * structure for "bluetooth" feature data.
+ */
+typedef struct {
+       uint scanTime;                  /**< Total time spent by the resource in (scan) mode during the session */
+       uint connectedTime;             /**< Total time spent by the resource in (connected) mode during the session */
+       time_t startTime;               /**< start time of feature data collection session */
+       time_t stopTime;                /**< stop time of feature data collection session */
+       GSList *atm_list;               /**< application time map('app_time_map_st2') list for all active applications between start & stop */
+       GSList *bt_data_list;           /**< list of nodes of 'bm_bluetooth_st' for next consecutive sessions */
+} bm_bluetooth_st;
+
+/*
+ * structure for "gps" feature data.
+ */
+typedef struct {
+       time_t connStartTime;           /**< start time of feature data collection session */
+       time_t connStopTime;            /**< stop time of feature data collection session */
+       GSList *atm_list;               /**< application time map('app_time_map_st1') list for all active applications between start & stop */
+       GSList *gps_data_list;          /**< list of nodes of 'bm_gps_st' for next consecutive sessions */
+} bm_gps_st;
+
+/*
+ * structure for "hrm-sensor" feature data.
+ */
+typedef struct {
+       uint sensor_hub_wakeup_time;    /**< wake-up time of sensor-hub */
+       uint sensor_hub_wakeup_count;   /**< wake-up count of sensor-hub */
+       uint sensor_wakeup_time;        /**< sensor wake-up time */
+       uint sensor_wakeup_count;       /**< sensor wake-up count */
+       GSList *atm_list;               /**< application time map('app_time_map_st1') list for all active applications between start & stop */
+       GSList *hrm_data_list;          /**< list of nodes of 'bm_hrm_sensor_st' for next consecutive sessions */
+} bm_hrm_sensor_st;
+
+/*
+ * structure for "battery" feature data.
+ */
+typedef struct {
+       uint battery_percent;           /**< Battery percent */
+       uint is_charging;               /**< State of charging */
+} bm_battery_st;
+
+/* ========================================================================== */
+
+/*
+ * battery-monitor data handle
+ */
+typedef void *bm_data_h;
+
+/*
+ * Callback to be invoked when service is going OFF
+ *
+ * [Param] handle - handle through which service will provide data
+ *        to battery-monitor service daemon.
+ *
+ * [Param] result - the result of callback operation
+ */
+typedef void (*bm_data_callback)(bm_plugin_error_e result, bm_data_h *handle);
+
+/*
+ * battery-monitor callback structure
+ */
+typedef struct {
+       bm_data_callback provide_feature_data;
+} bm_callbacks_st;
+
+/*
+ * structure for plugin API's
+ */
+typedef struct {
+       /*
+       * [Sync API] To initialize plugin
+       */
+       int (*init)(const bm_callbacks_st *callbacks);
+       /*
+       * [Sync API] To deinitialize plugin
+       */
+       int (*deinit)(void);
+       /*
+       * [Sync API] To get feature data from plugin
+       *
+       * [Param] handle - battery-monitor data handle through which plugin
+       *       will provide data to the manager. This handle will be passed
+       *       as reference, plugin will assign a valid object which will be
+       *       set free by the manager; battery-monitor manager will typecast
+       *       the object provided through handle for each plugin and will use
+       *       it for further calculation.
+       *
+       * [Param] data_type - type of data like - BLE, Wi-Fi, CPU etc.
+       */
+       int (*get_feature_data)(bm_data_h *handle, bm_plugin_data_type_e data_type);
+} bm_api_st;
+
+/*
+ * structure for plugin information
+ */
+typedef struct {
+       /*
+       * Respective "identifier" of Plugin
+       */
+       int id;
+       /*
+       * Respective "name" of Plugin
+       */
+       const char *name;
+       /*
+       * Respective "author" of Plugin
+       */
+       const char *author;
+       /*
+       * Respective "version" of Plugin
+       */
+       const char *version;
+       /*
+       * Plugin init function
+       */
+       int (*init)(bm_api_st **api);
+       /*
+       * Plugin de-init function
+       */
+       int (*deinit)(void);
+} bm_plugin_st;
+
+
+/*
+ *  macro for adding plugin
+ */
+#define BM_PLUGIN_ADD(id, name, author, version, init, deinit) \
+               bm_plugin_st bm_plugin = { id, name, author, version, init, deinit };
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_PLUGIN_INTERFACE_H__ */
diff --git a/include/bm_plugin_manager.h b/include/bm_plugin_manager.h
new file mode 100644 (file)
index 0000000..ec0b667
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_PLUGIN_MANAGER_H__
+#define __BM_PLUGIN_MANAGER_H__
+
+#include "bm_plugin_interface.h"
+#include "bm_common.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct bm_plugin_info_s {
+       void *handle;
+       bm_plugin_st *plugin;
+       bm_api_st *api;
+};
+
+typedef struct bm_plugin_info_s bm_plugin_info_h;
+
+const bm_callbacks_st ble_cb;
+const bm_callbacks_st wifi_cb;
+const bm_callbacks_st cpu_cb;
+const bm_callbacks_st display_cb;
+const bm_callbacks_st device_network_cb;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+const bm_callbacks_st gps_cb;
+const bm_callbacks_st hrm_cb;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+/*
+ * This function provides the name of plugin for use during error handling.
+ */
+const char *bm_get_plugin_name(bm_plugin_id_e id);
+
+/*
+ * This function is responsible for providing the required plugin handle.
+ * It provides the handle for the plugin id which is passed to it.
+ */
+void bm_get_feature_plugin_handle(bm_plugin_info_h **handle, bm_plugin_id_e id);
+
+/*
+ * This function initializes the plugin manager and is respondible for:
+ * - loading feature plugins from the directory
+ * - initializing loaded plugins
+ */
+int initialize_plugin_manager(void);
+
+/*
+ * This function de-initializes the plugin manager by calling de-init
+ * function of all the loaded plugins.
+ */
+void deinitialize_plugin_manager(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_PLUGIN_MANAGER_H__ */
diff --git a/include/bm_power_engine.h b/include/bm_power_engine.h
new file mode 100644 (file)
index 0000000..f89f439
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_ENGINE_H__
+#define __BM_ENGINE_H__
+
+#include <job_scheduler.h>
+
+#include "bm_plugin_interface.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct battery_total_consumption_s {
+       int ble_val;
+       int wifi_val;
+       int cpu_val;
+       int dp_val;
+       int dn_val;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       int gps_val;
+       int hrm_val;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+       int bat_val;
+};
+
+typedef struct battery_total_consumption_s *bm_total_consumption_h;    /**< handle for total battery consumption structure */
+
+struct bm_feature_data_handles_s {
+       bm_bluetooth_st         *bm_ble_handle;
+       bm_wifi_st              *bm_wifi_handle;
+       bm_cpu_st               *bm_cpu_handle;
+       bm_display_st           *bm_display_handle;
+       bm_device_network_st    *bm_dn_handle;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       bm_gps_st               *bm_gps_handle;
+       bm_hrm_sensor_st        *bm_hrm_handle;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+};
+
+typedef struct bm_feature_data_handles_s *bm_feature_data_h;   /**< handle for feature data handle structure */
+
+struct bm_req_feature_data_handle_flag_s {
+       bool req_ble_data;
+       bool req_wifi_data;
+       bool req_cpu_data;
+       bool req_dp_data;
+       bool req_dn_data;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       bool req_gps_data;
+       bool req_hrm_data;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+};
+
+struct bm_req_feature_data_handle_flag_s *bm_req_flag_h;
+
+int bm_engine_get_usage_by_app_id_for_resource_id(const gchar *app_id, gint resource_id, gint duration, int *b_usage);
+
+int bm_engine_get_total_usage_by_app_id(const gchar *app_id, gint duration, int *b_usage);
+
+int bm_engine_get_total_usage_by_resource_id(gint resource_id, gint duration, int *b_usage);
+
+int bm_engine_get_all_resource_usage(const gchar *app_id, gint duration, bm_total_consumption_h data);
+
+/* power consumption calculation & Db commit functions*/
+int bm_ble_calc_power_and_commit(bm_bluetooth_st *handle, bool mode);
+
+int bm_wifi_calc_power_and_commit(bm_wifi_st *handle, bool mode);
+
+int bm_cpu_calc_power_and_commit(bm_cpu_st *handle, bool mode);
+
+int bm_display_calc_power_and_commit(bm_display_st *handle, bool mode);
+
+int bm_device_network_calc_power_and_commit(bm_device_network_st *handle, bool mode);
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+int bm_gps_calc_power_and_commit(bm_gps_st *handle);
+
+int bm_hrm_calc_power_and_commit(bm_hrm_sensor_st *handle);
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+int bm_battery_calc_power_and_commit(void);
+
+int bm_get_data_from_handles(void);
+
+int bm_start_getting_feature_data(void);
+
+int bm_clean_db_table_for_job_id(void);
+
+int initialize_power_engine(void);
+
+void deinitialize_power_engine(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_ENGINE_H__ */
diff --git a/include/bm_private.h b/include/bm_private.h
new file mode 100644 (file)
index 0000000..823f1fe
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ *  Battery-Monitor
+ *
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_PRIVATE_H__
+#define __BM_PRIVATE_H__
+
+#include <stdlib.h>
+#include <tizen.h>
+#include <glib.h>
+#include <system_info.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+typedef struct _appid_map_s {
+       char *AppName;
+       int AppId;
+} appid_map_s;
+
+typedef struct _appid_usage_s {
+       char *AppId;
+       long int log_time;
+       int rId_ble;
+       int rId_wifi;
+       int rId_cpu;
+       int rId_display;
+       int rId_device_network;
+       int rId_gps;
+       int rId_hrm;
+       int rId_battery;
+} appid_usage_s;
+
+typedef struct _resourceid_usage_s {
+       char *ResourceId;
+       long int log_time;
+       int usage;
+} resourceid_usage_s;
+
+/**
+ * @brief       Enumarations for Struct Fields fields.
+ */
+
+typedef enum {
+       BM_APPIDMAP_FIELD_NONE = -1,
+       BM_APPIDMAP_FIELD_APPNAME,
+       BM_APPIDMAP_FIELD_APPID,
+       BM_APPIDMAP_FIELD_END,
+} BM_APPIDMAP_DB_IDX;
+
+typedef enum {
+       BM_APPUSAGE_FIELD_NONE = -1,
+       BM_APPUSAGE_FIELD_APPID,
+       BM_APPUSAGE_FIELD_RID_BLE,
+       BM_APPUSAGE_FIELD_RID_WIFI,
+       BM_APPUSAGE_FIELD_RID_CPU,
+       BM_APPUSAGE_FIELD_RID_DISPLAY,
+       BM_APPUSAGE_FIELD_RID_DEV_NTW,
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       BM_APPUSAGE_FIELD_RID_GPS,
+       BM_APPUSAGE_FIELD_RID_HRM,
+       BM_APPUSAGE_FIELD_RID_BATTERY,
+#endif
+       BM_APPUSAGE_FIELD_END,
+} BM_APPUSAGE_DB_IDX;
+
+typedef enum {
+       BM_RESOURCEUSAGE_FIELD_NONE = -1,
+       BM_RESOURCEUSAGE_FIELD_RESID,
+       BM_RESOURCEUSAGE_FIELD_USAGE,
+       BM_RESOURCEUSAGE_FIELD_END,
+} BM_RESOURCEUSAGE_DB_IDX;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_PRIVATE_H__*/
diff --git a/include/bm_server.h b/include/bm_server.h
new file mode 100644 (file)
index 0000000..68561f2
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+
+#ifndef __BM_SERVER_H__
+#define __BM_SERVER_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <glib.h>
+
+#include "../battery_monitor_stub.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+gboolean bm_get_usage_by_app_id_for_resource_id(BatteryMonitor *obj, GDBusMethodInvocation *invocation,
+                                               const gchar *app_id, gint resource_id, gint duration, gint uid);
+
+gboolean bm_get_total_usage_by_app_id(BatteryMonitor *obj, GDBusMethodInvocation *invocation, const gchar *app_id,
+                                               gint duration, gint uid);
+
+gboolean bm_get_total_usage_by_resource_id(BatteryMonitor *obj, GDBusMethodInvocation *invocation, gint resource_id,
+                                               gint duration, gint uid);
+
+gboolean bm_get_all_resource_usage(BatteryMonitor *obj, GDBusMethodInvocation *invocation, const gchar *app_id,
+                                               gint duration, gint uid);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_SERVER_H__ */
diff --git a/include/bm_server_db.h b/include/bm_server_db.h
new file mode 100644 (file)
index 0000000..50fa068
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_SERVER_DB_H__
+#define __BM_SERVER_DB_H__
+
+#include <stdbool.h>
+#include <glib.h>
+#include <tzplatform_config.h>
+#include <db-util.h>
+#include "bm_private.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* BATTERY_DB */
+/* THIS DB IS THE DEFAULT DB TO BE USED FOR LOGGING APP BASED USAGE AND RESOURCE BASED USAGE IT WILL BE USED TO STORE PROCESSED VALUE OF THE USAGE, AND WILL BE REFERRED FOR ANSWERING API CALLS */
+
+/* List of Resources
+BM_RESOURCE_ID_BLE ==> rId_ble,
+BM_RESOURCE_ID_WIFI,
+BM_RESOURCE_ID_CPU,
+BM_RESOURCE_ID_DISPLAY,
+BM_RESOURCE_ID_DEVICE_NETWORK,
+BM_RESOURCE_ID_GPS_SENSOR,
+BM_RESOURCE_ID_ID_HRM_SENSOR,
+BM_RESOURCE_ID_BATTERY,
+BM_RESOURCE_ID_MAX,
+*/
+
+/* Battery Monitor AppId Vs Integer Map */
+/* TO DO: Cleaning of redundant records from DB */
+#define APP_ID_MAP_SCHEMA "create table appid_map \n"\
+       "(\n"\
+"AppName TEXT, "\
+"AppId INT "\
+");"
+
+/* Battery Monitor APPID Vs RESOURCE ID */
+#define APP_ID_USAGE_SCHEMA "create table appid_usage \n"\
+       "(\n"\
+"AppId TEXT, "\
+"log_time INT, "\
+"rId_ble INT, "\
+"rId_wifi INT, "\
+"rId_cpu INT, "\
+"rId_display INT, "\
+"rId_device_network INT, "\
+"rId_gps INT, "\
+"rId_hrm INT, "\
+"rId_battery INT, "\
+"rId_newone INT, "\
+"rId_newtwo INT, "\
+"rId_newthree INT "\
+");"
+
+/* Battery Monitor RESOURCE ID Vs TIME */
+/* TO DO: Adding Enum for Resources */
+#define RESOURCE_ID_USAGE_SCHEMA "create table resourceid_usage \n"\
+       "(\n"\
+"ResourceId TEXT, "\
+"log_time INT, "\
+"usage INT "\
+");"
+
+#define OWNER_ROOT 0
+
+/* Macros of Time Duration */
+#define BM_DURATION_1DAY               86400                   /*One Day in Seconds*/
+#define BM_DURATION_1WEEK              604800                  /*One Week(7 Days) in Seconds*/
+
+/* #define GLOBAL_USER tzplatform_getuid(TZ_SYS_GLOBALAPP_USER) */
+
+#define BATTERY_MONITOR_APP_ID_MAP_TABLE               "appid_map"
+#define BATTERY_MONITOR_APP_ID_USAGE_TABLE             "appid_usage"
+#define BATTERY_MONITOR_RESOURCE_ID_USAGE_TABLE                "resourceid_usage"
+#define BATTERY_MONITOR_SQLITE_SEQ                     "sqlite_sequence"
+#define BATTERY_MONITOR_SQL_LEN_MAX                    1024
+#define BATTERY_MONITOR_TABLE_COUNT                    3
+
+typedef sqlite3_stmt *bm_stmt;
+
+/* Server Functions */
+int initialize_database(void);
+
+int deinitialize_database(void);
+
+appid_usage_s *bm_server_query_app_usage_by_appid(const char *app_id, int period_type, int *error_code);
+
+int bm_server_app_usage_insert_to_db(appid_usage_s *bm_app_type);
+
+resourceid_usage_s *bm_server_query_resource_usage_resourceid(const char *resource_id, int period_type, int *error_code);
+
+int bm_server_resource_usage_insert_to_db(resourceid_usage_s *bm_resource_type);
+
+int bm_server_delete_table_by_appid(const char* app_id);
+
+int bm_server_delete_table_by_time_interval(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_SERVER_DB_H__ */
diff --git a/include/bm_util.h b/include/bm_util.h
new file mode 100644 (file)
index 0000000..114de87
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#ifndef __BM_UTIL_H__
+#define __BM_UTIL_H__
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <glib.h>
+
+#if !GLIB_CHECK_VERSION(2, 31, 0)
+#include <glib/gmacros.h>
+#endif
+
+#include "../battery_monitor_stub.h"
+#include "bm_power_engine.h"
+#include "bm_private.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+GQuark bm_error_quark(void);
+
+int bm_check_privilege_battery(GDBusMethodInvocation *invocation);
+
+int bm_calc_individual_consumption(int resource_val, int total_consumption);
+
+GVariant* bm_marshal_serialized_data(const bm_total_consumption_h data);
+
+const char *bm_get_resource_id_string(gint resource_id);
+
+void bm_data_free(gpointer data);
+
+void bm_atm_st1_free(gpointer data);
+
+void bm_atm_st2_free(gpointer data);
+
+void bm_appid_usage_free(appid_usage_s *data);
+
+void bm_resourceid_usage_free(resourceid_usage_s *data);
+
+long int bm_get_log_time();
+
+void bm_set_free_atm_st2_list(GSList *atm_list);
+
+void bm_set_free_atm_st1_list(GSList *atm_list);
+
+void bm_set_free_ble_data_handle(bm_bluetooth_st *handle);
+
+void bm_set_free_wifi_data_handle(bm_wifi_st *handle);
+
+void bm_set_free_cpu_data_handle(bm_cpu_st *handle);
+
+void bm_set_free_display_data_handle(bm_display_st *handle);
+
+void bm_set_free_device_network_data_handle(bm_device_network_st *handle);
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+void bm_set_free_gps_sensor_data_handle(bm_gps_st *handle);
+
+void bm_set_free_hrm_sensor_data_handle(bm_hrm_sensor_st *handle);
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+void bm_set_free_data_handles(bm_feature_data_h data_h);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __BM_UTIL_H__ */
+
diff --git a/packaging/battery-monitor.xml b/packaging/battery-monitor.xml
new file mode 100644 (file)
index 0000000..7e052b1
--- /dev/null
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<node name="/org/tizen/battery/monitor">
+  <interface name="org.tizen.battery.monitor">
+    <method name="get_usage_by_app_id_for_resource_id">
+       <arg type="s" name="app_id" direction="in" />
+       <arg type="i" name="resource_id" direction="in" />
+       <arg type="i" name="duration" direction="in" />
+       <arg type="i" name="uid" direction="in" />
+       <arg type="i" name="battery_usage" direction="out" />
+    </method>
+    <method name="get_total_usage_by_app_id">
+       <arg type="s" name="app_id" direction="in" />
+       <arg type="i" name="duration" direction="in" />
+       <arg type="i" name="uid" direction="in" />
+       <arg type="i" name="battery_usage" direction="out" />
+    </method>
+    <method name="get_total_usage_by_resource_id">
+       <arg type="i" name="resource_id" direction="in" />
+       <arg type="i" name="duration" direction="in" />
+       <arg type="i" name="uid" direction="in" />
+       <arg type="i" name="battery_usage" direction="out" />
+    </method>
+    <method name="get_all_resource_usage">
+       <arg type="s" name="app_id" direction="in" />
+       <arg type="i" name="duration" direction="in" />
+       <arg type="i" name="uid" direction="in" />
+       <arg type="a{sv}" name="battery_data" direction="out" />
+    </method>
+  </interface>
+</node>
+
diff --git a/packaging/batterymonitor.manifest b/packaging/batterymonitor.manifest
new file mode 100644 (file)
index 0000000..97e8c31
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+       <request>
+               <domain name="_"/>
+       </request>
+</manifest>
diff --git a/packaging/batterymonitor.service b/packaging/batterymonitor.service
new file mode 100644 (file)
index 0000000..4eff9ed
--- /dev/null
@@ -0,0 +1,17 @@
+[Unit]
+Description=BatteryMonitor Service Daemon
+After=dbus.socket
+Requires=dbus.socket
+
+[Service]
+User=service_fw
+Group=service_fw
+Type=dbus
+BusName=org.tizen.battery.monitor
+ExecStart=/usr/bin/batterymonitor-svcd
+Restart=on-failure
+SmackProcessLabel=System
+
+[Install]
+WantedBy=multi-user.target
+
diff --git a/packaging/batterymonitor.spec b/packaging/batterymonitor.spec
new file mode 100644 (file)
index 0000000..483417f
--- /dev/null
@@ -0,0 +1,108 @@
+Name:          batterymonitor
+Summary:       batterymonitor service daemon
+Version:       0.0.1
+Release:       1
+License:       Apache-2.0
+Source0:       %{name}-%{version}.tar.gz
+Source1:       org.tizen.battery.monitor.service
+Source2:       org.tizen.battery.monitor.conf
+Source3:       batterymonitor.service
+Source4:       batterymonitor.manifest
+
+BuildRequires:  cmake
+BuildRequires:  pkgconfig(dlog)
+BuildRequires:  pkgconfig(capi-system-info)
+BuildRequires:  pkgconfig(glib-2.0) >= 2.26
+BuildRequires:  pkgconfig(gio-2.0)
+BuildRequires:  pkgconfig(gio-unix-2.0)
+BuildRequires:  pkgconfig(db-util)
+BuildRequires:  pkgconfig(sqlite3)
+BuildRequires:  pkgconfig(pkgmgr-info)
+BuildRequires:  pkgconfig(cynara-client)
+BuildRequires:  pkgconfig(cynara-session)
+BuildRequires:  pkgconfig(cynara-creds-gdbus)
+BuildRequires:  pkgconfig(libtzplatform-config)
+BuildRequires:  pkgconfig(json-c)
+BuildRequires:  pkgconfig(capi-appfw-job-scheduler)
+BuildRequires:  pkgconfig(capi-system-device)
+
+Requires(post): /sbin/ldconfig
+Requires(postun): /sbin/ldconfig
+
+%define power_profile_config_path /usr/etc/batterymonitor/config
+
+%description
+Battery-Monitor Service Daemon
+
+
+%prep
+%setup -q
+cp -a %{SOURCE1} .
+cp -a %{SOURCE2} .
+cp -a %{SOURCE3} .
+cp %{SOURCE4} .
+
+%build
+MAJORVER=`echo %{version} | awk 'BEGIN {FS="."}{print $1}'`
+cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} \
+               -DLIB_INSTALL_DIR=%{_libdir} \
+               -DBIN_INSTALL_DIR=%{_bindir} \
+               -DINCLUDE_INSTALL_DIR=%{_includedir} \
+               -DLIB_PATH=%{_lib} \
+               -DFULLVER=%{version} \
+               -DMAJORVER=${MAJORVER}
+
+%install
+%make_install
+mkdir -p %{buildroot}/usr/etc/batterymonitor/config
+cp config/bm_power_profile_params.json %{buildroot}%{power_profile_config_path}/bm_power_profile_params.json
+
+mkdir -p %{buildroot}%{_sysconfdir}/dbus-1/system.d
+cp org.tizen.battery.monitor.conf %{buildroot}%{_sysconfdir}/dbus-1/system.d/org.tizen.battery.monitor.conf
+
+mkdir -p %{buildroot}%{_datadir}/dbus-1/system-services/
+cp org.tizen.battery.monitor.service %{buildroot}%{_datadir}/dbus-1/system-services/org.tizen.battery.monitor.service
+
+mkdir -p %{buildroot}%{_unitdir}/multi-user.target.wants
+cp batterymonitor.service %{buildroot}%{_unitdir}/batterymonitor.service
+ln -s ../batterymonitor.service %{buildroot}%{_unitdir}/multi-user.target.wants/batterymonitor.service
+
+rm %{buildroot}%{_includedir}/battery_monitor_stub.h
+
+
+%post
+/sbin/ldconfig
+
+mkdir -p %{TZ_SYS_DB}
+if [ ! -f %{TZ_SYS_DB}/.battery-monitor.db ]
+then
+       sqlite3 %{TZ_SYS_DB}/.battery-monitor.db 'PRAGMA journal_mode = PERSIST;
+       CREATE TABLE if not exists appid_map (AppName TEXT, AppId INT);
+       CREATE TABLE if not exists appid_usage (AppId TEXT, log_time INT, rId_ble INT, rId_wifi INT, rId_cpu INT, rId_display INT, rId_device_network INT,
+       rId_gps INT, rId_hrm INT, rId_battery INT, rId_newone INT, rId_newtwo INT, rId_newthree INT);
+       CREATE TABLE if not exists resourceid_usage (ReourceId TEXT, log_time INT, usage INT);
+'
+fi
+
+chown service_fw:service_fw %{TZ_SYS_DB}/.battery-monitor.db
+chown service_fw:service_fw %{TZ_SYS_DB}/.battery-monitor.db-journal
+
+chmod 644 %{TZ_SYS_DB}/.battery-monitor.db
+chmod 644 %{TZ_SYS_DB}/.battery-monitor.db-journal
+
+#smack labeling
+chsmack -a "System" %{TZ_SYS_DB}/.battery-monitor.db
+chsmack -a "System" %{TZ_SYS_DB}/.battery-monitor.db-journal
+
+%postun -p /sbin/ldconfig
+
+%files
+%manifest %{name}.manifest
+%license LICENSE
+%defattr(-,root,root)
+%attr(755,-,-) %{_bindir}/batterymonitor-svcd
+%config %{_sysconfdir}/dbus-1/system.d/org.tizen.battery.monitor.conf
+%config %attr(755,root,root) %{power_profile_config_path}/bm_power_profile_params.json
+%attr(644,root,root) %{_datadir}/dbus-1/system-services/*
+%attr(644,root,root) %{_unitdir}/batterymonitor.service
+%attr(644,root,root) %{_unitdir}/multi-user.target.wants/batterymonitor.service
diff --git a/packaging/org.tizen.battery.monitor.conf b/packaging/org.tizen.battery.monitor.conf
new file mode 100644 (file)
index 0000000..16ef9d0
--- /dev/null
@@ -0,0 +1,25 @@
+<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
+"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
+<busconfig>
+       <policy user="root">
+               <allow own="org.tizen.battery.monitor"/>
+               <allow send_destination="org.tizen.battery.monitor"/>
+       </policy>
+       <policy user="service_fw">
+               <allow own="org.tizen.battery.monitor"/>
+               <allow send_destination="org.tizen.battery.monitor"/>
+       </policy>
+       <policy context="default">
+               <deny own="org.tizen.battery.monitor"/>
+               <deny send_destination="org.tizen.battery.monitor"/>
+
+               <check send_destination="org.tizen.battery.monitor" send_interface="org.tizen.battery.monitor"
+                       send_member="get_usage_by_app_id_for_resource_id" privilege="http://tizen.org/privilege/systemmonitor"/>
+               <check send_destination="org.tizen.battery.monitor" send_interface="org.tizen.battery.monitor"
+                       send_member="get_total_usage_by_app_id" privilege="http://tizen.org/privilege/systemmonitor"/>
+               <check send_destination="org.tizen.battery.monitor" send_interface="org.tizen.battery.monitor"
+                       send_member="get_total_usage_by_resource_id" privilege="http://tizen.org/privilege/systemmonitor"/>
+               <check send_destination="org.tizen.battery.monitor" send_interface="org.tizen.battery.monitor"
+                       send_member="get_all_resource_usage" privilege="http://tizen.org/privilege/systemmonitor"/>
+       </policy>
+</busconfig>
diff --git a/packaging/org.tizen.battery.monitor.service b/packaging/org.tizen.battery.monitor.service
new file mode 100644 (file)
index 0000000..eb2c05d
--- /dev/null
@@ -0,0 +1,7 @@
+[Unit]
+Description=BatteryMonitor Service DBUS
+
+[D-BUS Service]
+Name=org.tizen.battery.monitor
+Exec=/bin/false
+SystemdService=batterymonitor.service
diff --git a/src/bm_callback_handler.c b/src/bm_callback_handler.c
new file mode 100644 (file)
index 0000000..9c47084
--- /dev/null
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include "bm_plugin_interface.h"
+#include "bm_power_engine.h"
+#include "bm_common.h"
+#include "bm_util.h"
+
+void bm_receive_ble_feature_data(bm_plugin_error_e result, bm_data_h *handle)
+{
+       ENTER;
+
+       if (!handle || (result != BM_PLUGIN_ERROR_NONE)) {
+               _ERR("incorrect input param");
+               return;
+       }
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _DBG("received ble data");
+
+       bm_bluetooth_st *bt_data_h = (bm_bluetooth_st *)handle;
+
+       ret_val = bm_ble_calc_power_and_commit(bt_data_h, true);
+
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to calculate ble power");
+               return;
+       }
+
+       /* set flag for skipping next period request */
+       bm_req_flag_h->req_ble_data = false;
+
+       bm_set_free_ble_data_handle(bt_data_h);
+
+       EXIT;
+       return;
+}
+
+void bm_receive_wifi_feature_data(bm_plugin_error_e result, bm_data_h *handle)
+{
+       ENTER;
+
+       if (!handle || (result != BM_PLUGIN_ERROR_NONE)) {
+               _ERR("incorrect input param");
+               return;
+       }
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _DBG("received wifi data");
+
+       bm_wifi_st *wifi_data_h = (bm_wifi_st *)handle;
+
+       ret_val = bm_wifi_calc_power_and_commit(wifi_data_h, true);
+
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to calculate wifi power");
+               return;
+       }
+
+       /* set flag for skipping next period request */
+       bm_req_flag_h->req_wifi_data = false;
+
+       bm_set_free_wifi_data_handle(wifi_data_h);
+
+       EXIT;
+       return;
+}
+
+void bm_receive_cpu_feature_data(bm_plugin_error_e result, bm_data_h *handle)
+{
+       ENTER;
+
+       if (!handle || (result != BM_PLUGIN_ERROR_NONE)) {
+               _ERR("incorrect input param");
+               return;
+       }
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _DBG("received cpu data");
+
+       bm_cpu_st *cpu_data_h = (bm_cpu_st *)handle;
+
+       ret_val = bm_cpu_calc_power_and_commit(cpu_data_h, true);
+
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to calculate cpu power");
+               return;
+       }
+
+       /* set flag for skipping next period request */
+       bm_req_flag_h->req_cpu_data = false;
+
+       bm_set_free_cpu_data_handle(cpu_data_h);
+
+       EXIT;
+       return;
+}
+
+void bm_receive_display_feature_data(bm_plugin_error_e result, bm_data_h *handle)
+{
+       ENTER;
+
+       if (!handle || (result != BM_PLUGIN_ERROR_NONE)) {
+               _ERR("incorrect input param");
+               return;
+       }
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _DBG("received display data");
+
+       bm_display_st *display_data_h = (bm_display_st *)handle;
+
+       ret_val = bm_display_calc_power_and_commit(display_data_h, true);
+
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to calculate display power");
+               return;
+       }
+
+       /* set flag for skipping next period request */
+       bm_req_flag_h->req_dp_data = false;
+
+       bm_set_free_display_data_handle(display_data_h);
+
+       EXIT;
+       return;
+}
+
+void bm_receive_device_network_feature_data(bm_plugin_error_e result, bm_data_h *handle)
+{
+       ENTER;
+
+       if (!handle || (result != BM_PLUGIN_ERROR_NONE)) {
+               _ERR("incorrect input param");
+               return;
+       }
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _DBG("received device network data");
+
+       bm_device_network_st *device_network_data_h = (bm_device_network_st *)handle;
+
+       ret_val = bm_device_network_calc_power_and_commit(device_network_data_h, true);
+
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to calculate device-network power");
+               return;
+       }
+
+       /* set flag for skipping next period request */
+       bm_req_flag_h->req_dn_data = false;
+
+       bm_set_free_device_network_data_handle(device_network_data_h);
+
+       EXIT;
+       return;
+}
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+void bm_receive_gps_sensor_feature_data(bm_plugin_error_e result, bm_data_h *handle)
+{
+       ENTER;
+
+       if (!handle || (result != BM_PLUGIN_ERROR_NONE)) {
+               _ERR("incorrect input param");
+               return;
+       }
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _DBG("received gps-sensor data");
+
+       bm_gps_st *gps_data_h = (bm_gps_st *)handle;
+
+       ret_val = bm_gps_calc_power_and_commit(gps_data_h);
+
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to calculate gps-sensor power");
+               return;
+       }
+
+       /* set flag for skipping next period request */
+       bm_req_flag_h->req_gps_data = false;
+
+       bm_set_free_gps_sensor_data_handle(gps_data_h);
+
+       EXIT;
+       return;
+}
+
+void bm_receive_hrm_sensor_feature_data(bm_plugin_error_e result, bm_data_h *handle)
+{
+       ENTER;
+
+       if (!handle || (result != BM_PLUGIN_ERROR_NONE)) {
+               _ERR("incorrect input param");
+               return;
+       }
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _DBG("received hrm-sensor data");
+
+       bm_hrm_sensor_st *hrm_sensor_data_h = (bm_hrm_sensor_st *)handle;
+
+       ret_val = bm_hrm_calc_power_and_commit(hrm_sensor_data_h);
+
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to calculate hrm-sensor power");
+               return;
+       }
+
+       /* set flag for skipping next period request */
+       bm_req_flag_h->req_hrm_data = false;
+
+       bm_set_free_hrm_sensor_data_handle(hrm_sensor_data_h);
+
+       EXIT;
+       return;
+}
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+bm_callbacks_st bm_receiver_callbacks[BATTERY_MONITOR_CALLBACKS_MAX] = \
+                       {       { .provide_feature_data = bm_receive_ble_feature_data },
+                               { .provide_feature_data = bm_receive_wifi_feature_data },
+                               { .provide_feature_data = bm_receive_cpu_feature_data },
+                               { .provide_feature_data = bm_receive_display_feature_data },
+                               { .provide_feature_data = bm_receive_device_network_feature_data },
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+                               { .provide_feature_data = bm_receive_gps_sensor_feature_data },
+                               { .provide_feature_data = bm_receive_hrm_sensor_feature_data }
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+                       };
diff --git a/src/bm_config_parser.c b/src/bm_config_parser.c
new file mode 100644 (file)
index 0000000..1c7bdaa
--- /dev/null
@@ -0,0 +1,552 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <glib.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <json-c/json.h>
+
+#include "bm_dbg.h"
+#include "bm_common.h"
+#include "bm_config_parser.h"
+
+static char* bm_read_content_from_file(const char *file_name)
+{
+       ENTER;
+
+       gsize len = 0;
+       gchar *contents;
+       GError *error = NULL;
+
+       if (!file_name) {
+               _ERR("invalid param");
+               goto END;
+       }
+
+       if (!g_file_test(file_name, G_FILE_TEST_EXISTS)) {
+               _ERR("file not available");
+               goto END;
+       }
+
+       g_file_get_contents(file_name, &contents, &len, &error);
+       if (error) {
+               _ERR("Unable to read file [%s] with error: [%s]",
+                                               file_name, error->message);
+               g_error_free(error);
+               goto END;
+       }
+
+       if (!contents) {
+               _ERR("content not read");
+               goto END;
+       }
+
+       _INFO("read [%zd] bytes from [%s]", len, file_name);
+
+       EXIT;
+       return (char *)contents;
+END:
+       return NULL;
+}
+
+int bm_get_wifi_power_params(int *rssi_l0, int *rssi_l1, int *rssi_l2, int *rssi_l3,
+                                       int *rssi_l4, int *scan, int *idle, int *rx, int *tx)
+{
+       ENTER;
+
+       int ret = BATTERY_MONITOR_ERROR_INTERNAL;
+
+       char *contents = NULL;
+       json_object *jmain = NULL, *jint = NULL, *jvalue = NULL;
+
+       BM_CHECK_INPUT_PARAM(rssi_l0);
+       BM_CHECK_INPUT_PARAM(rssi_l1);
+       BM_CHECK_INPUT_PARAM(rssi_l2);
+       BM_CHECK_INPUT_PARAM(rssi_l3);
+       BM_CHECK_INPUT_PARAM(rssi_l4);
+       BM_CHECK_INPUT_PARAM(scan);
+       BM_CHECK_INPUT_PARAM(idle);
+       BM_CHECK_INPUT_PARAM(rx);
+       BM_CHECK_INPUT_PARAM(tx);
+
+       contents = bm_read_content_from_file(BATTERY_MONITOR_CONFIG_FILE_PATH);
+
+       BM_RETURN_VAL((contents != NULL), {},
+               BATTERY_MONITOR_ERROR_NO_DATA, "failed to read from file");
+
+       jmain = json_tokener_parse(contents);
+       if (!jmain)
+               goto END;
+
+       /* wifi power profile parameters */
+       json_object_object_get_ex(jmain, "wifi", &jvalue);
+       if (!jvalue)
+               goto END;
+
+       json_object_object_get_ex(jvalue, "p_wifi_rssi_0", &jint);
+       if (!jint)
+               goto END;
+       *rssi_l0 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_wifi_rssi_1", &jint);
+       if (!jint)
+               goto END;
+       *rssi_l1 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_wifi_rssi_2", &jint);
+       if (!jint)
+               goto END;
+       *rssi_l2 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_wifi_rssi_3", &jint);
+       if (!jint)
+               goto END;
+       *rssi_l3 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_wifi_rssi_4", &jint);
+       if (!jint)
+               goto END;
+       *rssi_l4 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_wifi_scan", &jint);
+       if (!jint)
+               goto END;
+       *scan = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_wifi_idle", &jint);
+       if (!jint)
+               goto END;
+       *idle = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_wifi_rx", &jint);
+       if (!jint)
+               goto END;
+       *rx = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_wifi_tx", &jint);
+       if (!jint)
+               goto END;
+       *tx = json_object_get_int(jint);
+
+       _DBG("wifi power params - rssi_0[%d], rssi_1[%d], rssi_2[%d], \
+               rssi_3[%d], rssi_4[%d], scan[%d], idle[%d], rx[%d], tx[%d]", \
+               *rssi_l0, *rssi_l1, *rssi_l2, *rssi_l3, *rssi_l4, *scan, \
+               *idle, *rx, *tx);
+
+       ret = BATTERY_MONITOR_ERROR_NONE;
+END:
+       g_free(contents);
+       if (jmain)
+               json_object_put(jmain);
+
+       EXIT;
+       return ret;
+}
+
+int bm_get_blutooth_power_params(int *idle, int *scan, int *connected, int *rx, int *tx)
+{
+       ENTER;
+
+       int ret = BATTERY_MONITOR_ERROR_INTERNAL;
+
+       char *contents = NULL;
+       json_object *jmain = NULL, *jint = NULL, *jvalue = NULL;
+
+       BM_CHECK_INPUT_PARAM(idle);
+       BM_CHECK_INPUT_PARAM(scan);
+       BM_CHECK_INPUT_PARAM(connected);
+       BM_CHECK_INPUT_PARAM(rx);
+       BM_CHECK_INPUT_PARAM(tx);
+
+       contents = bm_read_content_from_file(BATTERY_MONITOR_CONFIG_FILE_PATH);
+
+       BM_RETURN_VAL((contents != NULL), {},
+               BATTERY_MONITOR_ERROR_NO_DATA, "failed to read from file");
+
+       jmain = json_tokener_parse(contents);
+       if (!jmain)
+               goto END;
+
+       /* bluetooth power profile parameters */
+       json_object_object_get_ex(jmain, "bluetooth", &jvalue);
+       if (!jvalue)
+               goto END;
+
+       json_object_object_get_ex(jvalue, "p_bt_idle", &jint);
+       if (!jint)
+               goto END;
+       *idle = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_bt_scan", &jint);
+       if (!jint)
+               goto END;
+       *scan = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_bt_connected", &jint);
+       if (!jint)
+               goto END;
+       *connected = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_bt_rx", &jint);
+       if (!jint)
+               goto END;
+       *rx = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_bt_tx", &jint);
+       if (!jint)
+               goto END;
+       *tx = json_object_get_int(jint);
+
+       _DBG("bluetooth power params - idle[%d], scan[%d], connected[%d], \
+               rx[%d], tx[%d]", *idle, *scan, *connected, *rx, *tx);
+
+       ret = BATTERY_MONITOR_ERROR_NONE;
+END:
+       g_free(contents);
+       if (jmain)
+               json_object_put(jmain);
+
+       EXIT;
+       return ret;
+}
+
+int bm_get_device_network_power_params(int *signal_strength0, int *signal_strength1, int *signal_strength2,
+                                       int *signal_strength3, int *signal_strength4, int *signal_strength5,
+                                       int *signal_strength6, int *rx, int *tx)
+{
+       ENTER;
+
+       int ret = BATTERY_MONITOR_ERROR_INTERNAL;
+
+       char *contents = NULL;
+       json_object *jmain = NULL, *jint = NULL, *jvalue = NULL;
+
+       BM_CHECK_INPUT_PARAM(signal_strength0);
+       BM_CHECK_INPUT_PARAM(signal_strength1);
+       BM_CHECK_INPUT_PARAM(signal_strength2);
+       BM_CHECK_INPUT_PARAM(signal_strength3);
+       BM_CHECK_INPUT_PARAM(signal_strength4);
+       BM_CHECK_INPUT_PARAM(signal_strength5);
+       BM_CHECK_INPUT_PARAM(signal_strength6);
+       BM_CHECK_INPUT_PARAM(rx);
+       BM_CHECK_INPUT_PARAM(tx);
+
+       contents = bm_read_content_from_file(BATTERY_MONITOR_CONFIG_FILE_PATH);
+
+       BM_RETURN_VAL((contents != NULL), {},
+               BATTERY_MONITOR_ERROR_NO_DATA, "failed to read from file");
+
+       jmain = json_tokener_parse(contents);
+       if (!jmain)
+               goto END;
+
+       /* device-network power profile params */
+       json_object_object_get_ex(jmain, "device_network", &jvalue);
+       if (!jvalue)
+               goto END;
+
+       json_object_object_get_ex(jvalue, "p_dnw_sig_strength_0", &jint);
+       if (!jint)
+               goto END;
+       *signal_strength0 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dnw_sig_strength_1", &jint);
+       if (!jint)
+               goto END;
+       *signal_strength1 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dnw_sig_strength_2", &jint);
+       if (!jint)
+               goto END;
+       *signal_strength2 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dnw_sig_strength_3", &jint);
+       if (!jint)
+               goto END;
+       *signal_strength3 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dnw_sig_strength_4", &jint);
+       if (!jint)
+               goto END;
+       *signal_strength4 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dnw_sig_strength_5", &jint);
+       if (!jint)
+               goto END;
+       *signal_strength5 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dnw_sig_strength_6", &jint);
+       if (!jint)
+               goto END;
+       *signal_strength6 = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dnw_rx", &jint);
+       if (!jint)
+               goto END;
+       *rx = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dnw_tx", &jint);
+       if (!jint)
+               goto END;
+       *tx = json_object_get_int(jint);
+
+       _DBG("device-network power params - signal_strength0[%d], signal_strength1[%d], signal_strength2[%d], \
+               signal_strength3[%d], signal_strength4[%d], signal_strength5[%d], signal_strength6[%d], rx[%d], \
+               tx[%d]", *signal_strength0, *signal_strength1, *signal_strength2, *signal_strength3, \
+               *signal_strength4, *signal_strength5, *signal_strength6, *rx, *tx);
+
+       ret = BATTERY_MONITOR_ERROR_NONE;
+END:
+       g_free(contents);
+       if (jmain)
+               json_object_put(jmain);
+
+       EXIT;
+       return ret;
+}
+
+int bm_get_display_power_params(int *high, int *medium, int *low)
+{
+       ENTER;
+
+       int ret = BATTERY_MONITOR_ERROR_INTERNAL;
+
+       char *contents = NULL;
+       json_object *jmain = NULL, *jint = NULL, *jvalue = NULL;
+
+       BM_CHECK_INPUT_PARAM(high);
+       BM_CHECK_INPUT_PARAM(medium);
+       BM_CHECK_INPUT_PARAM(low);
+
+       contents = bm_read_content_from_file(BATTERY_MONITOR_CONFIG_FILE_PATH);
+
+       BM_RETURN_VAL((contents != NULL), {},
+               BATTERY_MONITOR_ERROR_NO_DATA, "failed to read from file");
+
+       jmain = json_tokener_parse(contents);
+       if (!jmain)
+               goto END;
+
+       /* display power profile params */
+       json_object_object_get_ex(jmain, "display", &jvalue);
+       if (!jvalue)
+               goto END;
+
+       json_object_object_get_ex(jvalue, "p_dp_high", &jint);
+       if (!jint)
+               goto END;
+       *high = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dp_medium", &jint);
+       if (!jint)
+               goto END;
+       *medium = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_dp_low", &jint);
+       if (!jint)
+               goto END;
+       *low = json_object_get_int(jint);
+
+       _DBG("display power params - high[%d], medium[%d], low[%d]",
+                       *high, *medium, *low);
+
+       ret = BATTERY_MONITOR_ERROR_NONE;
+END:
+       g_free(contents);
+       if (jmain)
+               json_object_put(jmain);
+
+       EXIT;
+       return ret;
+}
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM
+int bm_get_gps_sensor_power_params(int *gps_use)
+{
+       ENTER;
+
+       int ret = BATTERY_MONITOR_ERROR_INTERNAL;
+
+       char *contents = NULL;
+       json_object *jmain = NULL, *jint = NULL, *jvalue = NULL;
+
+       BM_CHECK_INPUT_PARAM(gps_use);
+
+       contents = bm_read_content_from_file(BATTERY_MONITOR_CONFIG_FILE_PATH);
+
+       BM_RETURN_VAL((contents != NULL), {},
+               BATTERY_MONITOR_ERROR_NO_DATA, "failed to read from file");
+
+       jmain = json_tokener_parse(contents);
+       if (!jmain)
+               goto END;
+
+       /* device-network power profile params */
+       json_object_object_get_ex(jmain, "gps_sensor", &jvalue);
+       if (!jvalue)
+               goto END;
+
+       json_object_object_get_ex(jvalue, "p_gps_inuse", &jint);
+       if (!jint)
+               goto END;
+       *gps_use = json_object_get_int(jint);
+
+       _DBG("gps-sensor power params - gps[%d]", *gps_use);
+
+       ret = BATTERY_MONITOR_ERROR_NONE;
+END:
+       g_free(contents);
+       if (jmain)
+               json_object_put(jmain);
+
+       EXIT;
+       return ret;
+}
+
+int bm_get_hrm_sensor_power_params(int *hrm_use)
+{
+       ENTER;
+
+       int ret = BATTERY_MONITOR_ERROR_INTERNAL;
+
+       char *contents = NULL;
+       json_object *jmain = NULL, *jint = NULL, *jvalue = NULL;
+
+       BM_CHECK_INPUT_PARAM(hrm_use);
+
+       contents = bm_read_content_from_file(BATTERY_MONITOR_CONFIG_FILE_PATH);
+
+       BM_RETURN_VAL((contents != NULL), {},
+               BATTERY_MONITOR_ERROR_NO_DATA, "failed to read from file");
+
+       jmain = json_tokener_parse(contents);
+       if (!jmain)
+               goto END;
+
+       /* device-network power profile params */
+       json_object_object_get_ex(jmain, "hrm_sensor", &jvalue);
+       if (!jvalue)
+               goto END;
+
+       json_object_object_get_ex(jvalue, "p_hrm_inuse", &jint);
+       if (!jint)
+               goto END;
+       *hrm_use = json_object_get_int(jint);
+
+       _DBG("hrm-sensor power params - gps[%d]", *hrm_use);
+
+       ret = BATTERY_MONITOR_ERROR_NONE;
+END:
+       g_free(contents);
+       if (jmain)
+               json_object_put(jmain);
+
+       EXIT;
+       return ret;
+}
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM */
+
+int bm_get_cpu_power_params(int *fg, int *bg)
+{
+       ENTER;
+
+       int ret = BATTERY_MONITOR_ERROR_INTERNAL;
+
+       char *contents = NULL;
+       json_object *jmain = NULL, *jint = NULL, *jvalue = NULL;
+
+       BM_CHECK_INPUT_PARAM(fg);
+       BM_CHECK_INPUT_PARAM(bg);
+
+       contents = bm_read_content_from_file(BATTERY_MONITOR_CONFIG_FILE_PATH);
+
+       BM_RETURN_VAL((contents != NULL), {},
+               BATTERY_MONITOR_ERROR_NO_DATA, "failed to read from file");
+
+       jmain = json_tokener_parse(contents);
+       if (!jmain)
+               goto END;
+
+       /* cpu power profile params */
+       json_object_object_get_ex(jmain, "cpu", &jvalue);
+       if (!jvalue)
+               goto END;
+
+       json_object_object_get_ex(jvalue, "p_cpu_fg", &jint);
+       if (!jint)
+               goto END;
+       *fg = json_object_get_int(jint);
+
+       json_object_object_get_ex(jvalue, "p_cpu_bg", &jint);
+       if (!jint)
+               goto END;
+       *bg = json_object_get_int(jint);
+
+       _DBG("cpu power params - fg[%d], bg[%d]", *fg, *bg);
+
+       ret = BATTERY_MONITOR_ERROR_NONE;
+END:
+       g_free(contents);
+       if (jmain)
+               json_object_put(jmain);
+
+       EXIT;
+       return ret;
+}
+
+int bm_get_battery_power_params(int *battery)
+{
+       ENTER;
+
+       int ret = BATTERY_MONITOR_ERROR_INTERNAL;
+
+       char *contents = NULL;
+       json_object *jmain = NULL, *jint = NULL, *jvalue = NULL;
+
+       BM_CHECK_INPUT_PARAM(battery);
+
+       contents = bm_read_content_from_file(BATTERY_MONITOR_CONFIG_FILE_PATH);
+
+       BM_RETURN_VAL((contents != NULL), {},
+               BATTERY_MONITOR_ERROR_NO_DATA, "failed to read from file");
+
+       jmain = json_tokener_parse(contents);
+       if (!jmain)
+               goto END;
+
+       /* device-network power profile params */
+       json_object_object_get_ex(jmain, "battery", &jvalue);
+       if (!jvalue)
+               goto END;
+
+       json_object_object_get_ex(jvalue, "p_battery", &jint);
+       if (!jint)
+               goto END;
+       *battery = json_object_get_int(jint);
+
+       _DBG("battery power params - battery[%d]", *battery);
+
+       ret = BATTERY_MONITOR_ERROR_NONE;
+END:
+       g_free(contents);
+       if (jmain)
+               json_object_put(jmain);
+
+       EXIT;
+       return ret;
+}
diff --git a/src/bm_plugin_manager.c b/src/bm_plugin_manager.c
new file mode 100644 (file)
index 0000000..133aa86
--- /dev/null
@@ -0,0 +1,320 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <dlfcn.h>
+
+#include "bm_plugin_interface.h"
+#include "bm_plugin_manager.h"
+
+bm_plugin_info_h *plugins[BATTERY_MONITOR_PLUGINS_MAX];
+
+extern const bm_callbacks_st *bm_receiver_callbacks[BATTERY_MONITOR_CALLBACKS_MAX];
+
+void bm_populate_callbacks(void)
+{
+       ENTER;
+
+       bm_receiver_callbacks[BM_DATA_TYPE_BLE] = &ble_cb;
+       bm_receiver_callbacks[BM_DATA_TYPE_WIFI] = &wifi_cb;
+       bm_receiver_callbacks[BM_DATA_TYPE_CPU] = &cpu_cb;
+       bm_receiver_callbacks[BM_DATA_TYPE_DISPLAY] = &display_cb;
+       bm_receiver_callbacks[BM_DATA_TYPE_DEVICE_NETWORK] = &device_network_cb;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       bm_receiver_callbacks[BM_DATA_TYPE_GPS_SENSOR] = &gps_cb;
+       bm_receiver_callbacks[BM_DATA_TYPE_HRM_SENSOR] = &hrm_cb;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+       EXIT;
+       return;
+}
+
+const char *bm_get_plugin_name(bm_plugin_id_e id)
+{
+       switch (id) {
+       BM_ENUM_ID_TO_STR(BM_PLUGIN_ID_BLE)
+       BM_ENUM_ID_TO_STR(BM_PLUGIN_ID_WIFI)
+       BM_ENUM_ID_TO_STR(BM_PLUGIN_ID_CPU)
+       BM_ENUM_ID_TO_STR(BM_PLUGIN_ID_DISPLAY)
+       BM_ENUM_ID_TO_STR(BM_PLUGIN_ID_DEVICE_NETWORK)
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       BM_ENUM_ID_TO_STR(BM_PLUGIN_ID_GPS_SENSOR)
+       BM_ENUM_ID_TO_STR(BM_PLUGIN_ID_HRM_SENSOR)
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+       default:
+               return "UNKNOWN PLUGIN NAME";
+       }
+}
+
+void bm_get_feature_plugin_handle(bm_plugin_info_h **handle, bm_plugin_id_e id)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("invalid handle");
+               return;
+       }
+
+       if (id > BM_PLUGIN_ID_MAX) {
+               *handle = NULL;
+               _ERR("invalid plugin id");
+               goto END;
+       }
+
+       if (plugins[id] == NULL) {
+               _ERR("[%s] plugin not loaded", bm_get_plugin_name(id));
+               *handle = plugins[id];
+               goto END;
+       }
+
+       *handle = plugins[id];
+       _INFO("[%s] handle available - success", bm_get_plugin_name(id));
+END:
+       EXIT;
+       return;
+}
+
+static int bm_init_loaded_plugins()
+{
+       ENTER;
+
+       int ret_val = BM_PLUGIN_ERROR_NONE;
+       int id;
+       bm_plugin_info_h *bm_plugin = NULL;
+       const bm_callbacks_st *bm_cb = NULL;
+
+       _INFO("populate callbacks");
+
+       bm_populate_callbacks();
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       for (id = BM_PLUGIN_ID_BLE; id < BM_PLUGIN_ID_MAX; ++id) {
+#else
+       for (id = BM_PLUGIN_ID_BLE; id <= BM_PLUGIN_ID_DEVICE_NETWORK; ++id) {
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+               bm_plugin = plugins[id];
+               bm_cb = bm_receiver_callbacks[id];
+
+               if (!bm_plugin || !bm_plugin->api) {
+                       _WARN("Plugin with ID: %s is NULL", bm_get_plugin_name(id));
+                       continue;
+               }
+
+               /* init plugin one-by-one */
+               _INFO("init plugin - %s", bm_get_plugin_name(id));
+
+               ret_val = bm_plugin->api->init(bm_cb);
+
+               if (BM_PLUGIN_ERROR_NONE != ret_val) {
+                       _ERR("error in initializing plugin, error - %d", ret_val);
+                       continue;
+               }
+       }
+
+       if (ret_val == BM_PLUGIN_ERROR_NONE)
+               ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       EXIT;
+       return ret_val;
+}
+
+static int bm_add_plugin(void *handle, bm_plugin_st *plugin)
+{
+       ENTER;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _INFO("Plugin Info - name[%s], id[%d], version[%s]",
+                       plugin->name, plugin->id, plugin->version);
+
+       if (BATTERY_MONITOR_PLUGINS_MAX < plugin->id) {
+               _ERR("Unknown plugin id[%d] for [%s]", plugin->id, plugin->name);
+               return BATTERY_MONITOR_ERROR_PLUGIN_ADD;
+       }
+
+       if (plugins[plugin->id] != NULL) {
+               _WARN("plugin already added");
+               return BATTERY_MONITOR_ERROR_NONE;
+       }
+
+       if (g_str_equal(plugin->version, BATTERY_MONITOR_VERSION) == FALSE) {
+               _ERR("Version (%s) mismatch for %s",
+                               plugin->version, plugin->name);
+               return BATTERY_MONITOR_ERROR_PLUGIN_ADD;
+       }
+
+       bm_plugin_info_h *bm_plugin = g_try_new0(bm_plugin_info_h, 1);
+       if (NULL == bm_plugin) {
+               _ERR("Memory allocation failed");
+               return BATTERY_MONITOR_ERROR_PLUGIN_ADD;
+       }
+
+       if (NULL == plugin->init) {
+               _ERR("plugin init call failed");
+               return BATTERY_MONITOR_ERROR_PLUGIN_ADD;
+       }
+
+       bm_api_st *api = NULL;
+       plugin->init(&api);
+       if (NULL == api) {
+               _ERR("init failed, api is NULL");
+               return BATTERY_MONITOR_ERROR_PLUGIN_ADD;
+       }
+
+       bm_plugin->handle = handle;
+       bm_plugin->plugin = plugin;
+       bm_plugin->api = api;
+
+       plugins[plugin->id] = bm_plugin;
+
+       _INFO("SUCCESS - [%s] plugin addition", plugin->name);
+
+       EXIT;
+       return ret_val;
+}
+
+static int bm_load_plugin(const char *dir, const char *name, const char *symbol)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(dir);
+       BM_CHECK_INPUT_PARAM(name);
+       BM_CHECK_INPUT_PARAM(symbol);
+
+       _INFO("loading plugin - dir[%s], name[%s], symbol[%s]",
+                                               dir, name, symbol);
+
+       char *filename = g_build_filename(dir, name, NULL);
+       _DBG("Loading [%s]", filename);
+
+       void *handle = dlopen(filename, RTLD_NOW);
+       BM_GFREE(filename);
+       if (handle == NULL) {
+               _ERR("error loading plugin - %s", dlerror());
+               return BATTERY_MONITOR_ERROR_NULL_POINTER;
+       }
+
+       bm_plugin_st *plugin = (bm_plugin_st *)dlsym(handle, symbol);
+       if (plugin == NULL) {
+               _ERR("error loading plugin - %s", dlerror());
+               dlclose(handle);
+               return BATTERY_MONITOR_ERROR_NULL_POINTER;
+       }
+
+       if (BATTERY_MONITOR_ERROR_NONE != bm_add_plugin(handle, plugin)) {
+               _ERR("error adding plugin");
+               return BATTERY_MONITOR_ERROR_PLUGIN_ADD;
+       }
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+static int bm_load_feature_plugins()
+{
+       ENTER;
+
+       _INFO("plugin directory [%s]", BATTERY_MONITOR_PLUGIN_DIR);
+
+       const char *filename;
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       BM_RETURN_VAL((0 != strlen(BATTERY_MONITOR_PLUGIN_DIR)), {},
+               BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "improper plugin directory path");
+
+       GDir *dir = g_dir_open(BATTERY_MONITOR_PLUGIN_DIR, 0, NULL);
+
+       BM_RETURN_VAL((dir != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER,
+                                       "Unable to open plugin directory");
+
+       while ((filename = g_dir_read_name(dir)) != NULL) {
+
+               if ((g_file_test(filename, G_FILE_TEST_IS_SYMLINK) == TRUE) ||
+                       (g_str_has_suffix(filename, ".so") == FALSE))
+                       continue;
+
+               _DBG("plugin lib - [%s]", filename);
+
+               if (BATTERY_MONITOR_ERROR_NONE == bm_load_plugin(BATTERY_MONITOR_PLUGIN_DIR,
+                                                               filename,
+                                                               BATTERY_MONITOR_PLUGIN_SYMBOL))
+                       ret_val = BATTERY_MONITOR_ERROR_NONE;
+       }
+
+       g_dir_close(dir);
+
+       EXIT;
+       return ret_val;
+}
+
+int initialize_plugin_manager(void)
+{
+       ENTER;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       _INFO("load plugins");
+
+       ret_val = bm_load_feature_plugins();
+       BM_RETURN_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), {},
+                               ret_val, ("feature-plugin load error"));
+
+       _INFO("initialize loaded plugins");
+
+       ret_val = bm_init_loaded_plugins();
+       BM_RETURN_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), {},
+                               ret_val, ("feature-plugin init error"));
+
+       EXIT;
+       return ret_val;
+}
+
+void deinitialize_plugin_manager(void)
+{
+       ENTER;
+
+       _INFO("deinit loaded plugins");
+
+       int id;
+       bm_plugin_info_h *bm_plugin = NULL;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       for (id = BM_PLUGIN_ID_BLE; id < BM_PLUGIN_ID_MAX; ++id) {
+#else
+       for (id = BM_PLUGIN_ID_BLE; id <= BM_PLUGIN_ID_DEVICE_NETWORK; ++id) {
+#endif
+
+               bm_plugin = plugins[id];
+
+               if (!bm_plugin)
+                       continue;
+
+               if (bm_plugin->api && bm_plugin->api->deinit)
+                       bm_plugin->api->deinit();
+
+               if (bm_plugin->plugin && bm_plugin->plugin->deinit)
+                       bm_plugin->plugin->deinit();
+
+               if (bm_plugin->handle)
+                       dlclose(bm_plugin->handle);
+
+               BM_GFREE(bm_plugin);
+               bm_plugin = NULL;
+       }
+
+       EXIT;
+       return;
+}
diff --git a/src/bm_power_engine.c b/src/bm_power_engine.c
new file mode 100644 (file)
index 0000000..1bbde09
--- /dev/null
@@ -0,0 +1,1926 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <device/battery.h>
+#include <device/callback.h>
+
+#include "bm_power_engine.h"
+#include "bm_dbg.h"
+#include "bm_common.h"
+#include "bm_config_parser.h"
+#include "bm_plugin_manager.h"
+#include "bm_server_db.h"
+#include "bm_private.h"
+#include "bm_util.h"
+
+bm_feature_data_h bm_data_handle = NULL;
+GHashTable *gl_hash = NULL;
+
+int bm_engine_get_usage_by_app_id_for_resource_id(const gchar *app_id, gint resource_id, gint duration, int *b_usage)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(app_id);
+
+       BM_RETURN_VAL((resource_id < BM_PLUGIN_ID_MAX), {},
+                       BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "invalid resource-id param");
+
+       BM_RETURN_VAL((duration < BM_DURATION_TYPE_MAX), {},
+                       BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "invalid duration param");
+
+       _INFO("usage requested - app-id[%s], resource_id[%d], duration[%d]",
+                               app_id, resource_id, duration);
+
+       int error = BATTERY_MONITOR_ERROR_NONE;
+
+       appid_usage_s *app_usage = bm_server_query_app_usage_by_appid(app_id, duration, &error);
+
+       if (!app_usage) {
+               _ERR("battery usage data for app_id(%s) is not available", app_id);
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       if (error != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("error reported, error = %d", error);
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       if (resource_id == BM_PLUGIN_ID_BLE)
+               *b_usage = app_usage->rId_ble;
+       else if (resource_id == BM_PLUGIN_ID_WIFI)
+               *b_usage = app_usage->rId_wifi;
+       else if (resource_id == BM_PLUGIN_ID_CPU)
+               *b_usage = app_usage->rId_cpu;
+       else if (resource_id == BM_PLUGIN_ID_DISPLAY)
+               *b_usage = app_usage->rId_display;
+       else if (resource_id == BM_PLUGIN_ID_DEVICE_NETWORK)
+               *b_usage = app_usage->rId_device_network;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       else if (resource_id == BM_PLUGIN_ID_GPS_SENSOR)
+               *b_usage = app_usage->rId_gps;
+       else if (resource_id == BM_PLUGIN_ID_HRM_SENSOR)
+               *b_usage = app_usage->rId_hrm;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+       else if (resource_id == BM_PLUGIN_CONST_BATTERY)
+               *b_usage = app_usage->rId_battery;
+
+       bm_appid_usage_free(app_usage);
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int bm_engine_get_total_usage_by_app_id(const gchar *app_id, gint duration, int *b_usage)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(app_id);
+
+       BM_RETURN_VAL((duration < BM_DURATION_TYPE_MAX), {},
+                       BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "invalid duration param");
+
+       _INFO("usage requested - app-id[%s], duration[%d]", app_id, duration);
+
+       int error = BATTERY_MONITOR_ERROR_NONE;
+
+       appid_usage_s *app_usage = bm_server_query_app_usage_by_appid(app_id, duration, &error);
+
+       if (!app_usage) {
+               _ERR("battery usage data for app_id(%s) is not available", app_id);
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       if (error != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("error reported, error = %d", error);
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       int total_consumption = (app_usage->rId_ble + app_usage->rId_wifi + app_usage->rId_cpu + \
+                               app_usage->rId_display + app_usage->rId_device_network);
+
+       int ble_usage = 0, wifi_usage = 0, cpu_usage = 0, display_usage = 0, device_network_usage = 0;
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       total_consumption += (app_usage->rId_gps + app_usage->rId_hrm);
+       int gps_usage = 0, hrm_usage = 0;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+       ble_usage = bm_calc_individual_consumption(app_usage->rId_ble, total_consumption);
+
+       wifi_usage = bm_calc_individual_consumption(app_usage->rId_wifi, total_consumption);
+
+       cpu_usage = bm_calc_individual_consumption(app_usage->rId_cpu, total_consumption);
+
+       display_usage = bm_calc_individual_consumption(app_usage->rId_display, total_consumption);
+
+       device_network_usage = bm_calc_individual_consumption(app_usage->rId_device_network, total_consumption);
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       gps_usage = bm_calc_individual_consumption(app_usage->rId_gps, total_consumption);
+
+       hrm_usage = bm_calc_individual_consumption(app_usage->rId_hrm, total_consumption);
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       _DBG("individual usage - ble[%d], wifi[%d], cpu[%d], dsp[%d], device-network[%d], gps[%d], hrm[%d]", \
+               ble_usage, wifi_usage, cpu_usage, display_usage, device_network_usage, gps_usage, hrm_usage);
+
+       *b_usage = (ble_usage + wifi_usage + cpu_usage + display_usage + device_network_usage \
+                               + gps_usage + hrm_usage);
+#else /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+       _DBG("individual usage - ble[%d], wifi[%d], cpu[%d], dsp[%d], device-network[%d]", \
+               ble_usage, wifi_usage, cpu_usage, display_usage, device_network_usage);
+
+       *b_usage = (ble_usage + wifi_usage + cpu_usage + display_usage + device_network_usage);
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+       _INFO("total battery consumption is [%d] for app-id[%s]", *b_usage, app_id);
+
+       bm_appid_usage_free(app_usage);
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int bm_engine_get_total_usage_by_resource_id(gint resource_id, gint duration, int *b_usage)
+{
+       ENTER;
+
+       BM_RETURN_VAL((resource_id < BM_PLUGIN_ID_MAX), {},
+                       BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "invalid resource-id");
+
+       BM_RETURN_VAL((duration < BM_DURATION_TYPE_MAX), {},
+                       BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "invalid duration param");
+
+       _INFO("usage requested - resource_id[%d], duration[%d]", resource_id, duration);
+
+       int error = BATTERY_MONITOR_ERROR_NONE;
+
+       const char *resource_id_str = NULL;
+       resource_id_str = bm_get_resource_id_string(resource_id);
+       if (g_strcmp0(resource_id_str, "UNKNOWN RESOURCE-ID") == 0) {
+               _ERR("invalid resource-id");
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       _INFO("resource string - [%s]", resource_id_str);
+
+       resourceid_usage_s *resource_usage = bm_server_query_resource_usage_resourceid(resource_id_str, duration, &error);
+
+       if (!resource_usage) {
+               _ERR("battery usage data for resource-id(%s) is not available", resource_id_str);
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       if (error != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("error reported, error = %d", error);
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       *b_usage = resource_usage->usage;
+
+       bm_resourceid_usage_free(resource_usage);
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int bm_engine_get_all_resource_usage(const gchar *app_id, gint duration, bm_total_consumption_h data)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(app_id);
+
+       BM_CHECK_INPUT_PARAM(data);
+
+       BM_RETURN_VAL((duration < BM_DURATION_TYPE_MAX), {},
+                       BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "invalid duration param");
+
+       _INFO("usage requested - app-id[%s], duration[%d]", app_id, duration);
+
+       int error = BATTERY_MONITOR_ERROR_NONE;
+
+       appid_usage_s *app_usage = bm_server_query_app_usage_by_appid(app_id, duration, &error);
+
+       if (!app_usage) {
+               _ERR("battery usage data for app_id(%s) is not available", app_id);
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       if (error != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("error reported, error = %d", error);
+               return BATTERY_MONITOR_ERROR_INTERNAL;
+       }
+
+       data->ble_val = app_usage->rId_ble;
+       data->wifi_val = app_usage->rId_wifi;
+       data->cpu_val = app_usage->rId_cpu;
+       data->dp_val = app_usage->rId_display;
+       data->dn_val = app_usage->rId_device_network;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       data->gps_val = app_usage->rId_gps;
+       data->hrm_val = app_usage->rId_hrm;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+       data->bat_val = app_usage->rId_battery;
+
+       bm_appid_usage_free(app_usage);
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+void bm_set_req_flag_handles(bool value)
+{
+       ENTER;
+
+       if (!bm_req_flag_h) {
+               _ERR("invalid flag handle");
+               return;
+       }
+
+       bm_req_flag_h->req_ble_data = value;
+       bm_req_flag_h->req_wifi_data = value;
+       bm_req_flag_h->req_cpu_data = value;
+       bm_req_flag_h->req_dp_data = value;
+       bm_req_flag_h->req_dn_data = value;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       bm_req_flag_h->req_gps_data = value;
+       bm_req_flag_h->req_hrm_data = value;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+       _INFO("request flags set-[%s]", (value == true) ? "TRUE" : "FALSE");
+
+       EXIT;
+       return;
+}
+
+static int bm_appid_session_usage_map(char *app_id, int app_usage, bm_plugin_id_e resource_id)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(app_id);
+
+       void *prv_data = NULL;
+       void *prv_app_id = NULL;
+
+       appid_usage_s *temp = NULL;
+       temp = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (temp == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+       _DBG("app_id [%s] app_usage is [%d]", app_id, app_usage);
+
+       if (g_hash_table_lookup_extended(gl_hash, app_id, &prv_app_id, &prv_data) == true) {
+               temp = (appid_usage_s *)prv_data;
+               if (resource_id == BM_PLUGIN_ID_BLE)
+                       temp->rId_ble += app_usage;
+               else if (resource_id == BM_PLUGIN_ID_WIFI)
+                       temp->rId_wifi += app_usage;
+               else if (resource_id == BM_PLUGIN_ID_CPU)
+                       temp->rId_cpu += app_usage;
+               else if (resource_id == BM_PLUGIN_ID_DISPLAY)
+                       temp->rId_display += app_usage;
+               else if (resource_id == BM_PLUGIN_ID_DEVICE_NETWORK)
+                       temp->rId_device_network += app_usage;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+               else if (resource_id == BM_PLUGIN_ID_GPS_SENSOR)
+                       temp->rId_gps += app_usage;
+               else if (resource_id == BM_PLUGIN_ID_HRM_SENSOR)
+                       temp->rId_hrm += app_usage;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+               _DBG("update - app_usage for app_id(%s), for resource(%d), by usage(%d)", app_id, resource_id, app_usage);
+               _INFO("updated - %d", g_hash_table_replace(gl_hash, app_id, temp));
+       } else {
+               if (resource_id == BM_PLUGIN_ID_BLE)
+                       temp->rId_ble = app_usage;
+               else if (resource_id == BM_PLUGIN_ID_WIFI)
+                       temp->rId_wifi = app_usage;
+               else if (resource_id == BM_PLUGIN_ID_CPU)
+                       temp->rId_cpu = app_usage;
+               else if (resource_id == BM_PLUGIN_ID_DISPLAY)
+               temp->rId_display = app_usage;
+               else if (resource_id == BM_PLUGIN_ID_DEVICE_NETWORK)
+                       temp->rId_device_network = app_usage;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+               else if (resource_id == BM_PLUGIN_ID_GPS_SENSOR)
+                       temp->rId_gps = app_usage;
+               else if (resource_id == BM_PLUGIN_ID_HRM_SENSOR)
+                       temp->rId_hrm = app_usage;
+#endif
+               _DBG("insert - app_usage app_id(%s), for resource(%d), by usage(%d)", app_id, resource_id, app_usage);
+               _INFO("inserted - %d", g_hash_table_insert(gl_hash, app_id, temp));
+       }
+
+       EXIT;
+       return ret_val;
+}
+
+static int bm_insert_appid_session_usage_to_db()
+{
+       ENTER;
+
+       GHashTableIter iter;
+       gpointer key, value;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       appid_usage_s *app_usage = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (app_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       long int ret_time = bm_get_log_time();
+
+       g_hash_table_iter_init(&iter, gl_hash);
+
+       while (g_hash_table_iter_next(&iter, &key, &value)) {
+               app_usage = (appid_usage_s *)value;
+               app_usage->AppId = (char *)key;
+               app_usage->log_time = ret_time;
+
+               _DBG("Calculated Power for Appid(%s) for resources bt(%d), wifi(%d), cpu(%d), \
+                       display(%d), dn(%d)", app_usage->AppId, app_usage->rId_ble,
+                       app_usage->rId_wifi, app_usage->rId_cpu, app_usage->rId_display,
+                                       app_usage->rId_device_network);
+
+               ret_val = bm_server_app_usage_insert_to_db(app_usage);
+               if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+                       _ERR("Insert of App Usage failed ");
+               else
+                       _DBG("Insert successful");
+       }
+
+       EXIT;
+       return ret_val;
+}
+
+/* TODO: Add Normalization of values based on sP_Power_xxx & Time unit */
+int bm_ble_calc_power_and_commit(bm_bluetooth_st *handle, bool mode)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       GSList *bt_data_iterator = NULL;
+       GSList *bt_atm_iterator = NULL;
+
+       void *prv_data = NULL;
+       void *prv_app_id = NULL;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       /* creating hash-map with (key, value) = (app-id, data) */
+       GHashTable *hash = g_hash_table_new_full(g_str_hash, g_str_equal, bm_data_free, bm_atm_st2_free);
+
+       long int edTime = 0, stTime = 0;
+       int sesTime = 0, scTime = 0, conTime = 0, RX = 0, TX = 0, onTime = 0;
+
+       /* iterating over list for data accumulation */
+       for (bt_data_iterator = handle->bt_data_list; bt_data_iterator; bt_data_iterator = bt_data_iterator->next) {
+
+               bm_bluetooth_st *datalistnode = (bm_bluetooth_st *)(bt_data_iterator->data);
+
+               edTime = datalistnode->stopTime;
+               stTime = datalistnode->startTime;
+               scTime += datalistnode->scanTime;
+               conTime += datalistnode->connectedTime;
+               sesTime += (edTime-stTime);
+
+               //bt_atm_iterator = ((bm_bluetooth_st *)(bt_data_iterator->data))->atm_list;
+               bt_atm_iterator = datalistnode->atm_list;
+
+               for ( ; bt_atm_iterator; bt_atm_iterator = bt_atm_iterator->next) {
+
+                       app_time_map_st2 *bt_atm_node = NULL;
+                       bt_atm_node = bt_atm_iterator->data;
+
+                       if (!bt_atm_node) {
+                               _DBG("no data available");
+                               continue;
+                       }
+
+                       _DBG("bt data available");
+
+                       RX += bt_atm_node->rx;
+                       TX += bt_atm_node->tx;
+                       onTime += bt_atm_node->time;
+
+                       prv_data = NULL;
+                       prv_app_id = NULL;
+
+                       if (g_hash_table_lookup_extended(hash, bt_atm_node->app_id, &prv_app_id, &prv_data) == true) {
+
+                               _DBG("previous app_id = %s", (char *)prv_app_id);
+
+                               app_time_map_st2 *temp = (app_time_map_st2 *)prv_data;
+
+                               bt_atm_node->time += temp->time;
+                               bt_atm_node->rx += temp->rx;
+                               bt_atm_node->tx += temp->tx;
+
+                               _DBG("update - app_id(%s), time(%d), rx(%d), tx(%d)", bt_atm_node->app_id,
+                                               bt_atm_node->time, bt_atm_node->rx, bt_atm_node->tx);
+
+                               _INFO("updated - %d", g_hash_table_replace(hash, bt_atm_node->app_id, bt_atm_node));
+
+                       } else {
+
+                               _DBG("insert - app_id(%s), time(%d), rx(%d), tx(%d)", bt_atm_node->app_id,
+                                               bt_atm_node->time, bt_atm_node->rx, bt_atm_node->tx);
+
+                               _INFO("inserted - %d", g_hash_table_insert(hash, bt_atm_node->app_id, bt_atm_node));
+                       }
+               }
+       }
+
+       /* Read standard Rated Values from Device Spec File/Power Profile File */
+       int sP_power_bt_idle = 0, sP_power_bt_scan = 0, sP_power_bt_conn = 0, sP_power_bt_tx = 0, sP_power_bt_rx = 0;
+
+       ret_val = bm_get_blutooth_power_params(&sP_power_bt_idle, &sP_power_bt_scan, &sP_power_bt_conn, &sP_power_bt_tx, &sP_power_bt_rx);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("failed to get bt power params");
+
+       _DBG("received bt power params - idle[%d], scan[%d], connected[%d], rx[%d], tx[%d]",
+                       sP_power_bt_idle, sP_power_bt_scan, sP_power_bt_conn, sP_power_bt_tx, sP_power_bt_rx);
+
+       /* BT power consumption Level - 1 at the Resource Level */
+       int P_power_bt = 0, P_power_data = 0, P_power_conn = 0;
+
+       P_power_conn = ((sP_power_bt_idle) * (sesTime - (scTime + conTime))) + ((sP_power_bt_scan) * (scTime)) + ((sP_power_bt_conn) * (conTime));
+
+       P_power_data = ((sP_power_bt_tx) * TX) + ((sP_power_bt_rx) * RX);
+
+       P_power_bt = P_power_conn + P_power_data;
+
+       _DBG("Calculated Power for Bluetooth P_power_bt(%d),  P_power_conn (%d), P_power_data(%d)", P_power_bt, P_power_conn, P_power_data);
+
+       /* BT power consumption Level - 2 at the Application Level */
+       GHashTableIter iter;
+       gpointer key, value;
+
+       g_hash_table_iter_init(&iter, hash);
+
+       int P_power_app_bt = 0, P_power_app_data = 0, P_power_app_conn = 0;
+       char *appid = NULL;
+       int apprx = 0, apptx = 0, apptime = 0;
+
+       long int ret_time = bm_get_log_time();
+
+       appid_usage_s *app_usage = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (app_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       while (g_hash_table_iter_next(&iter, &key, &value)) {
+
+               P_power_app_bt = 0; P_power_app_data = 0 ; P_power_app_conn = 0;
+               apprx = 0, apptx = 0, apptime = 0;
+
+               app_time_map_st2 *temp = (app_time_map_st2 *)value;
+
+               appid = temp->app_id;
+               apprx = temp->rx;
+               apptx = temp->tx;
+               apptime = temp->time;
+
+               P_power_app_data = ((sP_power_bt_tx) * apptx) + ((sP_power_bt_rx) * apprx);
+
+               if (onTime != 0)
+                       P_power_app_conn = P_power_conn * (apptime/onTime); //check for 0 denominator & same units
+
+               P_power_app_bt = P_power_app_data + P_power_app_conn;
+
+               app_usage->AppId = appid;
+               app_usage->rId_ble = P_power_app_bt;
+               app_usage->log_time = ret_time;
+
+               /* Call Insert Function */
+               _DBG("Calculated Power for Appid(%s) -  P_power_app_bt(%d), P_power_app_conn(%d), P_power_app_data(%d)",
+                                       appid, P_power_app_bt, P_power_app_conn, P_power_app_data);
+
+               if (mode)
+                       ret_val = bm_server_app_usage_insert_to_db(app_usage);
+               else/* Call Global Hash */
+                       ret_val = bm_appid_session_usage_map(g_strdup(app_usage->AppId), app_usage->rId_ble, BM_PLUGIN_ID_BLE);
+
+               /* Error Check */
+               if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+                       _ERR("Insert of BT App failed ");
+               else
+                       _DBG("Insert successful");
+       }
+
+       /* commit to database the output after power calculation */
+       resourceid_usage_s *res_usage = (resourceid_usage_s *)calloc(1, sizeof(resourceid_usage_s));
+       if (res_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       res_usage->ResourceId = BM_RID_BLE;
+       res_usage->log_time = ret_time;
+       res_usage->usage = P_power_bt;
+
+       ret_val = bm_server_resource_usage_insert_to_db(res_usage);
+       /* Error Check */
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("Insert of BT resource failed ");
+       else
+               _DBG("Insert successful");
+
+       bm_appid_usage_free(app_usage);
+       bm_resourceid_usage_free(res_usage);
+
+       /* Free the hash map */
+       g_hash_table_destroy(hash);
+
+       EXIT;
+       return ret_val;
+}
+
+int bm_wifi_calc_power_and_commit(bm_wifi_st *handle, bool mode)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       GSList *wifi_data_iterator = NULL;
+       GSList *wifi_atm_iterator = NULL;
+
+       void *prv_data = NULL;
+       void *prv_app_id = NULL;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       /* creating hash-map with (key, value) = (app-id, data) */
+       GHashTable *hash = g_hash_table_new_full(g_str_hash, g_str_equal, bm_data_free, bm_atm_st2_free);
+
+       long int edTime = 0;
+       long int stTime = 0;
+       int sesTime = 0;
+       int scTime = 0;
+       int tl0 = 0, tl1 = 0, tl2 = 0, tl3 = 0, tl4 = 0;
+       int RX = 0, TX = 0;
+       int onTime = 0;
+
+       /* iterating over list for data accumulation */
+       for (wifi_data_iterator = handle->wifi_data_list; wifi_data_iterator; wifi_data_iterator = wifi_data_iterator->next) {
+
+               bm_wifi_st *datalistnode = (bm_wifi_st *)(wifi_data_iterator->data);
+
+               edTime = datalistnode->endTime;
+               stTime = datalistnode->startTime;
+               sesTime += edTime - stTime;
+               scTime += datalistnode->scanTime;
+               tl0 += datalistnode->time_level_0;
+               tl1 += datalistnode->time_level_1;
+               tl2 += datalistnode->time_level_2;
+               tl3 += datalistnode->time_level_3;
+               tl4 += datalistnode->time_level_4;
+
+               wifi_atm_iterator = datalistnode->atm_list;
+//             wifi_atm_iterator = ((bm_wifi_st *)(wifi_data_iterator->data))->atm_list;
+
+               for ( ; wifi_atm_iterator; wifi_atm_iterator = wifi_atm_iterator->next) {
+
+                       app_time_map_st2 *wifi_atm_node = NULL;
+                       wifi_atm_node = wifi_atm_iterator->data;
+
+                       if (!wifi_atm_node) {
+                               _DBG("no data available");
+                               continue;
+                       }
+
+                       _DBG("wifi data available");
+
+                       RX += wifi_atm_node->rx;
+                       TX += wifi_atm_node->tx;
+                       onTime += wifi_atm_node->time;
+
+                       prv_app_id = NULL;
+                       prv_data = NULL;
+
+                       if (g_hash_table_lookup_extended(hash, wifi_atm_node->app_id, &prv_app_id, &prv_data) == true) {
+
+                               _DBG("previous app_id = %s", (char *)prv_app_id);
+
+                               app_time_map_st2 *temp = (app_time_map_st2 *)prv_data;
+
+                               wifi_atm_node->time += temp->time;
+                               wifi_atm_node->rx += temp->rx;
+                               wifi_atm_node->tx += temp->tx;
+
+                               _DBG("update - app_id(%s), time(%d), rx(%d), tx(%d)", wifi_atm_node->app_id,
+                                               wifi_atm_node->time, wifi_atm_node->rx, wifi_atm_node->tx);
+
+                               _INFO("updated - %d", g_hash_table_replace(hash, wifi_atm_node->app_id, wifi_atm_node));
+
+                       } else {
+
+                               _DBG("insert - app_id(%s), time(%d), rx(%d), tx(%d)", wifi_atm_node->app_id,
+                                               wifi_atm_node->time, wifi_atm_node->rx, wifi_atm_node->tx);
+
+                               _INFO("inserted - %d", g_hash_table_insert(hash, wifi_atm_node->app_id, wifi_atm_node));
+                       }
+               }
+       }
+
+       /* Read standard Rated Values from Device Spec File/Power Profile File */
+       int sP_power_wf_idle = 0, sP_power_wf_scan = 0, sP_power_wf_tl0 = 0, sP_power_wf_tl1 = 0, sP_power_wf_tl2 = 0;
+       int sP_power_wf_tl3 = 0, sP_power_wf_tl4 = 0, sP_power_wf_tx = 0, sP_power_wf_rx = 0;
+
+       ret_val = bm_get_wifi_power_params(&sP_power_wf_tl0, &sP_power_wf_tl1, &sP_power_wf_tl2, &sP_power_wf_tl3,
+                               &sP_power_wf_tl4, &sP_power_wf_scan, &sP_power_wf_idle, &sP_power_wf_rx, &sP_power_wf_tx);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("failed to get wifi power params");
+
+       _DBG("received wifi power params - rssi_0[%d], rssi_1[%d], rssi_2[%d], rssi_3[%d], rssi_4[%d], scan[%d], \
+                       idle[%d], rx[%d], tx[%d]", sP_power_wf_tl0, sP_power_wf_tl1, sP_power_wf_tl2, sP_power_wf_tl3,
+                       sP_power_wf_tl4, sP_power_wf_scan, sP_power_wf_idle, sP_power_wf_rx, sP_power_wf_tx);
+
+       int tl_total = 0;
+
+       tl_total = tl0 + tl1 + tl2 + tl3 + tl4;
+
+       /* Wifi power consumption Level - 1 at the Resource Level */
+       int P_power_wifi = 0; int P_power_data = 0; int P_power_conn = 0;
+
+       P_power_conn = ((sP_power_wf_tl0 * tl0) + (sP_power_wf_tl1 * tl1) +
+                       (sP_power_wf_tl2 * tl2) + (sP_power_wf_tl3 * tl3) +
+                       (sP_power_wf_tl4 * tl4) + (sP_power_wf_scan * scTime) +
+                       (sP_power_wf_idle * tl_total));
+
+       P_power_data = ((sP_power_wf_tx) * TX) + ((sP_power_wf_rx) * RX);
+
+       P_power_wifi = P_power_conn + P_power_data;
+
+       _DBG("Calculated Power for Wifi P_power_wifi(%d),  P_power_conn (%d), P_power_data(%d)", P_power_wifi, P_power_conn, P_power_data);
+
+       /* Wifi power consumption Level - 2 at the Application Level */
+       GHashTableIter iter;
+       gpointer key, value;
+
+       g_hash_table_iter_init(&iter, hash);
+
+       int P_power_app_wifi = 0, P_power_app_data = 0, P_power_app_conn = 0;
+       char *appid = NULL;
+       int apprx = 0, apptx = 0, apptime = 0;
+
+       long int ret_time = bm_get_log_time();
+
+       appid_usage_s *app_usage = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (app_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       while (g_hash_table_iter_next(&iter, &key, &value)) {
+               P_power_app_wifi = 0; P_power_app_data = 0 ; P_power_app_conn = 0;
+               apprx = 0, apptx = 0, apptime = 0;
+
+               app_time_map_st2 *temp = (app_time_map_st2 *)value;
+
+               appid = temp->app_id;
+               apprx = temp->rx;
+               apptx = temp->tx;
+               apptime = temp->time;
+
+               P_power_app_data = ((sP_power_wf_tx) * apptx) + ((sP_power_wf_rx) * apprx);
+
+               if (onTime != 0)
+                       P_power_app_conn = P_power_conn * (apptime/onTime); //check for 0 denominator & same units
+               P_power_app_wifi = P_power_app_data + P_power_app_conn;
+
+               app_usage->AppId = appid;
+               app_usage->rId_wifi = P_power_app_wifi;
+               app_usage->log_time = ret_time;
+
+               /* Call Insert Function */
+               _DBG("Calculated Power for Appid(%s) -  P_power_app_wifi(%d), P_power_app_conn(%d), P_power_app_data(%d)",
+                                       appid, P_power_app_wifi, P_power_app_conn, P_power_app_data);
+
+               if (mode)
+                       ret_val = bm_server_app_usage_insert_to_db(app_usage);
+               else/* Call Global Hash */
+                       ret_val = bm_appid_session_usage_map(g_strdup(app_usage->AppId), app_usage->rId_wifi, BM_PLUGIN_ID_WIFI);
+
+               /* Error Check */
+               if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+                       _ERR("Insert of Wifi App failed ");
+               else
+                       _DBG("Insert successful");
+       }
+
+       /* commit to database the output after power calculation */
+       resourceid_usage_s *res_usage = (resourceid_usage_s *)calloc(1, sizeof(resourceid_usage_s));
+       if (res_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       res_usage->ResourceId = BM_RID_WIFI;
+       res_usage->log_time = ret_time;
+       res_usage->usage = P_power_wifi;
+
+       ret_val = bm_server_resource_usage_insert_to_db(res_usage);
+       /* Error Check */
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("Insert of Wifi resource failed ");
+       else
+               _DBG("Insert successful");
+
+       bm_appid_usage_free(app_usage);
+       bm_resourceid_usage_free(res_usage);
+
+       /* Free the Hash Map */
+       g_hash_table_destroy(hash);
+
+       EXIT;
+       return ret_val;
+}
+
+int bm_cpu_calc_power_and_commit(bm_cpu_st *handle, bool mode)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       GSList *cpu_data_iterator = NULL;
+       GSList *cpu_atm_iterator = NULL;
+
+       void *prv_data = NULL;
+       void *prv_app_id = NULL;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       /* creating hash-map with (key, value) = (app-id, data) */
+       GHashTable *hash = g_hash_table_new_full(g_str_hash, g_str_equal, bm_data_free, bm_atm_st1_free);
+
+       int fgTime = 0;
+       int bgTime = 0;
+       int onTime = 0;
+
+       /* iterating over list for data accumulation */
+       for (cpu_data_iterator = handle->cpu_data_list; cpu_data_iterator; cpu_data_iterator = cpu_data_iterator->next) {
+
+               bm_cpu_st *datalistnode = (bm_cpu_st *)(cpu_data_iterator->data);
+               fgTime += datalistnode->cpuTimeForeground;
+               bgTime += datalistnode->cpuTimeBackground;
+
+               cpu_atm_iterator = datalistnode->atm_list;
+//             cpu_atm_iterator = ((bm_cpu_st *)(cpu_data_iterator->data))->atm_list;
+
+               for ( ; cpu_atm_iterator; cpu_atm_iterator = cpu_atm_iterator->next) {
+                       app_time_map_st1 *cpu_atm_node = (app_time_map_st1 *)cpu_atm_iterator->data;
+                       if (!cpu_atm_node) {
+                               _DBG("no data available");
+                               continue;
+                       }
+
+                       _DBG("cpu data available");
+
+                       onTime += cpu_atm_node->time;
+
+                       prv_app_id = NULL;
+                       prv_data = NULL;
+
+                       if (g_hash_table_lookup_extended(hash, cpu_atm_node->app_id, &prv_app_id, &prv_data) == true) {
+
+                               _DBG("previous app_id = %s", (char *)prv_app_id);
+
+                               app_time_map_st1 *cpu_atm_prv_node = (app_time_map_st1 *)prv_data;
+
+                               cpu_atm_node->time += cpu_atm_prv_node->time;
+
+                               _DBG("update - app_id(%s), time(%d)", cpu_atm_node->app_id, cpu_atm_node->time);
+
+                               _INFO("updated - %d", g_hash_table_replace(hash, cpu_atm_node->app_id, cpu_atm_node));
+
+                       } else {
+
+                               _DBG("insert - app_id(%s), time(%d)", cpu_atm_node->app_id, cpu_atm_node->time);
+
+                               _INFO("inserted - %d", g_hash_table_insert(hash, cpu_atm_node->app_id, cpu_atm_node));
+                       }
+               }
+       }
+       /* Read standard Rated Values from Device Spec File/Power Profile File */
+       int sP_power_cpu_fg = 0, sP_power_cpu_bg = 0;
+
+       ret_val = bm_get_cpu_power_params(&sP_power_cpu_fg, &sP_power_cpu_bg);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("failed to get cpu power params");
+
+       _DBG("received cpu power params - fg[%d]\n, bg[%d]\n", sP_power_cpu_fg, sP_power_cpu_bg);
+       /* CPU power consumption Level - 1 at the Resource Level */
+       int P_power_cpu = 0, P_power_fg = 0, P_power_bg = 0;
+
+       P_power_fg = ((sP_power_cpu_fg * fgTime));
+       P_power_bg = ((sP_power_cpu_bg * bgTime));
+
+       P_power_cpu = P_power_bg + P_power_fg;
+
+       _DBG("Calculated Power for CPU P_power_cpu (%d),  P_power_bg (%d), P_power_fg (%d)", P_power_cpu, P_power_bg, P_power_fg);
+
+       /* CPU power consumption Level - 2 at the Application Level */
+       GHashTableIter iter;
+       gpointer key, value;
+
+       g_hash_table_iter_init(&iter, hash);
+
+       int P_power_app_cpu = 0, P_power_app_use = 0;
+       char *appid = NULL;
+       int apptime = 0;
+
+       long int ret_time = bm_get_log_time();
+
+       appid_usage_s *app_usage = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (app_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       while (g_hash_table_iter_next(&iter, &key, &value)) {
+               P_power_app_cpu = 0; P_power_app_use = 0;
+               apptime = 0;
+
+               app_time_map_st1 *temp = (app_time_map_st1 *)value;
+
+               appid = temp->app_id;
+               apptime = temp->time;
+
+               if (onTime != 0)
+                       P_power_app_use = P_power_cpu * (apptime/onTime); //check for 0 denominator & same units
+               P_power_app_cpu = P_power_app_use;
+
+               app_usage->AppId = appid;
+               app_usage->rId_cpu = P_power_app_cpu;
+               app_usage->log_time = ret_time;
+
+               /* Call Insert Function */
+               _DBG("Calculated Power for Appid (%s) P_power_app_cpu (%d),  P_power_app_use (%d)", appid, P_power_app_cpu, P_power_app_use);
+               if (mode)
+                       ret_val = bm_server_app_usage_insert_to_db(app_usage);
+               else
+                       ret_val = bm_appid_session_usage_map(g_strdup(app_usage->AppId), app_usage->rId_cpu, BM_PLUGIN_ID_CPU);
+               /* Error Check */
+               if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+                       _ERR("Insert of CPU App failed ");
+               else
+                       _DBG("Insert successful");
+       }
+
+       /* commit to database the output after power calculation */
+       resourceid_usage_s *res_usage = (resourceid_usage_s *)calloc(1, sizeof(resourceid_usage_s));
+       if (res_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       res_usage->ResourceId = BM_RID_CPU;
+       res_usage->log_time = ret_time;
+       res_usage->usage = P_power_cpu;
+
+       ret_val = bm_server_resource_usage_insert_to_db(res_usage);
+       /* Error Check */
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("Insert of CPU resource failed ");
+       else
+               _DBG("Insert successful");
+
+       bm_appid_usage_free(app_usage);
+       bm_resourceid_usage_free(res_usage);
+
+       /* Free the Hash Map */
+       g_hash_table_destroy(hash);
+
+       EXIT;
+       return ret_val;
+}
+
+int bm_display_calc_power_and_commit(bm_display_st *handle, bool mode)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       GSList *dp_data_iterator = NULL;
+       GSList *dp_atm_iterator = NULL;
+
+       void *prv_data = NULL;
+       void *prv_app_id = NULL;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       /* creating hash-map with (key, value) = (app-id, data) */
+       GHashTable *hash = g_hash_table_new_full(g_str_hash, g_str_equal, bm_data_free, bm_atm_st1_free);
+
+       long int edTime = 0;
+       long int stTime = 0;
+       int sesTime = 0;
+
+       int highTime = 0, medTime = 0, lowTime = 0;
+       int onTime = 0;
+
+       /* iterating over list for data accumulation */
+       for (dp_data_iterator = handle->display_list; dp_data_iterator; dp_data_iterator = dp_data_iterator->next) {
+
+               bm_display_st *datalistnode = (bm_display_st *)(dp_data_iterator->data);
+               edTime = datalistnode->stop;
+               stTime = datalistnode->start;
+               highTime += datalistnode->high;
+               medTime += datalistnode->med;
+               lowTime += datalistnode->low;
+               sesTime += edTime - stTime;
+
+               dp_atm_iterator = datalistnode->atm_list;
+//             dp_atm_iterator = ((bm_display_st *)(dp_data_iterator->data))->atm_list;
+
+               for ( ; dp_atm_iterator; dp_atm_iterator = dp_atm_iterator->next) {
+
+                       app_time_map_st1 *dp_atm_node = (app_time_map_st1 *)dp_atm_iterator->data;
+
+                       if (!dp_atm_node) {
+                               _DBG("no data available");
+                               continue;
+                       }
+
+                       _DBG("display data available");
+
+                       onTime += dp_atm_node->time;
+
+                       prv_data = NULL;
+                       prv_app_id = NULL;
+
+                       if (g_hash_table_lookup_extended(hash, dp_atm_node->app_id, &prv_app_id, &prv_data) == true) {
+
+                               _DBG("previous app_id = %s", (char *)prv_app_id);
+
+                               app_time_map_st1 *dp_atm_prv_node = (app_time_map_st1 *)prv_data;
+
+                               dp_atm_node->time += dp_atm_prv_node->time;
+
+                               _DBG("update - app_id(%s), time(%d)", dp_atm_node->app_id, dp_atm_node->time);
+
+                               _INFO("updated - %d", g_hash_table_replace(hash, dp_atm_node->app_id, dp_atm_node));
+
+                       } else {
+
+                               _DBG("insert - app_id(%s), time(%d)", dp_atm_node->app_id, dp_atm_node->time);
+
+                               _INFO("inserted - %d", g_hash_table_insert(hash, dp_atm_node->app_id, dp_atm_node));
+                       }
+               }
+       }
+
+       /* Read standard Rated Values from Device Spec File/Power Profile File */
+       int sP_power_dp_low = 0, sP_power_dp_med = 0, sP_power_dp_high = 0;
+
+       ret_val = bm_get_display_power_params(&sP_power_dp_high, &sP_power_dp_med, &sP_power_dp_low);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("failed to get cpu power params");
+
+       _DBG("received display power params - high[%d], medium[%d], low[%d]", sP_power_dp_high, sP_power_dp_med, sP_power_dp_low);
+
+       /* Display power consumption Level - 1 at the Resource Level */
+       int P_power_disp = 0, P_power_on = 0;
+       P_power_on = ((sP_power_dp_low * lowTime) + (sP_power_dp_med * medTime) * (sP_power_dp_high * highTime));
+
+       P_power_disp = P_power_on;
+       _DBG("Calculated Power for Display P_power_disp (%d),  P_power_on (%d)", P_power_disp, P_power_on);
+
+       /* Display power consumption Level - 2 at the Application Level */
+       GHashTableIter iter;
+       gpointer key, value;
+
+       g_hash_table_iter_init(&iter, hash);
+
+       int P_power_app_disp = 0, P_power_app_on = 0;
+       char *appid = NULL;
+       int apptime = 0;
+
+       long int ret_time = bm_get_log_time();
+
+       appid_usage_s *app_usage = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (app_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       while (g_hash_table_iter_next(&iter, &key, &value)) {
+               P_power_app_disp = 0; P_power_app_on = 0;
+               apptime = 0;
+
+               app_time_map_st1 *temp = (app_time_map_st1 *)value;
+
+               appid = temp->app_id;
+               apptime = temp->time;
+
+               if (onTime != 0)
+                       P_power_app_on = P_power_on * (apptime/onTime); //check for 0 denominator & same units
+
+               P_power_app_disp = P_power_app_on;
+
+               app_usage->AppId = appid;
+               app_usage->rId_display = P_power_app_disp;
+               app_usage->log_time = ret_time;
+
+               /* Call Insert Function */
+               _DBG("Calculated Power for Appid (%s) P_power_app_disp(%d),  P_power_app_on (%d)", appid, P_power_app_disp, P_power_app_on);
+               if (mode)
+                       ret_val = bm_server_app_usage_insert_to_db(app_usage);
+               else
+                       ret_val = bm_appid_session_usage_map(g_strdup(app_usage->AppId), app_usage->rId_display, BM_PLUGIN_ID_DISPLAY);
+               /* Error Check */
+               if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+                       _ERR("Insert of Display App failed ");
+               else
+                       _DBG("Insert successful");
+       }
+
+       /* commit to database the output after power calculation */
+       resourceid_usage_s *res_usage = (resourceid_usage_s *)calloc(1, sizeof(resourceid_usage_s));
+       if (res_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       res_usage->ResourceId = BM_RID_DISP;
+       res_usage->log_time = ret_time;
+       res_usage->usage = P_power_disp;
+
+       ret_val = bm_server_resource_usage_insert_to_db(res_usage);
+       /* Error Check */
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("Insert of Display resource failed ");
+       else
+               _DBG("Insert successful");
+
+
+       bm_appid_usage_free(app_usage);
+       bm_resourceid_usage_free(res_usage);
+
+       /* Free the Hash Map */
+       g_hash_table_destroy(hash);
+
+       EXIT;
+       return ret_val;
+}
+
+int bm_device_network_calc_power_and_commit(bm_device_network_st *handle, bool mode)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       GSList *dn_data_iterator = NULL;
+       GSList *dn_atm_iterator = NULL;
+
+       void *prv_data = NULL;
+       void *prv_app_id = NULL;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       /* creating hash-map with (key, value) = (app-id, data) */
+       GHashTable *hash = g_hash_table_new_full(g_str_hash, g_str_equal, bm_data_free, bm_atm_st2_free);
+
+       /* Session variables for Data accumulation */
+       int tl0 = 0, tl1 = 0, tl2 = 0, tl3 = 0, tl4 = 0, tl5 = 0, tl6 = 0;
+       int RX = 0, TX = 0;
+
+       /* iterating over list for data accumulation */
+       for (dn_data_iterator = handle->dn_data_list; dn_data_iterator; dn_data_iterator = dn_data_iterator->next) {
+
+               bm_device_network_st *datalistnode = (bm_device_network_st *)(dn_data_iterator->data);
+               tl0 += datalistnode->time_level_0;
+               tl1 += datalistnode->time_level_1;
+               tl2 += datalistnode->time_level_2;
+               tl3 += datalistnode->time_level_3;
+               tl4 += datalistnode->time_level_4;
+               tl5 += datalistnode->time_level_5;
+               tl6 += datalistnode->time_level_6;
+
+               dn_atm_iterator = datalistnode->atm_list;
+
+               for ( ; dn_atm_iterator; dn_atm_iterator = dn_atm_iterator->next) {
+
+                       app_time_map_st2 *dn_atm_node = (app_time_map_st2 *)dn_atm_iterator->data;
+
+                       if (!dn_atm_node) {
+                               _DBG("no data available");
+                               continue;
+                       }
+
+                       _DBG("device-network data available");
+
+                       RX += dn_atm_node->rx;
+                       TX += dn_atm_node->tx;
+
+                       prv_data = NULL;
+                       prv_app_id = NULL;
+
+                       if (g_hash_table_lookup_extended(hash, dn_atm_node->app_id, &prv_app_id, &prv_data) == true) {
+
+                               _DBG("previous app_id = %s", (char *)prv_app_id);
+
+                               app_time_map_st2 *dn_atm_prv_node = (app_time_map_st2 *)prv_data;
+
+                               dn_atm_node->time += dn_atm_prv_node->time;
+                               dn_atm_node->rx += dn_atm_prv_node->rx;
+                               dn_atm_node->tx += dn_atm_prv_node->tx;
+
+                               _DBG("update - app_id(%s), time(%d), rx(%d), tx(%d)", dn_atm_node->app_id,
+                                               dn_atm_node->time, dn_atm_node->rx, dn_atm_node->tx);
+
+                               _INFO("updated - %d", g_hash_table_replace(hash, dn_atm_node->app_id, dn_atm_node));
+
+                       } else {
+
+                               _DBG("insert - app_id(%s), time(%d), rx(%d), tx(%d)", dn_atm_node->app_id,
+                                               dn_atm_node->time, dn_atm_node->rx, dn_atm_node->tx);
+
+                               _INFO("inserted - %d", g_hash_table_insert(hash, dn_atm_node->app_id, dn_atm_node));
+                       }
+               }
+       }
+
+       /* Read standard Rated Values from Device Spec File/Power Profile File */
+       int sP_power_dn_tl0 = 0, sP_power_dn_tl1 = 0, sP_power_dn_tl2 = 0, sP_power_dn_tl3 = 0, sP_power_dn_tl4 = 0,
+       sP_power_dn_tl5 = 0, sP_power_dn_tl6 = 0, sP_power_dn_tx = 0, sP_power_dn_rx = 0;
+
+       ret_val = bm_get_device_network_power_params(&sP_power_dn_tl0, &sP_power_dn_tl1, &sP_power_dn_tl2, &sP_power_dn_tl3,
+                       &sP_power_dn_tl4, &sP_power_dn_tl5, &sP_power_dn_tl6, &sP_power_dn_rx, &sP_power_dn_tx);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("failed to get cpu power params");
+
+       _DBG("received device-network power params - signal_0[%d]\n, signal_1[%d]\n, signal_2[%d]\n, \
+                       signal_3[%d]\n, signal_4[%d]\n, signal_5[%d]\n, signal_6[%d]\n, rx[%d]\n, tx[%d]\n",
+                       sP_power_dn_tl0, sP_power_dn_tl1, sP_power_dn_tl2, sP_power_dn_tl3, sP_power_dn_tl4, sP_power_dn_tl5,
+                       sP_power_dn_tl6, sP_power_dn_rx, sP_power_dn_tx);
+
+       int tl_total = 0;
+       tl_total = tl0 + tl1 + tl2 + tl3 + tl4 + tl5 + tl6;
+
+       /* Device Network power consumption Level - 1 at the Resource Level */
+       int P_power_dntw = 0, P_power_data = 0, P_power_conn = 0;
+       P_power_conn = ((sP_power_dn_tl0 * tl0) + (sP_power_dn_tl1 * tl1) + (sP_power_dn_tl2 * tl2) + (sP_power_dn_tl3 * tl3) + (sP_power_dn_tl4 * tl4) + (sP_power_dn_tl5 * tl5) + (sP_power_dn_tl6 * tl6));
+       P_power_data = ((sP_power_dn_tx) * TX) + ((sP_power_dn_rx) * RX);
+
+       P_power_dntw = P_power_conn + P_power_data;
+
+       _DBG("Calculated Power for Device Network P_power_ntw(%d),  P_power_conn (%d), P_power_data(%d)", P_power_dntw, P_power_conn, P_power_data);
+
+       /* Device Network power consumption Level - 2 at the Application Level */
+       GHashTableIter iter;
+       gpointer key, value;
+
+       g_hash_table_iter_init(&iter, hash);
+
+       int P_power_app_dntw = 0, P_power_app_data = 0, P_power_app_conn = 0;
+       char *appid = NULL;
+       int apprx = 0, apptx = 0, apptime = 0;
+
+       long int ret_time = bm_get_log_time();
+
+       appid_usage_s *app_usage = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (app_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       while (g_hash_table_iter_next(&iter, &key, &value)) {
+               P_power_app_dntw = 0; P_power_app_data = 0 ; P_power_app_conn = 0;
+               apprx = 0, apptx = 0, apptime = 0;
+
+               app_time_map_st2 *temp = (app_time_map_st2 *)value;
+
+               appid = temp->app_id;
+               apprx = temp->rx;
+               apptx = temp->tx;
+               apptime = temp->time;
+
+               P_power_app_data = ((sP_power_dn_tx) * apptx) + ((sP_power_dn_rx) * apprx);
+               if (tl_total != 0)
+                       P_power_app_conn = P_power_conn * (apptime/tl_total); //check for 0 denominator & same units
+               P_power_app_dntw = P_power_app_data + P_power_app_conn;
+
+               app_usage->AppId = appid;
+               app_usage->rId_device_network = P_power_app_dntw;
+               app_usage->log_time = ret_time;
+
+               /* Call Insert Function */
+               _DBG("Calculated Power for Appid (%s) P_power_app_dntw(%d),  P_power_app_conn (%d), P_power_app_data(%d)", appid, P_power_app_dntw, P_power_app_conn, P_power_app_data);
+               if (mode)
+                       ret_val = bm_server_app_usage_insert_to_db(app_usage);
+               else
+                       ret_val = bm_appid_session_usage_map(g_strdup(app_usage->AppId), app_usage->rId_device_network, BM_PLUGIN_ID_DEVICE_NETWORK);
+
+               /* Error Check */
+               if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+                       _ERR("Insert of Data Ntwk App failed ");
+               else
+                       _DBG("Insert successful");
+       }
+
+       /* commit to database the output after power calculation */
+       resourceid_usage_s *res_usage = (resourceid_usage_s *)calloc(1, sizeof(resourceid_usage_s));
+       if (res_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       res_usage->ResourceId = BM_RID_DNTW;
+       res_usage->log_time = ret_time;
+       res_usage->usage = P_power_dntw;
+
+       ret_val = bm_server_resource_usage_insert_to_db(res_usage);
+       /* Error Check */
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("Insert of Data Network resource failed ");
+       else
+               _DBG("Insert successful");
+
+
+       bm_appid_usage_free(app_usage);
+       bm_resourceid_usage_free(res_usage);
+
+       /* Free the Hash Map */
+       g_hash_table_destroy(hash);
+
+       EXIT;
+       return ret_val;
+}
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+int bm_gps_calc_power_and_commit(bm_gps_st *handle)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       GSList *gps_data_iterator = NULL;
+       GSList *gps_atm_iterator = NULL;
+
+       void *prv_data = NULL;
+       void *prv_app_id = NULL;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       /* creating hash-map with (key, value) = (app-id, data) */
+       GHashTable *hash = g_hash_table_new_full(g_str_hash, g_str_equal, bm_data_free, bm_atm_st1_free);
+
+       long int edTime = 0;
+       long int stTime = 0;
+       int sesTime = 0;
+       int onTime = 0;
+
+       /* iterating over list for data accumulation */
+       for (gps_data_iterator = handle->gps_data_list; gps_data_iterator; gps_data_iterator = gps_data_iterator->next) {
+
+               bm_gps_st *datalistnode = (bm_gps_st *)(gps_data_iterator->data);
+
+               edTime = datalistnode->connStartTime;
+               stTime = datalistnode->connStopTime;
+               sesTime = edTime - stTime;
+
+               gps_atm_iterator = datalistnode->atm_list;
+//             gps_atm_iterator = ((bm_gps_st *)(gps_data_iterator->data))->atm_list;
+
+               for ( ; gps_atm_iterator; gps_atm_iterator = gps_atm_iterator->next) {
+
+                       app_time_map_st1 *gps_atm_node = (app_time_map_st1 *)gps_atm_iterator->data;
+
+                       if (!gps_atm_node) {
+                               _DBG("no bt data available");
+                               continue;
+                       }
+
+                       _DBG("gps data available");
+
+                       onTime += gps_atm_node->time;
+
+                       prv_app_id = NULL;
+                       prv_data = NULL;
+
+                       if (g_hash_table_lookup_extended(hash, gps_atm_node->app_id, &prv_app_id, &prv_data) == true) {
+
+                               _DBG("previous app_id = %s", (char *)prv_app_id);
+
+                               app_time_map_st1 *gps_atm_prv_node = (app_time_map_st1 *)prv_data;
+
+                               gps_atm_node->time += gps_atm_prv_node->time;
+
+                               _DBG("update - app_id(%s), time(%d)", gps_atm_node->app_id, gps_atm_node->time);
+
+                               _INFO("updated - %d", g_hash_table_replace(hash, gps_atm_node->app_id, gps_atm_node));
+
+                       } else {
+
+                               _DBG("insert - app_id(%s), time(%d)", gps_atm_node->app_id, gps_atm_node->time);
+
+                               _INFO("inserted - %d", g_hash_table_insert(hash, gps_atm_node->app_id, gps_atm_node));
+                       }
+               }
+       }
+
+       /* Read standard Rated Values from Device Spec File/Power Profile File */
+       int sP_power_gps_conn = 0;
+
+       ret_val = bm_get_gps_sensor_power_params(&sP_power_gps_conn);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("failed to get gps-sensor power params");
+
+       _DBG("gps-sensor power params - gps[%d]", sP_power_gps_conn);
+
+       /* GPS power consumption Level - 1 at the Resource Level */
+       int P_power_gps = 0, P_power_conn = 0;
+       P_power_conn = ((sP_power_gps_conn * sesTime));
+
+       P_power_gps = P_power_conn;
+       _DBG("Calculated Power for GPS P_power_gps (%d),  P_power_conn (%d)", P_power_gps, P_power_conn);
+
+       /* GPS power consumption Level - 2 at the Application Level */
+       GHashTableIter iter;
+       gpointer key, value;
+
+       g_hash_table_iter_init(&iter, hash);
+
+       int P_power_app_gps = 0, P_power_app_conn = 0;
+       char *appid = NULL;
+       int apptime = 0;
+
+       long int ret_time = bm_get_log_time();
+
+       appid_usage_s *app_usage = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (app_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       while (g_hash_table_iter_next(&iter, &key, &value)) {
+               P_power_app_gps = 0; P_power_app_conn = 0;
+               apptime = 0;
+
+               app_time_map_st1 *temp = (app_time_map_st1 *)value;
+
+               appid = temp->app_id;
+               apptime = temp->time;
+
+               if (onTime != 0)
+                       P_power_app_conn = P_power_conn * (apptime/onTime); //check for 0 denominator & same units
+               P_power_app_gps = P_power_app_conn;
+
+               app_usage->AppId = appid;
+               app_usage->rId_gps = P_power_app_gps;
+               app_usage->log_time = ret_time;
+
+               /* Call Insert Function */
+               _DBG("Calculated Power for Appid (%s) P_power_app_gps (%d),  P_power_app_conn (%d)", appid, P_power_app_gps, P_power_app_conn);
+               ret_val = bm_server_app_usage_insert_to_db(app_usage);
+               /* Error Check */
+               if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+                       _ERR("Insert of GPS App failed ");
+               else
+                       _DBG("Insert successful");
+       }
+
+       /* commit to database the output after power calculation */
+       resourceid_usage_s *res_usage = (resourceid_usage_s *)calloc(1, sizeof(resourceid_usage_s));
+       if (res_usage == NULL) {
+               _ERR("memory allocation failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       res_usage->ResourceId = BM_RID_GPS;
+       res_usage->log_time = ret_time;
+       res_usage->usage = P_power_gps;
+
+       ret_val = bm_server_resource_usage_insert_to_db(res_usage);
+       /* Error Check */
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("Insert of GPS resource failed ");
+       else
+               _DBG("Insert successful");
+
+       bm_appid_usage_free(app_usage);
+       bm_resourceid_usage_free(res_usage);
+
+       /* Free the Hash Map */
+       g_hash_table_destroy(hash);
+
+       EXIT;
+       return ret_val;
+}
+
+int bm_hrm_calc_power_and_commit(bm_hrm_sensor_st *handle)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       GSList *hrm_data_iterator = NULL;
+       GSList *hrm_atm_iterator = NULL;
+
+       void *prv_data = NULL;
+       void *prv_app_id = NULL;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       /* creating hash-map with (key, value) = (app-id, data) */
+       GHashTable *hash = g_hash_table_new_full(g_str_hash, g_str_equal, bm_data_free, bm_atm_st1_free);
+
+       /* iterating over list for data accumulation */
+       for (hrm_data_iterator = handle->hrm_data_list; hrm_data_iterator; hrm_data_iterator = hrm_data_iterator->next) {
+
+               hrm_atm_iterator = ((bm_hrm_sensor_st *)(hrm_data_iterator->data))->atm_list;
+
+               for ( ; hrm_atm_iterator; hrm_atm_iterator = hrm_atm_iterator->next) {
+
+                       app_time_map_st1 *hrm_atm_node = (app_time_map_st1 *)hrm_atm_iterator->data;
+
+                       if (!hrm_atm_node) {
+                               _DBG("no bt data available");
+                               continue;
+                       }
+
+                       _DBG("hrm data available");
+
+                       prv_data = NULL;
+                       prv_app_id = NULL;
+
+                       if (g_hash_table_lookup_extended(hash, hrm_atm_node->app_id, &prv_app_id, &prv_data) == true) {
+
+                               _DBG("previous app_id = %s", (char *)prv_app_id);
+
+                               app_time_map_st1 *hrm_atm_prv_node = (app_time_map_st1 *)prv_data;
+
+                               hrm_atm_node->time += hrm_atm_prv_node->time;
+
+                               _DBG("update - app_id(%s), time(%d)", hrm_atm_node->app_id, hrm_atm_node->time);
+
+                               _INFO("updated - %d", g_hash_table_replace(hash, hrm_atm_node->app_id, hrm_atm_node));
+
+                       } else {
+
+                               _DBG("insert - app_id(%s), time(%d)", hrm_atm_node->app_id, hrm_atm_node->time);
+
+                               _INFO("inserted - %d", g_hash_table_insert(hash, hrm_atm_node->app_id, hrm_atm_node));
+                       }
+               }
+       }
+
+       int sP_power_hrm_conn = 0;
+
+       /* read hrm-sensor power params */
+       ret_val = bm_get_hrm_sensor_power_params(&sP_power_hrm_conn);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("failed to get hrm-sensor power params");
+
+       _DBG("hrm-sensor power params - gps[%d]", sP_power_hrm_conn);
+
+       /* apply power calculation on the hash-map data*/
+
+       /* commit to database the output after power calculation */
+
+       /* Free the Hash Map */
+       g_hash_table_destroy(hash);
+
+       EXIT;
+       return ret_val;
+}
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+int bm_battery_calc_power_and_commit(void)
+{
+       ENTER;
+
+       int ret_val = DEVICE_ERROR_NONE;
+       int battery_percent = 0;
+       bool is_charging = false;
+
+       ret_val = device_battery_get_percent(&battery_percent);
+       BM_RETURN_VAL((ret_val == DEVICE_ERROR_NONE), {},
+               BATTERY_MONITOR_ERROR_INTERNAL, "failed to get battery percent");
+
+       ret_val = device_battery_is_charging(&is_charging);
+       BM_RETURN_VAL((ret_val == DEVICE_ERROR_NONE), {},
+               BATTERY_MONITOR_ERROR_INTERNAL, "failed to get charging status");
+
+       device_battery_level_e battery_level;
+       ret_val = device_battery_get_level_status(&battery_level);
+       BM_RETURN_VAL((ret_val == DEVICE_ERROR_NONE), {},
+               BATTERY_MONITOR_ERROR_INTERNAL, "failed to get warning status");
+
+       switch (battery_level) {
+       case DEVICE_BATTERY_LEVEL_EMPTY:
+               _DBG("battery level - EMPTY");
+               break;
+       case DEVICE_BATTERY_LEVEL_CRITICAL:
+               _DBG("battery level - CRITICAL");
+               break;
+       case DEVICE_BATTERY_LEVEL_LOW:
+               _DBG("battery level - LOW");
+               break;
+       case DEVICE_BATTERY_LEVEL_HIGH:
+               _DBG("battery level - HIGH");
+               break;
+       case DEVICE_BATTERY_LEVEL_FULL:
+               _DBG("battery level - FULL");
+               break;
+       default:
+               _DBG("invalid battery-level");
+               break;
+       }
+
+       _INFO("battery percent[%d] & charging status[%s]",
+               battery_percent, (is_charging == true) ? "TRUE" : "FALSE");
+
+       int sP_power_battery = 0;
+
+       ret_val = bm_get_battery_power_params(&sP_power_battery);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("failed to get battery power params");
+
+       _DBG("received battery power params - battery[%d]", sP_power_battery);
+
+       ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       EXIT;
+       return ret_val;
+}
+
+int bm_get_data_from_handles(void)
+{
+       ENTER;
+
+       BM_CHECK_INPUT_PARAM(bm_data_handle);
+       BM_CHECK_INPUT_PARAM(bm_req_flag_h);
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+       bool mode = false;
+
+       gl_hash = g_hash_table_new_full(g_str_hash, g_str_equal, bm_data_free, g_free);
+       if (!gl_hash)
+               _ERR("Global Hash creation failed");
+
+       /* parsing ble data */
+       if (bm_data_handle->bm_ble_handle != NULL &&
+                       bm_req_flag_h->req_ble_data) {
+
+               _DBG("parsing ble data");
+
+               ret_val = bm_ble_calc_power_and_commit(bm_data_handle->bm_ble_handle, mode);
+
+               BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "ble power cal failure");
+
+       } else {
+               _DBG("set ble flag - true");
+               bm_req_flag_h->req_ble_data = true;
+       }
+
+       _DBG("completed ble data request");
+
+       /* parsing wifi data */
+       if (bm_data_handle->bm_wifi_handle != NULL &&
+                       bm_req_flag_h->req_wifi_data) {
+
+               _DBG("parsing wifi data");
+
+               ret_val = bm_wifi_calc_power_and_commit(bm_data_handle->bm_wifi_handle, mode);
+
+               BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "wifi power calc failure");
+       } else {
+               _DBG("set wifi flag - true");
+               bm_req_flag_h->req_wifi_data = true;
+       }
+
+       _DBG("completed wifi data request");
+
+       /* parsing cpu data */
+       if (bm_data_handle->bm_cpu_handle != NULL &&
+                       bm_req_flag_h->req_cpu_data) {
+
+               _DBG("parsing cpu data");
+
+               ret_val = bm_cpu_calc_power_and_commit(bm_data_handle->bm_cpu_handle, mode);
+
+               BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "cpu power calc failure");
+       } else {
+               _DBG("set cpu flag - true");
+               bm_req_flag_h->req_cpu_data = true;
+       }
+
+       _DBG("completed cpu data request");
+
+       /* parsing display data */
+       if (bm_data_handle->bm_display_handle != NULL &&
+                       bm_req_flag_h->req_dp_data) {
+
+               _DBG("parsing display data");
+
+               ret_val = bm_display_calc_power_and_commit(bm_data_handle->bm_display_handle, mode);
+
+               BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "display power calc failure");
+       } else {
+               _DBG("set display flag - true");
+               bm_req_flag_h->req_dp_data = true;
+       }
+
+       _DBG("completed display data request");
+
+       /* parsing device-network data */
+       if (bm_data_handle->bm_dn_handle != NULL &&
+                       bm_req_flag_h->req_dn_data) {
+
+               _DBG("parsing device-network data");
+
+               ret_val = bm_device_network_calc_power_and_commit(bm_data_handle->bm_dn_handle, mode);
+
+               BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "device-network power calc failure");
+       } else {
+               _DBG("set device-network flag - true");
+               bm_req_flag_h->req_dn_data = true;
+       }
+
+       _DBG("completed device-network data request");
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       /* parsing gps data */
+       if (bm_data_handle->bm_gps_handle != NULL &&
+                       bm_req_flag_h->req_gps_data) {
+
+               _DBG("parsing gps data");
+
+               ret_val = bm_gps_calc_power_and_commit(bm_data_handle->bm_gps_handle);
+
+               BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "gps-sensor power calc failure");
+       } else {
+               _DBG("set gps-sensor flag - true");
+               bm_req_flag_h->req_gps_data = true;
+       }
+
+       _DBG("completed gps data request");
+
+       /* parsing hrm data */
+       if (bm_data_handle->bm_hrm_handle != NULL &&
+                       bm_req_flag_h->req_hrm_data) {
+
+               _DBG("parsing hrm data");
+
+               ret_val = bm_hrm_calc_power_and_commit(bm_data_handle->bm_hrm_handle);
+
+               BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "hrm-sensor power calc failure");
+       } else {
+               _DBG("set hrm-sensor flag - true");
+               bm_req_flag_h->req_hrm_data = true;
+       }
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+       _DBG("completed hrm data request");
+
+       /* parsing battery data */
+
+       _DBG("parsing battery data");
+
+       ret_val = bm_battery_calc_power_and_commit();
+
+       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "battery power calc failure");
+
+       _DBG("completed battery data request");
+
+       ret_val = bm_insert_appid_session_usage_to_db();
+       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), "battery session logging failure");
+
+       /* set free all the data handles */
+       //bm_set_free_data_handles(bm_data_handle);
+
+       if (gl_hash) {
+               g_hash_table_destroy(gl_hash);
+               gl_hash = NULL;
+       }
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int bm_start_getting_feature_data(void)
+{
+       ENTER;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+       int id;
+       bm_plugin_info_h *bm_plugin = NULL;
+       bm_data_h handle = NULL;
+
+       /* allocate  data & flag handle */
+       if (bm_data_handle == NULL) {
+               bm_data_handle = (bm_feature_data_h)calloc(1, sizeof(struct bm_feature_data_handles_s));
+               if (!bm_data_handle) {
+                       _ERR("memory allocation failed - data handle");
+                       return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+               }
+
+               bm_req_flag_h = (struct bm_req_feature_data_handle_flag_s *)
+                                       calloc(1, sizeof(struct bm_req_feature_data_handle_flag_s));
+               if (!bm_req_flag_h) {
+                       _ERR("memory allocation failed - requet flag handle");
+                       return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+               }
+
+               bm_set_req_flag_handles(true);
+       }
+
+       /* request data from each plugin & store its handle */
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       for (id = BM_PLUGIN_ID_BLE; id < BM_PLUGIN_ID_MAX; ++id) {
+#else
+       for (id = BM_PLUGIN_ID_BLE; id <= BM_PLUGIN_ID_DEVICE_NETWORK; ++id) {
+#endif
+               bm_get_feature_plugin_handle(&bm_plugin, id);
+
+               if (!bm_plugin || !bm_plugin->api) {
+                       _WARN("Plugin with ID: %s is NULL", bm_get_plugin_name(id));
+                       continue;
+               }
+
+               _INFO(" requesting data from plugin - %s", bm_get_plugin_name(id));
+
+               switch (id) {
+               case BM_PLUGIN_ID_BLE: /* BLE Data */
+                       ret_val = bm_plugin->api->get_feature_data(&handle, id);
+
+                       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE),"'ble' data not available");
+
+                       if (handle != NULL) {
+                               _DBG("received ble data handle");
+                               bm_data_handle->bm_ble_handle = (bm_bluetooth_st *)(handle);
+                       }
+                       break;
+               case BM_PLUGIN_ID_WIFI: /* WI-FI Data */
+                       ret_val = bm_plugin->api->get_feature_data(&handle, id);
+
+                       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE),"'wifi' data not available");
+
+                       if (handle != NULL) {
+                               _DBG("received wifi data handle");
+                               bm_data_handle->bm_wifi_handle = (bm_wifi_st *)(handle);
+                       }
+                       break;
+               case BM_PLUGIN_ID_CPU: /* CPU Data */
+                       ret_val = bm_plugin->api->get_feature_data(&handle, id);
+
+                       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE),"'cpu' data not available");
+
+                       if (handle != NULL) {
+                               _DBG("received cpu data handle");
+                               bm_data_handle->bm_cpu_handle = (bm_cpu_st *)(handle);
+                       }
+                       break;
+               case BM_PLUGIN_ID_DISPLAY: /* DISPLAY Data */
+                       ret_val = bm_plugin->api->get_feature_data(&handle, id);
+
+                       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE),"'display' data not available");
+
+                       if (handle != NULL) {
+                               _DBG("received display data handle");
+                               bm_data_handle->bm_display_handle = (bm_display_st *)(handle);
+                       }
+                       break;
+               case BM_PLUGIN_ID_DEVICE_NETWORK: /* DEVICE-NETWORK Data */
+                       ret_val = bm_plugin->api->get_feature_data(&handle, id);
+
+                       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE),"'device-network' data not available");
+
+                       if (handle != NULL) {
+                               _DBG("received device network data handle");
+                               bm_data_handle->bm_dn_handle = (bm_device_network_st *)(handle);
+                       }
+                       break;
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+               case BM_PLUGIN_ID_GPS_SENSOR: /* GPS Sensor Data */
+                       ret_val = bm_plugin->api->get_feature_data(&handle, id);
+
+                       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE),"'gps-sensor' data not available");
+
+                       if (handle != NULL) {
+                               _DBG("received gps data handle");
+                               bm_data_handle->bm_gps_handle = (bm_gps_st *)(handle);
+                       }
+                       break;
+               case BM_PLUGIN_ID_HRM_SENSOR: /* HRM Sensor Data */
+                       ret_val = bm_plugin->api->get_feature_data(&handle, id);
+
+                       BM_CHECK_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE),"'hrm-sensor' data not available");
+
+                       if (handle != NULL) {
+                               _DBG("received hrm data handle");
+                               bm_data_handle->bm_hrm_handle = (bm_hrm_sensor_st *)(handle);
+                       }
+                       break;
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+               default:
+                       break;
+               }
+       }
+
+       /* parse data which is received through handles */
+       ret_val = bm_get_data_from_handles();
+       BM_RETURN_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), {},
+                       BATTERY_MONITOR_ERROR_INTERNAL, "erorr in parsing data from handles");
+
+       EXIT;
+       return ret_val;
+}
+
+int bm_clean_db_table_for_job_id(void)
+{
+       ENTER;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       ret_val = bm_server_delete_table_by_time_interval();
+
+       BM_RETURN_VAL((ret_val == BATTERY_MONITOR_ERROR_NONE), {},
+                       BATTERY_MONITOR_ERROR_DB_FAILED, "error in deleting old db data");
+
+       EXIT;
+       return ret_val;
+}
+
+gboolean bm_request_feature_data(gpointer data)
+{
+       ENTER;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       ret_val = bm_start_getting_feature_data();
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("error requesting feature data");
+
+       EXIT;
+       return true;
+}
+
+gboolean bm_delete_data_from_db(gpointer data)
+{
+       ENTER;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       ret_val = bm_clean_db_table_for_job_id();
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("error cleaning database");
+
+       EXIT;
+       return true;
+}
+
+int initialize_power_engine(void)
+{
+       ENTER;
+
+       int ret_val = BATTERY_MONITOR_ERROR_NONE;
+
+       g_timeout_add(BATTERY_MONITOR_GET_DATA_JOB_PERIOD, bm_request_feature_data, NULL);
+
+       g_timeout_add(BATTERY_MONITOR_DELETE_DB_JOB_PERIOD, bm_delete_data_from_db, NULL);
+
+       EXIT;
+       return ret_val;
+}
+
+void deinitialize_power_engine(void)
+{
+       ENTER;
+
+       /* set all data-handle free */
+       if (bm_data_handle != NULL) {
+               _DBG("setting handle free - deinitializing");
+               bm_set_free_data_handles(bm_data_handle);
+       }
+
+       /* set flag handle free*/
+       BM_FREE(bm_req_flag_h);
+
+       EXIT;
+       return;
+}
diff --git a/src/bm_server.c b/src/bm_server.c
new file mode 100644 (file)
index 0000000..42f9b09
--- /dev/null
@@ -0,0 +1,453 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <signal.h>
+#include <cynara-client.h>
+#include <cynara-session.h>
+#include <cynara-creds-gdbus.h>
+
+#include "bm_dbg.h"
+#include "bm_server.h"
+#include "bm_plugin_manager.h"
+#include "bm_server_db.h"
+#include "bm_power_engine.h"
+#include "bm_util.h"
+#include "bm_common.h"
+
+static GMainLoop *mainloop = NULL;
+static guint owner_id = 0;
+
+BatteryMonitor *batterymonitor_obj = NULL;
+
+static void bm_signal_handler(int signo, siginfo_t *info, void *data)
+{
+       ENTER;
+
+       _WARN("signal [%d] is sent by [%d]", signo, info->si_pid);
+
+       if (SIGTERM == signo || SIGSYS == signo || SIGINT == signo || SIGUSR1 == signo) {
+               _WARN("quitting service");
+               g_main_loop_quit(mainloop);
+       }
+
+       EXIT;
+       return;
+}
+
+static void bm_set_signal_handling_info()
+{
+       ENTER;
+
+       struct sigaction bm_sa;
+
+       BM_MEMSET(&bm_sa, 0, sizeof(bm_sa));
+
+       bm_sa.sa_sigaction = bm_signal_handler;
+       bm_sa.sa_flags = SA_SIGINFO;
+       sigaction(SIGINT, &bm_sa, NULL);
+       sigaction(SIGTERM, &bm_sa, NULL);
+       sigaction(SIGUSR1, &bm_sa, NULL);
+
+       EXIT;
+       return;
+}
+
+gboolean
+bm_get_usage_by_app_id_for_resource_id(BatteryMonitor *obj, GDBusMethodInvocation *invocation, const gchar *app_id,
+                                                       gint resource_id, gint duration, gint uid)
+{
+       ENTER;
+
+       _INFO("app_id [%s], resource_id [%d], duration [%d]", app_id, resource_id, duration);
+
+       if (!app_id || (resource_id >= BM_PLUGIN_ID_MAX) || (duration >= BM_DURATION_TYPE_MAX)) {
+               _ERR("invalid function param");
+               return false;
+       }
+
+       int ret_val = bm_check_privilege_battery(invocation);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("privilege check failed, ret-val - %d", ret_val);
+               goto RETURN;
+       }
+
+       int battery_usage = 0;
+
+       ret_val = bm_engine_get_usage_by_app_id_for_resource_id(app_id, resource_id, duration, &battery_usage);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to get battery usage");
+               goto RETURN;
+       }
+
+       _INFO("battery usage - %d", battery_usage);
+
+RETURN:
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               GError* error = g_error_new(bm_error_quark(), ret_val, "info not available");
+               g_dbus_method_invocation_return_gerror(invocation, error);
+               g_error_free(error);
+       } else {
+               battery_monitor_complete_get_usage_by_app_id_for_resource_id(obj, invocation, battery_usage);
+       }
+
+       EXIT;
+       return true;
+}
+
+gboolean
+bm_get_total_usage_by_app_id(BatteryMonitor *obj, GDBusMethodInvocation *invocation,
+                                       const gchar *app_id, gint duration, gint uid)
+{
+       ENTER;
+
+       _INFO("app_id [%s], duration [%d]", app_id, duration);
+
+       if (!app_id || (duration >= BM_DURATION_TYPE_MAX))  {
+               _ERR("invalid function param");
+               return false;
+       }
+
+       int ret_val = bm_check_privilege_battery(invocation);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("privilege check failed, ret-val - %d", ret_val);
+               goto RETURN;
+       }
+
+       int battery_usage = 0;
+
+       ret_val = bm_engine_get_total_usage_by_app_id(app_id, duration, &battery_usage);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to get battery usage");
+               goto RETURN;
+       }
+
+       _INFO("battery usage - %d", battery_usage);
+
+RETURN:
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               GError* error = g_error_new(bm_error_quark(), ret_val, "info not available");
+               g_dbus_method_invocation_return_gerror(invocation, error);
+               g_error_free(error);
+       } else {
+               battery_monitor_complete_get_total_usage_by_app_id(obj, invocation, battery_usage);
+       }
+
+       EXIT;
+       return true;
+}
+
+gboolean
+bm_get_total_usage_by_resource_id(BatteryMonitor *obj, GDBusMethodInvocation *invocation,
+                                       gint resource_id, gint duration, gint uid)
+{
+       ENTER;
+
+       _INFO("resource_id [%d], duration [%d]", resource_id, duration);
+
+       if ((resource_id >= BM_PLUGIN_ID_MAX) || (duration >= BM_DURATION_TYPE_MAX))  {
+               _ERR("invalid function param");
+               return false;
+       }
+
+       int ret_val = bm_check_privilege_battery(invocation);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("privilege check failed, ret-val - %d", ret_val);
+               goto RETURN;
+       }
+
+       int battery_usage = 0;
+
+       ret_val = bm_engine_get_total_usage_by_resource_id(resource_id, duration, &battery_usage);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to get battery usage");
+               goto RETURN;
+       }
+
+       _INFO("battery usage - %d", battery_usage);
+
+RETURN:
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               GError* error = g_error_new(bm_error_quark(), ret_val, "info not available");
+               g_dbus_method_invocation_return_gerror(invocation, error);
+               g_error_free(error);
+       } else {
+               battery_monitor_complete_get_total_usage_by_resource_id(obj, invocation, battery_usage);
+       }
+
+       EXIT;
+       return true;
+}
+
+gboolean
+bm_get_all_resource_usage(BatteryMonitor *obj, GDBusMethodInvocation *invocation,
+                               const gchar *app_id, gint duration, gint uid)
+{
+       ENTER;
+
+       _INFO("app_id [%s], duration [%d]", app_id, duration);
+
+       if (!app_id || (duration >= BM_DURATION_TYPE_MAX))  {
+               _ERR("invalid function param");
+               return false;
+       }
+
+       bm_total_consumption_h battery_data = NULL;
+
+       int ret_val = bm_check_privilege_battery(invocation);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("privilege check failed, ret-val - %d", ret_val);
+               goto RETURN;
+       }
+
+       GVariant *battery_variant = NULL;
+
+       battery_data = (bm_total_consumption_h)calloc(1, sizeof(struct battery_total_consumption_s));
+       if (battery_data == NULL) {
+               ret_val = BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+               _ERR("memory allocation failed");
+               goto RETURN;
+       }
+
+       _INFO("before request to engine");
+
+       ret_val = bm_engine_get_all_resource_usage(app_id, duration, battery_data);
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("failed to get battery data");
+               goto RETURN;
+       }
+
+       _INFO("after request to engine");
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       _INFO("data received - bt[%d], wifi[%d], cpu[%d], dp[%d], dn[%d], gps[%d], hrm[%d], bat[%d]",
+                       battery_data->ble_val, battery_data->wifi_val, battery_data->cpu_val, battery_data->dp_val,
+                       battery_data->dn_val, battery_data->gps_val, battery_data->hrm_val, battery_data->bat_val);
+#else
+       _INFO("data received - bt[%d], wifi[%d], cpu[%d], dp[%d], dn[%d], bat[%d]",
+                       battery_data->ble_val, battery_data->wifi_val, battery_data->cpu_val, battery_data->dp_val,
+                       battery_data->dn_val, battery_data->bat_val);
+#endif
+       if (ret_val == BATTERY_MONITOR_ERROR_NONE)
+               battery_variant = bm_marshal_serialized_data(battery_data);
+
+RETURN:
+       if (ret_val != BATTERY_MONITOR_ERROR_NONE) {
+               GError* error = g_error_new(bm_error_quark(), ret_val, "info not available");
+               g_dbus_method_invocation_return_gerror(invocation, error);
+               g_error_free(error);
+       } else {
+               battery_monitor_complete_get_all_resource_usage(obj, invocation, battery_variant);
+       }
+
+       BM_FREE(battery_data);
+
+       EXIT;
+       return true;
+}
+
+static int bm_set_dbus_interface_handles(BatteryMonitorIface *iface)
+{
+       ENTER;
+
+       BM_RETURN_VAL((iface != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "interface handle is null");
+
+       iface->handle_get_usage_by_app_id_for_resource_id = &bm_get_usage_by_app_id_for_resource_id;
+
+       iface->handle_get_total_usage_by_app_id = &bm_get_total_usage_by_app_id;
+
+       iface->handle_get_total_usage_by_resource_id = &bm_get_total_usage_by_resource_id;
+
+       iface->handle_get_all_resource_usage = &bm_get_all_resource_usage;
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+static void on_bus_acquired(GDBusConnection *connection, const gchar *name, gpointer user_data)
+{
+       ENTER;
+
+       _INFO("on_bus_acquired [%s]", name);
+
+       GDBusInterfaceSkeleton* interface = NULL;
+
+       batterymonitor_obj = battery_monitor_skeleton_new();
+       if (batterymonitor_obj == NULL) {
+               _ERR("batterymonitor_obj NULL!!");
+               return;
+       }
+
+       interface = G_DBUS_INTERFACE_SKELETON(batterymonitor_obj);
+       if (!g_dbus_interface_skeleton_export(interface, connection, BATTERY_MONITOR_DBUS_PATH, NULL)) {
+               _ERR("export failed!!");
+               return;
+       }
+
+       BatteryMonitorIface *iface = BATTERY_MONITOR_GET_IFACE(batterymonitor_obj);
+       if (iface == NULL) {
+               _ERR("Failed to get interface");
+               return;
+       }
+
+       _INFO("connecting battery-monitor signals start");
+
+       if (BATTERY_MONITOR_ERROR_NONE != bm_set_dbus_interface_handles(iface)) {
+               _ERR("failed to set dbus interface handles");
+               return;
+       }
+
+       _INFO("connecting battery-monitor signals end");
+
+       _INFO("on_bus_acquired end [%s]", name);
+
+       EXIT;
+       return;
+}
+
+static void on_name_acquired(GDBusConnection *connection, const gchar *name, gpointer user_data)
+{
+       _INFO("on_name_acquired");
+}
+
+static void on_name_lost(GDBusConnection *connection, const gchar *name, gpointer user_data)
+{
+       _INFO("on_name_lost");
+       exit(1);
+}
+
+static bool initialize_dbus()
+{
+       ENTER;
+
+       _INFO("__initialize_dbus Enter");
+
+       owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
+                       BATTERY_MONITOR_DBUS_NAME,
+                       G_BUS_NAME_OWNER_FLAGS_NONE,
+                       on_bus_acquired,
+                       on_name_acquired,
+                       on_name_lost,
+                       NULL,
+                       NULL);
+
+       _INFO("owner_id=[%d]", owner_id);
+
+       if (owner_id == 0) {
+               _INFO("gdbus own failed!!");
+               return BATTERY_MONITOR_ERROR_NOT_INITIALIZED;
+       }
+
+       _INFO("g_bus_own_name SUCCESS");
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+static void bm_server_initialize()
+{
+       ENTER;
+
+#if !GLIB_CHECK_VERSION(2, 35, 0)
+       g_type_init();
+#endif
+       int return_code = BATTERY_MONITOR_ERROR_NONE;
+
+       /* dbus initialization */
+       return_code = initialize_dbus();
+       if (return_code != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("dbus initialization failed");
+               goto END;
+       }
+
+       /* battery-monitor database initialization */
+       return_code = initialize_database();
+       if (return_code != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("database initialization failed");
+               goto END;
+       }
+
+       /* plugin-manager initialization */
+       return_code = initialize_plugin_manager();
+       if (return_code != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("plugin-manager initialization failed");
+               goto END;
+       }
+
+       /* power-engine initialization */
+       return_code = initialize_power_engine();
+       if (return_code != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("power-engine initialization failed");
+               goto END;
+       }
+
+       _INFO("SUCCESS");
+
+       EXIT;
+       return;
+END:
+       _ERR("error occurred, exiting daemon");
+       exit(1);
+       return;
+}
+
+static void bm_server_deinitialize()
+{
+       ENTER;
+
+       /* database de-initialization */
+       deinitialize_database();
+
+       /* plugin-manager de-initialization */
+       deinitialize_plugin_manager();
+
+       /* power-engine deinitialization */
+       deinitialize_power_engine();
+
+       _INFO("de-initialization success");
+
+       EXIT;
+       return;
+}
+
+int main()
+{
+       _INFO("Starting Battery-Monitor Service");
+
+       bm_set_signal_handling_info();
+
+       _INFO("server initialization");
+
+       bm_server_initialize();
+
+       _INFO("g_main_loop_new");
+
+       mainloop = g_main_loop_new(NULL, FALSE);
+
+       _INFO("g_main_loop_run");
+
+       g_main_loop_run(mainloop);
+
+       _INFO("g_main_loop_quit");
+
+       if (mainloop)
+               g_main_loop_unref(mainloop);
+
+       _INFO("server deinitialization");
+
+       bm_server_deinitialize();
+
+       return 0;
+}
diff --git a/src/bm_server_db.c b/src/bm_server_db.c
new file mode 100644 (file)
index 0000000..598d5fa
--- /dev/null
@@ -0,0 +1,1541 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <glib.h>
+#include <db-util.h>
+#include <pthread.h>
+#include <sqlite3.h>
+#include <time.h>
+#include <tzplatform_config.h>
+
+#include "bm_private.h"
+#include "bm_server_db.h"
+#include "bm_common.h"
+#include "bm_dbg.h"
+
+#define BM_DB_OPEN_READONLY 0
+#define BM_DB_OPEN_READWRITE 1
+
+static sqlite3* g_hBatteryMonitorDB = NULL;
+static sqlite3* g_hBatteryMonitorDB2 = NULL;
+
+pthread_mutex_t battery_monitor_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+static const char* bm_db_err_msg(sqlite3 *bm_db_handle)
+{
+       return sqlite3_errmsg(bm_db_handle);
+}
+
+static int bm_db_err_code(sqlite3 *bm_db_handle)
+{
+       return sqlite3_errcode(bm_db_handle);
+}
+
+char* bm_dup_text(const char *text_data)
+{
+       ENTER;
+
+       char *text_value = NULL;
+
+       if (text_data != NULL)
+               text_value = strdup(text_data);
+
+       EXIT;
+       return text_value;
+}
+
+static bm_stmt bm_prepare_query(sqlite3 *bm_db_handle, char *query)
+{
+       ENTER;
+
+       int rc = -1;
+       bm_stmt pStmt = NULL;
+
+       BM_RETURN_VAL((query != NULL), {}, NULL, ("query is NULL"));
+
+       rc = sqlite3_prepare_v2(bm_db_handle, query, strlen(query), &pStmt, NULL);
+
+       BM_RETURN_VAL((SQLITE_OK == rc), {}, NULL, ("sqlite3_prepare_v2() failed(%s).",
+                               bm_db_err_msg(bm_db_handle)));
+
+       EXIT;
+       return pStmt;
+}
+
+static int bm_execute_query(sqlite3 *bm_db_handle, const char *query)
+{
+       ENTER;
+
+       int rc = -1;
+       char *pszErrorMsg = NULL;
+
+       if (!query) {
+               _ERR("NULL query\n");
+               return BATTERY_MONITOR_ERROR_QUERY_SYNTAX_ERROR;
+       }
+
+       if (!bm_db_handle) {
+               _ERR("DB is not opened\n");
+               return BATTERY_MONITOR_ERROR_DB_NOT_OPENED;
+       }
+
+       rc = sqlite3_exec(bm_db_handle, query, NULL, NULL, &pszErrorMsg);
+       if (SQLITE_OK != rc) {
+               _ERR("sqlite3_exec rc(%d) failed(%s).", rc, pszErrorMsg);
+               sqlite3_free(pszErrorMsg);
+       }
+
+       EXIT;
+       return rc;
+}
+
+static int bm_query_finalize(bm_stmt pStmt)
+{
+       ENTER;
+
+       int rc = -1;
+
+       if (!pStmt) {
+               _ERR("pStmt is NULL");
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+       }
+
+       rc = sqlite3_finalize(pStmt);
+       if (rc == SQLITE_BUSY) {
+               _ERR(" sqlite3 busy = %d", rc);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (rc != SQLITE_OK) {
+               _ERR("sqlite3_finalize fail, rc : %d\n", rc);
+               return BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+static int bm_query_step(bm_stmt pStmt)
+{
+       ENTER;
+
+       if (!pStmt) {
+               _ERR("pStmt is NULL");
+               return -1;
+       }
+
+       return sqlite3_step(pStmt);
+}
+
+static int bm_begin_transaction(sqlite3 *bm_db_handle)
+{
+       ENTER;
+
+       int ret = -1;
+
+       ret = bm_execute_query(bm_db_handle, "BEGIN IMMEDIATE TRANSACTION");
+
+       if (ret == SQLITE_BUSY) {
+               _ERR(" sqlite3 busy = %d", ret);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (ret != SQLITE_OK) {
+               _ERR("bm_svc_begin_transaction fail :: %d", ret);
+               return BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int bm_get_next_sequence(sqlite3 *bm_db_handle, const char *pszName)
+{
+       ENTER;
+
+       int rc = 0;
+       bm_stmt pStmt = NULL;
+       int max_seq = 0;
+
+       char szQuery[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       BM_MEMSET(szQuery, 0x00, sizeof(szQuery));
+
+       BM_SNPRINTF(szQuery, sizeof(szQuery), "SELECT max(seq) FROM %s where name = '%s'",
+                               BATTERY_MONITOR_SQLITE_SEQ, pszName);
+
+       rc = sqlite3_prepare_v2(bm_db_handle, szQuery, strlen(szQuery), &pStmt, NULL);
+       if (SQLITE_OK != rc) {
+               BM_SLOGE("sqlite3_prepare_v2() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       rc = sqlite3_step(pStmt);
+
+       max_seq = sqlite3_column_int(pStmt, 0);
+
+       max_seq++;
+
+       rc = sqlite3_finalize(pStmt);
+       pStmt = NULL;
+
+       EXIT;
+       return max_seq;
+}
+
+static int bm_end_transaction(sqlite3 *bm_db_handle, bool is_success)
+{
+       ENTER;
+
+       int ret = -1;
+
+       if (is_success == true) {
+               ret = bm_execute_query(bm_db_handle, "COMMIT TRANSACTION");
+               _DBG("bm_end_transaction COMMIT");
+       } else {
+               ret = bm_execute_query(bm_db_handle, "ROLLBACK TRANSACTION");
+               _DBG("bm_end_transaction ROLLBACK");
+       }
+
+       if (ret == SQLITE_PERM) {
+               _ERR("Battery Monitor permission denied :: %d", ret);
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+
+       if (ret == SQLITE_BUSY) {
+               _DBG(" sqlite3 busy = %d", ret);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       }
+
+       if (ret != SQLITE_OK) {
+               _ERR("bm_svc_end_transaction fail :: %d", ret);
+               return BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+static int bm_query_bind_int(bm_stmt pStmt, int pos, int num)
+{
+       ENTER;
+
+       if (!pStmt) {
+               _ERR("statement is null");
+               return -1;
+       }
+
+       if (pos < 0) {
+               _ERR("invalid pos");
+               return -1;
+       }
+
+       EXIT;
+       return sqlite3_bind_int(pStmt, pos, num);
+}
+
+static int bm_query_bind_text(bm_stmt pStmt, int pos, const char *str)
+{
+       ENTER;
+
+       if (!pStmt) {
+               _ERR("statement is null");
+               return -1;
+       }
+
+       if (str) {
+               _INFO("sqlite3_bind_text");
+               return sqlite3_bind_text(pStmt, pos, (const char *)str, strlen(str), SQLITE_STATIC);
+       } else {
+               _INFO("sqlite3_bind_null");
+               return sqlite3_bind_null(pStmt, pos);
+       }
+}
+
+static int bm_query_table_column_int(bm_stmt pStmt, int pos)
+{
+       ENTER;
+
+       if (!pStmt) {
+               _ERR("statement is null");
+               return -1;
+       }
+
+       if (pos < 0) {
+               _ERR("invalid pos");
+               return -1;
+       }
+
+       return sqlite3_column_int(pStmt, pos);
+}
+
+static const char* bm_query_table_column_text(bm_stmt pStmt, int pos)
+{
+       ENTER;
+
+       if (!pStmt) {
+               _ERR("statement is null");
+               return NULL;
+       }
+
+       if (pos < 0) {
+               _ERR("invalid pos");
+               return NULL;
+       }
+
+       return (const char *)sqlite3_column_text(pStmt, pos);
+}
+
+static void bm_db_data_to_text(const char *textbuf, char **output)
+{
+       ENTER;
+
+       if (textbuf) {
+               if (*output) {
+                       free(*output);
+                       *output = NULL;
+               }
+               *output = strdup(textbuf);
+       }
+
+       EXIT;
+}
+
+static int bm_db_handle_close(sqlite3 *bm_db_handle)
+{
+       ENTER;
+
+       int rc = 0;
+       int ret = BATTERY_MONITOR_ERROR_NONE;
+
+       if (bm_db_handle) {
+               rc = db_util_close(bm_db_handle);
+               if (rc == SQLITE_OK)
+                       ret = BATTERY_MONITOR_ERROR_NONE;
+               else if (rc == SQLITE_PERM)
+                       ret = BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+               else if (rc == SQLITE_BUSY)
+                       ret = BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+               else
+                       ret = BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       EXIT;
+       return ret;
+}
+
+static int bm_appid_map_usage_convert_to_sql(appid_map_s *bm_appid_map_type, bm_stmt hstmt, char *sql_value)
+{
+       ENTER;
+
+       int count = 1;
+
+       /* Caution : Keep insert query orders. */
+
+       bm_query_bind_text(hstmt, count++, (char *)bm_appid_map_type->AppName);
+
+       bm_query_bind_int(hstmt, count++, bm_appid_map_type->AppId);
+
+       EXIT;
+       return count;
+}
+
+static int bm_appid_usage_convert_to_sql(appid_usage_s *bm_app_type, bm_stmt hstmt, char *sql_value)
+{
+       ENTER;
+
+       int count = 1;
+
+       /* Caution : Keep insert query orders. */
+
+       bm_query_bind_text(hstmt, count++, (char *)bm_app_type->AppId);
+
+       bm_query_bind_int(hstmt, count++, bm_app_type->log_time);
+
+       bm_query_bind_int(hstmt, count++, bm_app_type->rId_ble);
+
+       bm_query_bind_int(hstmt, count++, bm_app_type->rId_wifi);
+
+       bm_query_bind_int(hstmt, count++, bm_app_type->rId_cpu);
+
+       bm_query_bind_int(hstmt, count++, bm_app_type->rId_display);
+
+       bm_query_bind_int(hstmt, count++, bm_app_type->rId_device_network);
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       bm_query_bind_int(hstmt, count++, bm_app_type->rId_gps);
+
+       bm_query_bind_int(hstmt, count++, bm_app_type->rId_hrm);
+
+       bm_query_bind_int(hstmt, count++, bm_app_type->rId_battery);
+#endif
+       EXIT;
+       return count;
+}
+
+static int bm_resourceid_usage_convert_to_sql(resourceid_usage_s *bm_resource_type, bm_stmt hstmt, char *sql_value)
+{
+       ENTER;
+
+       int count = 1;
+
+       /* Caution : Keep insert query orders. */
+
+       bm_query_bind_text(hstmt, count++, (char *)bm_resource_type->ResourceId);
+
+       bm_query_bind_int(hstmt, count++, bm_resource_type->log_time);
+
+       bm_query_bind_int(hstmt, count++, bm_resource_type->usage);
+
+       EXIT;
+
+       return count;
+}
+
+static void bm_convert_column_to_resourceid_usage(bm_stmt hstmt, resourceid_usage_s* bm_resource_type)
+{
+       ENTER;
+
+       const char *textbuf = NULL;
+
+       textbuf = bm_query_table_column_text(hstmt, BM_RESOURCEUSAGE_FIELD_RESID);
+       bm_db_data_to_text(textbuf, &(bm_resource_type->ResourceId));
+
+       _DBG("bm_resource_type->ResourceId =[%s]", bm_resource_type->ResourceId);
+
+       bm_resource_type->log_time = -1;
+
+       bm_resource_type->usage = bm_query_table_column_int(hstmt, BM_RESOURCEUSAGE_FIELD_USAGE);
+
+       EXIT;
+       return;
+}
+
+static void bm_convert_column_to_appid_usage(bm_stmt hstmt, appid_usage_s* bm_app_type)
+{
+       ENTER;
+
+       const char *textbuf = NULL;
+
+       textbuf = bm_query_table_column_text(hstmt, BM_APPUSAGE_FIELD_APPID);
+       bm_db_data_to_text(textbuf, &(bm_app_type->AppId));
+
+       _DBG("bm_app_type->AppId =[%s]", bm_app_type->AppId);
+
+       bm_app_type->log_time = -1;
+
+       bm_app_type->rId_ble = bm_query_table_column_int(hstmt, BM_APPUSAGE_FIELD_RID_BLE);
+
+       bm_app_type->rId_wifi = bm_query_table_column_int(hstmt, BM_APPUSAGE_FIELD_RID_WIFI);
+
+       bm_app_type->rId_cpu = bm_query_table_column_int(hstmt, BM_APPUSAGE_FIELD_RID_CPU);
+
+       bm_app_type->rId_display = bm_query_table_column_int(hstmt, BM_APPUSAGE_FIELD_RID_DISPLAY);
+
+       bm_app_type->rId_device_network = bm_query_table_column_int(hstmt, BM_APPUSAGE_FIELD_RID_DEV_NTW);
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       bm_app_type->rId_gps = bm_query_table_column_int(hstmt, BM_APPUSAGE_FIELD_RID_GPS);
+
+       bm_app_type->rId_hrm = bm_query_table_column_int(hstmt, BM_APPUSAGE_FIELD_RID_HRM);
+
+       bm_app_type->rId_battery = -1;
+#endif
+       EXIT;
+       return;
+
+}
+
+static int bm_get_record_count(sqlite3 *bm_db_handle, const char *query)
+{
+       ENTER;
+
+       int rc = -1;
+       int ncount = 0;
+       bm_stmt pStmt = NULL;
+
+       if (!query) {
+               _ERR("NULL query\n");
+               return BATTERY_MONITOR_ERROR_QUERY_SYNTAX_ERROR;
+       }
+
+       if (!bm_db_handle) {
+               _ERR("DB is not opened\n");
+               return BATTERY_MONITOR_ERROR_DB_NOT_OPENED;
+       }
+
+       rc = sqlite3_prepare_v2(bm_db_handle, query, strlen(query), &pStmt, NULL);
+
+       if (SQLITE_BUSY == rc) {
+               _ERR("sqlite3_prepare_v2() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (SQLITE_OK != rc) {
+       _ERR("sqlite3_prepare_v2() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       rc = sqlite3_step(pStmt);
+       if (SQLITE_BUSY == rc) {
+               _ERR("sqlite3_step() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (SQLITE_ROW != rc) {
+               _ERR("sqlite3_step() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       ncount = sqlite3_column_int(pStmt, 0);
+
+       _INFO("bm record count [%d]", ncount);
+       sqlite3_finalize(pStmt);
+
+       EXIT;
+       return ncount;
+}
+
+static int bm_check_is_all_table_exists(sqlite3 *bm_db_handle)
+{
+       ENTER;
+
+       int rc = 0;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0,};
+       BM_MEMSET(query, 0, sizeof(query));
+
+       BM_SNPRINTF(query, sizeof(query), "select count(*) from sqlite_master where name in ('%s', '%s', '%s')",
+                       BATTERY_MONITOR_APP_ID_MAP_TABLE, BATTERY_MONITOR_APP_ID_USAGE_TABLE,
+                       BATTERY_MONITOR_RESOURCE_ID_USAGE_TABLE);
+
+       rc = bm_get_record_count(bm_db_handle, query);
+
+       if (rc != BATTERY_MONITOR_TABLE_COUNT)
+               _ERR("Table count is not matched rc=%d\n", rc);
+
+       EXIT;
+       return rc;
+}
+
+static int bm_create_all_tables(sqlite3 *bm_db_handle)
+{
+       ENTER;
+
+       int rc = -1;
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+
+       _INFO("Create all tables - BEGIN");
+
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       BM_MEMSET(query, 0, sizeof(query));
+
+       /* Create the appid map table */
+       BM_SNPRINTF(query, sizeof(query), "select count(*) from sqlite_master where name in ('%s')",
+                                               BATTERY_MONITOR_APP_ID_MAP_TABLE);
+
+       rc = bm_get_record_count(bm_db_handle, query);
+
+       if (rc <= 0) {
+               rc = bm_execute_query(bm_db_handle, APP_ID_MAP_SCHEMA);
+
+               if (rc == SQLITE_BUSY)
+                       return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+
+               BM_RETURN_VAL((SQLITE_OK == rc), {}, BATTERY_MONITOR_ERROR_DB_FAILED,
+                       ("bm_execute_query(bm_db_handle, %s) failed(%d, %s).\n",
+                        APP_ID_MAP_SCHEMA, rc, bm_db_err_msg(bm_db_handle)));
+       }
+
+       /* Create the app based usage table */
+       BM_SNPRINTF(query, sizeof(query), "select count(*) from sqlite_master where name in ('%s')",
+                                               BATTERY_MONITOR_APP_ID_USAGE_TABLE);
+
+       rc = bm_get_record_count(bm_db_handle, query);
+
+       if (rc <= 0) {
+               rc = bm_execute_query(bm_db_handle, APP_ID_USAGE_SCHEMA);
+
+               if (rc == SQLITE_BUSY)
+                       return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+
+               BM_RETURN_VAL((SQLITE_OK == rc), {}, BATTERY_MONITOR_ERROR_DB_FAILED,
+                       ("bm_execute_query(bm_db_handle, %s) failed(%d, %s).\n",
+                        APP_ID_USAGE_SCHEMA, rc, bm_db_err_msg(bm_db_handle)));
+       }
+
+       /* Create the resource based usage table */
+       BM_SNPRINTF(query, sizeof(query), "select count(*) from sqlite_master where name in ('%s')",
+                                               BATTERY_MONITOR_RESOURCE_ID_USAGE_TABLE);
+
+       rc = bm_get_record_count(bm_db_handle, query);
+
+       if (rc <= 0) {
+               rc = bm_execute_query(bm_db_handle, RESOURCE_ID_USAGE_SCHEMA);
+
+               if (rc == SQLITE_BUSY)
+                       return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+
+               BM_RETURN_VAL((SQLITE_OK == rc), {}, BATTERY_MONITOR_ERROR_DB_FAILED,
+                       ("bm_execute_query(bm_db_handle, %s) failed(%d, %s).\n",
+                        RESOURCE_ID_USAGE_SCHEMA, rc, bm_db_err_msg(bm_db_handle)));
+       }
+
+       EXIT;
+       return error_code;
+}
+
+static long int bm_get_time_bias(int period_type)
+{
+       ENTER;
+
+       long int ret = 0;
+       time_t curr_time;
+
+       time(&curr_time);
+
+       ret = curr_time;
+
+       if (period_type == 0) {
+               ret = ret - BM_DURATION_1DAY;
+       } else if (period_type == 1) {
+               ret = ret - BM_DURATION_1WEEK;
+       } else {
+               _ERR("Invalid value for period [%d]", period_type);
+               ret = 0;
+       }
+
+       EXIT;
+       return ret;
+}
+
+static int bm_db_open(void)
+{
+       ENTER;
+
+       int rc = 0;
+       int ret = -1;
+
+       char bm_db_path[256] = {0, };
+       BM_MEMSET(bm_db_path, 0x00, sizeof(bm_db_path));
+
+       BATTERY_MONITOR_GET_DB_PATH(bm_db_path, sizeof(bm_db_path));
+
+       if (g_hBatteryMonitorDB) {
+               _ERR("Battery Monitor database is using in another app.");
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       }
+
+       ret = bm_db_handle_close(g_hBatteryMonitorDB2);
+       if (ret != BATTERY_MONITOR_ERROR_NONE)
+               _DBG("db_util_close(g_hBatteryMonitorDB2) fail ret = %d", ret);
+
+       _DBG("before bm_db_open()");
+//     if (mode == BM_DB_OPEN_READWRITE)
+               rc = db_util_open(bm_db_path, &g_hBatteryMonitorDB, DB_UTIL_REGISTER_HOOK_METHOD);
+//     else if (mode == BM_DB_OPEN_READONLY)
+//     rc = db_util_open_with_options(bm_db_path, &g_hBatteryMonitorDB, SQLITE_OPEN_READONLY, NULL);
+//     else
+//             return _BATTERY_MONITOR_ERROR_DB_NOT_OPENED;
+       _DBG("after bm_db_open() sqlite_rc = %d", rc);
+
+       if (rc == SQLITE_PERM || bm_db_err_code(g_hBatteryMonitorDB) == SQLITE_PERM) {
+               _ERR("Battery Monitor permission denied");
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+
+       if (rc == SQLITE_BUSY) {
+               _ERR("busy handler fail.");
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       }
+
+       if (rc != SQLITE_OK) {
+               _ERR("The database isn't connected.");
+               return BATTERY_MONITOR_ERROR_DB_NOT_OPENED;
+       }
+
+       rc = bm_check_is_all_table_exists(g_hBatteryMonitorDB);
+
+       if (rc < 0) {
+               _ERR("bm_check_is_all_table_exists rc=[%d]", rc);
+               return rc;
+       } else if (rc == BATTERY_MONITOR_TABLE_COUNT) {
+               _INFO("Tables OK");
+       } else {
+               int ret = bm_create_all_tables(g_hBatteryMonitorDB);
+               if (ret != BATTERY_MONITOR_ERROR_NONE) {
+                       _ERR("bm_create_all_tables fail ret=[%d]", ret);
+                       return ret;
+               }
+       }
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+static int bm_db_close(void)
+{
+       ENTER;
+
+       int ret = -1;
+
+       ret = bm_db_handle_close(g_hBatteryMonitorDB);
+       if (ret != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("db_util_close(g_hBatteryMonitorDB) fail ret = %d", ret);
+               g_hBatteryMonitorDB2 = g_hBatteryMonitorDB;
+       }
+
+       g_hBatteryMonitorDB = NULL;
+
+       EXIT;
+       return ret;
+}
+
+int bm_get_appint_by_app_name(sqlite3 *bm_db_handle, const char *AppId)
+{
+       ENTER;
+
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       int rc = -1;
+       int ncount = 0;
+       bm_stmt pStmt = NULL;
+
+       BM_RETURN_VAL((bm_db_handle != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((AppId != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("AppId is NULL."));
+
+       BM_MEMSET(query, 0x00, sizeof(query));
+       BM_SNPRINTF(query, sizeof(query), "SELECT AppId FROM %s WHERE AppName='%s'", BATTERY_MONITOR_APP_ID_MAP_TABLE, AppId);
+
+       rc = sqlite3_prepare_v2(bm_db_handle, query, strlen(query), &pStmt, NULL);
+
+       if (SQLITE_BUSY == rc) {
+               _ERR("sqlite3_prepare_v2() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (SQLITE_OK != rc) {
+               _ERR("sqlite3_prepare_v2() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       rc = sqlite3_step(pStmt);
+       if (SQLITE_BUSY == rc) {
+               _ERR("sqlite3_step() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (SQLITE_ROW != rc) {
+               _ERR("sqlite3_step() failed(%d, %s).", rc, bm_db_err_msg(bm_db_handle));
+               sqlite3_finalize(pStmt);
+               return BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       ncount = sqlite3_column_int(pStmt, 1);
+
+       _INFO("bm appint for appname [%d]", ncount);
+       sqlite3_finalize(pStmt);
+
+       EXIT;
+       return ncount;
+}
+
+static gboolean app_name_check_duplicated(sqlite3 *bm_db_handle, const char *AppId)
+{
+       ENTER;
+
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       int count = 0;
+
+       BM_RETURN_VAL((bm_db_handle != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((AppId != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("AppId is NULL."));
+       BM_MEMSET(query, 0x00, sizeof(query));
+
+       BM_SNPRINTF(query, sizeof(query), "SELECT COUNT(*) FROM %s WHERE AppName='%s'", BATTERY_MONITOR_APP_ID_MAP_TABLE, AppId);
+
+       count = bm_get_record_count(bm_db_handle, query);
+       if (count > 0) {
+               _INFO("query=[%s]", query);
+               return true;
+       }
+
+       EXIT;
+       return false;
+}
+
+static int bm_appid_usage_insert_to_db(sqlite3 *bm_db_handle, appid_usage_s *bm_app_type)
+{
+       ENTER;
+
+       int rc = 0;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       bm_stmt hstmt = NULL;
+
+       BM_RETURN_VAL((bm_db_handle != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((bm_app_type != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("The battery monitor handle is NULL"));
+
+       /* check mandatory field(app id)*/
+       if (!bm_app_type->AppId)
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+
+       BM_MEMSET(query, 0x00, sizeof(query));
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       BM_SNPRINTF(query, sizeof(query), "INSERT INTO %s( AppId, log_time, rId_ble, rId_wifi, rId_cpu, rId_display, rId_device_network, rId_gps, rId_hrm, rId_battery ) values "
+                       "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", BATTERY_MONITOR_APP_ID_USAGE_TABLE);
+#else
+       BM_SNPRINTF(query, sizeof(query), "INSERT INTO %s( AppId, log_time, rId_ble, rId_wifi, rId_cpu, rId_display, rId_device_network) values "
+                       "(?, ?, ?, ?, ?, ?, ?)", BATTERY_MONITOR_APP_ID_USAGE_TABLE);
+#endif
+
+       hstmt = bm_prepare_query(bm_db_handle, query);
+
+       if (bm_db_err_code(bm_db_handle) == SQLITE_PERM) {
+               _ERR("Access failed(%s)", bm_db_err_msg(bm_db_handle));
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       } else if (bm_db_err_code(bm_db_handle) == SQLITE_BUSY) {
+               _ERR("Database Busy(%s)", bm_db_err_msg(bm_db_handle));
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       }
+
+       BM_RETURN_VAL((hstmt != NULL), {}, BATTERY_MONITOR_ERROR_DB_FAILED, ("bm_prepare_query() failed(%s).\n", bm_db_err_msg(bm_db_handle)));
+
+       bm_appid_usage_convert_to_sql(bm_app_type, hstmt, query);
+
+       rc = bm_query_step(hstmt);
+       if (rc == SQLITE_BUSY) {
+               _ERR("bm_db_query_step() failed(%d, %s)", rc, bm_db_err_msg(bm_db_handle));
+               error_code = BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (rc != SQLITE_DONE) {
+               _ERR("bm_db_query_step() failed(%d, %s)", rc, bm_db_err_msg(bm_db_handle));
+               error_code = BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       rc = bm_query_finalize(hstmt);
+       BM_RETURN_VAL((rc == BATTERY_MONITOR_ERROR_NONE), {}, rc, ("finalize error"));
+       hstmt = NULL;
+
+       EXIT;
+       return error_code;
+}
+
+static int bm_resourceid_usage_insert_to_db(sqlite3 *bm_db_handle, resourceid_usage_s *bm_resource_type)
+{
+       ENTER;
+
+       int rc = 0;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       bm_stmt hstmt = NULL;
+
+       BM_RETURN_VAL((bm_db_handle != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((bm_resource_type != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("The battery monitor handle is NULL"));
+
+       /* check mandatory field(Resource id)*/
+       if (!bm_resource_type->ResourceId)
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+
+       BM_MEMSET(query, 0x00, sizeof(query));
+
+       BM_SNPRINTF(query, sizeof(query), "INSERT INTO %s( ResourceId, log_time, usage ) values " "(?, ?, ?)", BATTERY_MONITOR_RESOURCE_ID_USAGE_TABLE);
+
+       hstmt = bm_prepare_query(bm_db_handle, query);
+
+       if (bm_db_err_code(bm_db_handle) == SQLITE_PERM) {
+               _ERR("Access failed(%s)", bm_db_err_msg(bm_db_handle));
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       } else if (bm_db_err_code(bm_db_handle) == SQLITE_BUSY) {
+               _ERR("Database Busy(%s)", bm_db_err_msg(bm_db_handle));
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       }
+
+       BM_RETURN_VAL((hstmt != NULL), {}, BATTERY_MONITOR_ERROR_DB_FAILED, ("bm_prepare_query() failed(%s).\n", bm_db_err_msg(bm_db_handle)));
+
+       bm_resourceid_usage_convert_to_sql(bm_resource_type, hstmt, query);
+
+       rc = bm_query_step(hstmt);
+       if (rc == SQLITE_BUSY) {
+               _ERR("bm_db_query_step() failed(%d, %s)", rc, bm_db_err_msg(bm_db_handle));
+               error_code = BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (rc != SQLITE_DONE) {
+               _ERR("bm_db_query_step() failed(%d, %s)", rc, bm_db_err_msg(bm_db_handle));
+               error_code = BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       rc = bm_query_finalize(hstmt);
+       BM_RETURN_VAL((rc == BATTERY_MONITOR_ERROR_NONE), {}, rc, ("finalize error"));
+       hstmt = NULL;
+
+       EXIT;
+       return error_code;
+}
+
+int bm_appid_map_insert_to_db(sqlite3 *bm_db_handle, appid_map_s *bm_appid_map_type)
+{
+       ENTER;
+
+       int rc = 0;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       bm_stmt hstmt = NULL;
+       bool to_insert = false;
+
+       BM_RETURN_VAL((bm_db_handle != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((bm_appid_map_type != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("The battery monitor handle is NULL"));
+
+       /* check mandatory field(app id)*/
+       if (!bm_appid_map_type->AppName)
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+
+       to_insert = app_name_check_duplicated(bm_db_handle, bm_appid_map_type->AppName);
+       if (to_insert)
+               return BATTERY_MONITOR_ERROR_DUPLICATED;
+
+       /* The AppId integer value should be auto increment */
+       BM_MEMSET(query, 0x00, sizeof(query));
+       BM_SNPRINTF(query, sizeof(query), "INSERT INTO %s( AppName, AppId ) values "
+                       "(?, ?)", BATTERY_MONITOR_APP_ID_MAP_TABLE);
+
+       hstmt = bm_prepare_query(bm_db_handle, query);
+
+       if (bm_db_err_code(bm_db_handle) == SQLITE_PERM) {
+               _ERR("Access failed(%s)", bm_db_err_msg(bm_db_handle));
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       } else if (bm_db_err_code(bm_db_handle) == SQLITE_BUSY) {
+               _ERR("Database Busy(%s)", bm_db_err_msg(bm_db_handle));
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       }
+
+       BM_RETURN_VAL((hstmt != NULL), {}, BATTERY_MONITOR_ERROR_DB_FAILED, ("bm_prepare_query() failed(%s).\n", bm_db_err_msg(bm_db_handle)));
+
+       bm_appid_map_usage_convert_to_sql(bm_appid_map_type, hstmt, query);
+
+       rc = bm_query_step(hstmt);
+       if (rc == SQLITE_BUSY) {
+               _ERR("bm_db_query_step() failed(%d, %s)", rc, bm_db_err_msg(bm_db_handle));
+               error_code = BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (rc != SQLITE_DONE) {
+               _ERR("bm_db_query_step() failed(%d, %s)", rc, bm_db_err_msg(bm_db_handle));
+               error_code = BATTERY_MONITOR_ERROR_DB_FAILED;
+       }
+
+       rc = bm_query_finalize(hstmt);
+       BM_RETURN_VAL((rc == BATTERY_MONITOR_ERROR_NONE), {}, rc, ("finalize error"));
+       hstmt = NULL;
+
+       EXIT;
+       return error_code;
+}
+
+static appid_usage_s* bm_query_usage_by_appid(sqlite3 *bm_db_handle, const char *app_id, int *error_code, int period_type)
+{
+       ENTER;
+
+       long int duration  = 0;
+       duration = bm_get_time_bias(period_type);
+
+       if (duration == 0) {
+               _ERR("Invalid period_type [%d]", period_type);
+               return NULL;
+       }
+
+       _DBG("Value for duration is [%ld]", duration);
+
+       bm_stmt hstmt = NULL;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       int rc = 0;
+       *error_code = BATTERY_MONITOR_ERROR_NONE;
+
+       BM_RETURN_VAL((app_id != NULL), { *error_code = BATTERY_MONITOR_ERROR_INVALID_PARAMETER; },
+                                               NULL, ("APP ID IS NULL"));
+
+       BM_RETURN_VAL((bm_db_handle != NULL), { *error_code = BATTERY_MONITOR_ERROR_DB_NOT_OPENED; },
+                                               NULL, ("The database isn't connected."));
+
+       BM_MEMSET(query, 0x00, BATTERY_MONITOR_SQL_LEN_MAX);
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       BM_SNPRINTF(query, sizeof(query), "SELECT AppId, sum(rId_ble), sum(rId_wifi), sum(rId_cpu), \
+               sum(rId_display), sum(rId_device_network), sum(rId_gps), sum(rId_hrm) FROM %s WHERE \
+               AppId = '%s' AND log_time >= %ld", BATTERY_MONITOR_APP_ID_USAGE_TABLE, app_id, duration);
+#else
+       BM_SNPRINTF(query, sizeof(query), "SELECT AppId, sum(rId_ble), sum(rId_wifi), sum(rId_cpu), \
+               sum(rId_display), sum(rId_device_network) FROM %s WHERE \
+               AppId = '%s' AND log_time >= %ld", BATTERY_MONITOR_APP_ID_USAGE_TABLE, app_id, duration);
+#endif
+
+       hstmt = bm_prepare_query(bm_db_handle, query);
+
+       if (bm_db_err_code(bm_db_handle) == SQLITE_PERM) {
+               _ERR("Access failed(%s)", bm_db_err_msg(bm_db_handle));
+               *error_code = BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+               return NULL;
+       }
+
+       appid_usage_s *bm_app_type = NULL;
+
+       rc = bm_query_step(hstmt);
+       BM_CATCH_ERROR_P(rc == SQLITE_ROW, {}, BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND,
+                               ("The record isn't found.(%s)\n", app_id));
+
+       bm_app_type = (appid_usage_s *)calloc(1, sizeof(appid_usage_s));
+       if (bm_app_type == NULL) {
+               _ERR("memory allocation failed");
+               if (hstmt != NULL) {
+                       rc = bm_query_finalize(hstmt);
+                       BM_RETURN_VAL((rc == BATTERY_MONITOR_ERROR_NONE), { *error_code = rc; },
+                                               NULL, ("finalize error"));
+                       hstmt = NULL;
+               }
+               *error_code = BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+               return NULL;
+       }
+
+       bm_convert_column_to_appid_usage(hstmt, bm_app_type);
+
+       rc = bm_query_finalize(hstmt);
+       BM_CATCH_ERROR_P((rc == BATTERY_MONITOR_ERROR_NONE), {}, rc, ("finalize error"));
+       hstmt = NULL;
+
+       *error_code = BATTERY_MONITOR_ERROR_NONE;
+
+CATCH:
+       if (hstmt != NULL) {
+               rc = bm_query_finalize(hstmt);
+               if (rc != BATTERY_MONITOR_ERROR_NONE) {
+                       *error_code = rc;
+                       _ERR("finalize error");
+               }
+               hstmt = NULL;
+       }
+
+       if ((*error_code != BATTERY_MONITOR_ERROR_NONE) && bm_app_type) {
+               BM_FREE(bm_app_type);
+               bm_app_type = NULL;
+       }
+
+       if ((*error_code == BATTERY_MONITOR_ERROR_NONE) && bm_app_type != NULL) {
+               _INFO("Returning appid usage");
+               return bm_app_type;
+       }
+
+       EXIT;
+       return NULL;
+}
+
+static resourceid_usage_s* bm_query_usage_by_resourceid(sqlite3 *bm_db_handle, const char *resource_id, int *error_code, int period_type)
+{
+       ENTER;
+
+       long int duration  = 0;
+       duration = bm_get_time_bias(period_type);
+
+       if (duration == 0) {
+               _ERR("Invalid period_type [%d]", period_type);
+               return NULL;
+       }
+
+       _DBG("Value for duration is [%ld]", duration);
+
+       bm_stmt hstmt = NULL;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       int rc = 0;
+       *error_code = BATTERY_MONITOR_ERROR_NONE;
+
+       BM_RETURN_VAL((resource_id != NULL), { *error_code = BATTERY_MONITOR_ERROR_INVALID_PARAMETER; },
+                                       NULL, ("RESOURCE ID IS NULL"));
+
+       BM_RETURN_VAL((bm_db_handle != NULL), { *error_code = BATTERY_MONITOR_ERROR_DB_NOT_OPENED; },
+                                       NULL, ("The database isn't connected."));
+
+       BM_MEMSET(query, 0x00, BATTERY_MONITOR_SQL_LEN_MAX);
+
+       BM_SNPRINTF(query, sizeof(query), "SELECT ResourceId, sum(usage) FROM %s WHERE ResourceId = '%s' \
+                       AND log_time >= %ld", BATTERY_MONITOR_RESOURCE_ID_USAGE_TABLE, resource_id, duration);
+
+       hstmt = bm_prepare_query(bm_db_handle, query);
+
+       if (bm_db_err_code(bm_db_handle) == SQLITE_PERM) {
+               _ERR("Access failed(%s)", bm_db_err_msg(bm_db_handle));
+               *error_code = BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+               return NULL;
+       }
+
+       resourceid_usage_s *bm_resource_type = NULL;
+
+       rc = bm_query_step(hstmt);
+       BM_CATCH_ERROR_P(rc == SQLITE_ROW, {}, BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND, ("The record isn't found.(%s)\n", resource_id));
+
+       bm_resource_type = (resourceid_usage_s *)calloc(1, sizeof(resourceid_usage_s));
+       if (bm_resource_type == NULL) {
+               _ERR("memory allocation failed");
+               if (hstmt != NULL) {
+                       rc = bm_query_finalize(hstmt);
+                       BM_RETURN_VAL((rc == BATTERY_MONITOR_ERROR_NONE), { *error_code = rc; }, NULL, ("finalize error"));
+                       hstmt = NULL;
+               }
+               *error_code = BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+               return NULL;
+       }
+
+       bm_convert_column_to_resourceid_usage(hstmt, bm_resource_type);
+
+       rc = bm_query_finalize(hstmt);
+       BM_CATCH_ERROR_P((rc == BATTERY_MONITOR_ERROR_NONE), {}, rc, ("finalize error"));
+       hstmt = NULL;
+
+       *error_code = BATTERY_MONITOR_ERROR_NONE;
+
+CATCH:
+       if (hstmt != NULL) {
+               rc = bm_query_finalize(hstmt);
+               if (rc != BATTERY_MONITOR_ERROR_NONE) {
+                       *error_code = rc;
+                       _ERR("finalize error");
+               }
+               hstmt = NULL;
+       }
+
+       if ((*error_code != BATTERY_MONITOR_ERROR_NONE) && bm_resource_type) {
+               BM_FREE(bm_resource_type);
+               bm_resource_type = NULL;
+       }
+
+       if ((*error_code == BATTERY_MONITOR_ERROR_NONE) && bm_resource_type != NULL) {
+               _INFO("Returning appid usage");
+               return bm_resource_type;
+       }
+
+       EXIT;
+       return NULL;
+}
+
+static int bm_delete_table(sqlite3 *bm_db_handle, bm_stmt *phstmt, int num_app_id, const char *app_id, const char* table)
+{
+       ENTER;
+
+       _INFO("bm_delete_table start - table[%s]", table);
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       int binding_count = 1;
+       int rc = 0;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+
+       bm_stmt hstmt = *phstmt;
+
+       BM_RETURN_VAL((bm_db_handle != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((table != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("table is null!"));
+
+       if ((g_strcmp0(table, BATTERY_MONITOR_APP_ID_USAGE_TABLE) == 0))
+               BM_SNPRINTF(query, sizeof(query), "DELETE FROM %s WHERE AppId = ?", table);
+       else if (g_strcmp0(table, BATTERY_MONITOR_APP_ID_MAP_TABLE) == 0)
+               BM_SNPRINTF(query, sizeof(query), "DELETE FROM %s WHERE AppName = ?", table);
+
+       hstmt = bm_prepare_query(bm_db_handle, query);
+
+       bm_query_bind_text(hstmt, binding_count++, app_id);
+
+       if (hstmt == NULL) {
+               _ERR("bm_svc_query_prepare(%s) failed(%s).\n", query, bm_db_err_msg(bm_db_handle));
+               error_code = BATTERY_MONITOR_ERROR_DB_FAILED;
+               goto END;
+       }
+
+       rc = bm_query_step(hstmt);
+       if (rc != SQLITE_DONE) {
+               _ERR("The record isn't found\n");
+               error_code = BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND;
+               goto END;
+       }
+
+       rc = bm_query_finalize(hstmt);
+       if (rc != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("finalize error");
+               error_code = rc;
+               goto END;
+       }
+
+       hstmt =  NULL;
+       _INFO("bm_delete_table end");
+END:
+
+       EXIT;
+       return error_code;
+}
+
+static int bm_delete_table_by_app_id(sqlite3 *bm_db_handle, const char *AppId)
+{
+       ENTER;
+
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       bm_stmt hstmt = NULL;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       int rc = 0;
+       int count = -1;
+       int ret_transaction = 0;
+       bool is_success = FALSE;
+       int num_AppId = -1;
+
+       BM_RETURN_VAL((bm_db_handle != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((AppId != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("The database isn't connected."));
+
+       /* Check requested ID to delete */
+       BM_SNPRINTF(query, sizeof(query), "SELECT COUNT(*) FROM %s WHERE AppName = '%s'", BATTERY_MONITOR_APP_ID_MAP_TABLE, AppId);
+
+       count = bm_get_record_count(bm_db_handle, query);
+
+       if (bm_db_err_code(bm_db_handle) == SQLITE_PERM) {
+               _ERR("Access failed(%s)", bm_db_err_msg(bm_db_handle));
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+
+       if (count <= 0) {
+               BM_SLOGE("App ID(%s) is not exist. count(%d)\n", AppId, count);
+               return BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND;
+       }
+
+       /* transaction control required */
+       ret_transaction = bm_begin_transaction(bm_db_handle);
+
+       if (ret_transaction == BATTERY_MONITOR_ERROR_DATABASE_BUSY) {
+               _ERR("database busy(%s)", bm_db_err_msg(bm_db_handle));
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (ret_transaction != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("bm_delete:bm_begin_transaction fail %d\n", ret_transaction);
+               return ret_transaction;
+       }
+
+       /*delete AppId Usage table*/
+       error_code = bm_delete_table(bm_db_handle, &hstmt, num_AppId, AppId, BATTERY_MONITOR_APP_ID_USAGE_TABLE);
+       if ((error_code == BATTERY_MONITOR_ERROR_DB_FAILED) || (error_code == BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND)) {
+               _ERR("bm appid_usage deletion failed - db error[%d]", error_code);
+               goto CATCH;
+       } else if (error_code != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("bm appid_usage deletion failed - error[%d]", error_code);
+               return error_code;
+       }
+
+       /*delete AppId Map table*/
+       error_code = bm_delete_table(bm_db_handle, &hstmt, num_AppId, AppId, BATTERY_MONITOR_APP_ID_MAP_TABLE);
+       if ((error_code == BATTERY_MONITOR_ERROR_DB_FAILED) || (error_code == BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND)) {
+               _ERR("bm appid_map deletion failed - db error[%d]", error_code);
+               goto CATCH;
+       } else if (error_code != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("bm appid_map deletion failed - error[%d]", error_code);
+               return error_code;
+       }
+       is_success = TRUE;
+
+CATCH:
+       if (hstmt != NULL) {
+               rc = bm_query_finalize(hstmt);
+               BM_RETURN_VAL((rc == BATTERY_MONITOR_ERROR_NONE), {}, rc, ("finalize error"));
+               hstmt = NULL;
+       }
+
+       ret_transaction = bm_end_transaction(bm_db_handle, is_success);
+
+       if (ret_transaction != BATTERY_MONITOR_ERROR_NONE)
+               _ERR("bm_svc_delete:bm_svc_end_transaction fail %d, is_success=%d\n", ret_transaction, is_success);
+
+       EXIT;
+       return error_code;
+}
+
+static int bm_delete_table_by_time_interval(sqlite3 *bm_db_handle, const char* table)
+{
+       ENTER;
+
+       _INFO("bm_delete_table start - table[%s]", table);
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       int rc = 0;
+       char query[BATTERY_MONITOR_SQL_LEN_MAX] = {0, };
+       long int duration = bm_get_time_bias(1);
+
+       bm_stmt hstmt = NULL;
+
+       BM_RETURN_VAL((bm_db_handle != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((table != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("table is null!"));
+
+       if ((g_strcmp0(table, BATTERY_MONITOR_APP_ID_USAGE_TABLE) == 0))
+               BM_SNPRINTF(query, sizeof(query), "DELETE FROM %s WHERE log_time <= %ld", table, duration);
+       else if (g_strcmp0(table, BATTERY_MONITOR_RESOURCE_ID_USAGE_TABLE) == 0)
+               BM_SNPRINTF(query, sizeof(query), "DELETE FROM %s WHERE log_time <= %ld", table, duration);
+
+       hstmt = bm_prepare_query(bm_db_handle, query);
+
+       if (hstmt == NULL) {
+               _ERR("bm_svc_query_prepare(%s) failed(%s).\n", query, bm_db_err_msg(bm_db_handle));
+               error_code = BATTERY_MONITOR_ERROR_DB_FAILED;
+               goto END;
+       }
+
+       rc = bm_query_step(hstmt);
+       if (rc != SQLITE_DONE) {
+               _ERR("The record isn't found\n");
+               error_code = BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND;
+               goto END;
+       }
+
+       rc = bm_query_finalize(hstmt);
+       if (rc != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("finalize error");
+               error_code = rc;
+               goto END;
+       }
+
+       hstmt =  NULL;
+       EXIT;
+END:
+
+       return error_code;
+}
+
+/*
+Manager Functions
+>-------To be called by bm-engine & bm-server.
+>-------Only these will be exposed for other files to use.
+*/
+
+int bm_server_resource_usage_insert_to_db(resourceid_usage_s *bm_resource_type)
+{
+       ENTER;
+
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       int ret_transaction = 0;
+
+       BM_RETURN_VAL((g_hBatteryMonitorDB != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((bm_resource_type != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("The Battery Monitor Handle is NULL"));
+
+       pthread_mutex_lock(&battery_monitor_mutex);
+
+       /* Transaction Control Required */
+       ret_transaction = bm_begin_transaction(g_hBatteryMonitorDB);
+
+       if (bm_db_err_code(g_hBatteryMonitorDB) == SQLITE_PERM) {
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               _ERR("Access failed(%s)", bm_db_err_msg(g_hBatteryMonitorDB));
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+
+       if (ret_transaction == BATTERY_MONITOR_ERROR_DATABASE_BUSY) {
+               _ERR("Resource Usage insert:bm_begin_transaction fail %d\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (ret_transaction != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("Resource Usage insert:bm_begin_transaction fail %d\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return ret_transaction;
+       }
+
+       error_code = bm_resourceid_usage_insert_to_db(g_hBatteryMonitorDB, bm_resource_type);
+
+       if (error_code != BATTERY_MONITOR_ERROR_NONE) {
+               ret_transaction = bm_end_transaction(g_hBatteryMonitorDB, false);
+               _ERR("INSERT resource usage fail, rollback insert query(%d)!!!!\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return error_code;
+       }
+
+       pthread_mutex_unlock(&battery_monitor_mutex);
+       bm_end_transaction(g_hBatteryMonitorDB, true);
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int bm_server_app_usage_insert_to_db(appid_usage_s *bm_app_type)
+{
+       ENTER;
+
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       int ret_transaction = 0;
+
+       BM_RETURN_VAL((g_hBatteryMonitorDB != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+       BM_RETURN_VAL((bm_app_type != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("The Battery Monitor Handle is NULL"));
+
+       pthread_mutex_lock(&battery_monitor_mutex);
+
+       /* Transaction Control Required */
+       ret_transaction = bm_begin_transaction(g_hBatteryMonitorDB);
+
+       if (bm_db_err_code(g_hBatteryMonitorDB) == SQLITE_PERM) {
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               _ERR("Access failed(%s)", bm_db_err_msg(g_hBatteryMonitorDB));
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+
+       if (ret_transaction == BATTERY_MONITOR_ERROR_DATABASE_BUSY) {
+               _ERR("Resource Usage insert:bm_begin_transaction fail %d\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (ret_transaction != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("Resource Usage insert:bm_begin_transaction fail %d\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return ret_transaction;
+       }
+
+       error_code = bm_appid_usage_insert_to_db(g_hBatteryMonitorDB, bm_app_type);
+
+       if (error_code != BATTERY_MONITOR_ERROR_NONE) {
+               ret_transaction = bm_end_transaction(g_hBatteryMonitorDB, false);
+               _ERR("INSERT resource usage fail, rollback insert query(%d)!!!!\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return error_code;
+       }
+
+       pthread_mutex_unlock(&battery_monitor_mutex);
+       bm_end_transaction(g_hBatteryMonitorDB, true);
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+appid_usage_s *bm_server_query_app_usage_by_appid(const char *app_id, int period_type, int *error_code)
+{
+       ENTER;
+
+       appid_usage_s *bm_app_type = NULL;
+       *error_code = BATTERY_MONITOR_ERROR_NONE;
+
+       BM_RETURN_VAL((g_hBatteryMonitorDB != NULL), { *error_code =  BATTERY_MONITOR_ERROR_DB_NOT_OPENED; }, NULL, ("The database isn't connected."));
+       BM_RETURN_VAL((app_id != NULL), { *error_code = BATTERY_MONITOR_ERROR_INVALID_PARAMETER; }, NULL, ("The Battery Monitor Handle is NULL"));
+
+       bm_app_type = bm_query_usage_by_appid(g_hBatteryMonitorDB, app_id, error_code, period_type);
+
+       EXIT;
+       return bm_app_type;
+}
+
+resourceid_usage_s *bm_server_query_resource_usage_resourceid(const char *resource_id, int period_type, int *error_code)
+{
+       ENTER;
+
+       resourceid_usage_s *bm_resource_type = NULL;
+       *error_code = BATTERY_MONITOR_ERROR_NONE;
+
+       BM_RETURN_VAL((g_hBatteryMonitorDB != NULL), { *error_code = BATTERY_MONITOR_ERROR_DB_NOT_OPENED; }, NULL, ("The database isn't connected."));
+       BM_RETURN_VAL((resource_id != NULL), { *error_code = BATTERY_MONITOR_ERROR_INVALID_PARAMETER; }, NULL, ("The Battery Monitor Handle is NULL"));
+
+       bm_resource_type = bm_query_usage_by_resourceid(g_hBatteryMonitorDB, resource_id, error_code, period_type);
+
+       EXIT;
+       return bm_resource_type;
+}
+
+int bm_server_delete_table_by_appid(const char* app_id)
+{
+       ENTER;
+
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+
+       pthread_mutex_lock(&battery_monitor_mutex);
+
+       BM_RETURN_VAL((app_id != NULL), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, ("Application Id is NULL"));
+       BM_RETURN_VAL((g_hBatteryMonitorDB != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+
+       error_code = bm_delete_table_by_app_id(g_hBatteryMonitorDB, app_id);
+
+       pthread_mutex_unlock(&battery_monitor_mutex);
+
+       EXIT;
+       return error_code;
+}
+
+int bm_server_delete_table_by_time_interval(void)
+{
+       ENTER;
+
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       int ret_transaction = 0;
+
+       BM_RETURN_VAL((g_hBatteryMonitorDB != NULL), {}, BATTERY_MONITOR_ERROR_DB_NOT_OPENED, ("The database isn't connected."));
+
+       pthread_mutex_lock(&battery_monitor_mutex);
+
+       /* Transaction Control Required */
+       ret_transaction = bm_begin_transaction(g_hBatteryMonitorDB);
+
+       if (bm_db_err_code(g_hBatteryMonitorDB) == SQLITE_PERM) {
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               _ERR("Access failed(%s)", bm_db_err_msg(g_hBatteryMonitorDB));
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+
+       if (ret_transaction == BATTERY_MONITOR_ERROR_DATABASE_BUSY) {
+               _ERR("Usage Delete:bm_begin_transaction fail %d\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return BATTERY_MONITOR_ERROR_DATABASE_BUSY;
+       } else if (ret_transaction != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("Usage Delete:bm_begin_transaction fail %d\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return ret_transaction;
+       }
+
+       error_code = bm_delete_table_by_time_interval(g_hBatteryMonitorDB, BATTERY_MONITOR_RESOURCE_ID_USAGE_TABLE);
+
+       if (error_code != BATTERY_MONITOR_ERROR_NONE) {
+               ret_transaction = bm_end_transaction(g_hBatteryMonitorDB, false);
+               _ERR("Delete old resource usage fail, rollback delete query(%d)!!!!\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return error_code;
+       }
+
+       error_code = bm_delete_table_by_time_interval(g_hBatteryMonitorDB, BATTERY_MONITOR_APP_ID_USAGE_TABLE);
+
+       if (error_code != BATTERY_MONITOR_ERROR_NONE) {
+               ret_transaction = bm_end_transaction(g_hBatteryMonitorDB, false);
+               _ERR("Delete old app usage fail, rollback delete query(%d)!!!!\n", ret_transaction);
+               pthread_mutex_unlock(&battery_monitor_mutex);
+               return error_code;
+       }
+
+       pthread_mutex_unlock(&battery_monitor_mutex);
+       bm_end_transaction(g_hBatteryMonitorDB, true);
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int initialize_database(void)
+{
+       ENTER;
+
+       int return_code = BATTERY_MONITOR_ERROR_NONE;
+
+       return_code = bm_db_open();
+       if (return_code != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("Battery Monitor DB Open Error");
+               return -1;
+       }
+
+       EXIT;
+
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int deinitialize_database(void)
+{
+       ENTER;
+
+       int return_code = BATTERY_MONITOR_ERROR_NONE;
+
+       return_code = bm_db_close();
+       if (return_code != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("Battery Monitor DB Open Error");
+               return -1;
+       }
+
+       EXIT;
+
+       return BATTERY_MONITOR_ERROR_NONE;
+}
diff --git a/src/bm_util.c b/src/bm_util.c
new file mode 100644 (file)
index 0000000..ef64f70
--- /dev/null
@@ -0,0 +1,770 @@
+/*
+ * Copyright (c) 2019 Samsung Electronics Co., Ltd. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License")
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <cynara-client.h>
+#include <cynara-session.h>
+#include <cynara-creds-gdbus.h>
+
+#include "bm_util.h"
+#include "bm_common.h"
+
+static cynara *p_cynara;
+
+GDBusErrorEntry bm_svc_errors[] = {
+       {BATTERY_MONITOR_ERROR_NONE, BATTERY_MONITOR_SVC_ERROR_PREFIX".NoError"},
+       {BATTERY_MONITOR_ERROR_OUT_OF_MEMORY, BATTERY_MONITOR_SVC_ERROR_PREFIX".OutOfMemory"},
+       {BATTERY_MONITOR_ERROR_INVALID_PARAMETER, BATTERY_MONITOR_SVC_ERROR_PREFIX".InvalidParameter"},
+       {BATTERY_MONITOR_ERROR_DUPLICATED, BATTERY_MONITOR_SVC_ERROR_PREFIX".Duplicated"},
+       {BATTERY_MONITOR_ERROR_NO_DATA, BATTERY_MONITOR_SVC_ERROR_PREFIX".NoData"},
+       {BATTERY_MONITOR_ERROR_NOT_INITIALIZED, BATTERY_MONITOR_SVC_ERROR_PREFIX".NotInitialized"},
+       {BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND, BATTERY_MONITOR_SVC_ERROR_PREFIX".RecordNotFound"},
+       {BATTERY_MONITOR_ERROR_DB_FAILED, BATTERY_MONITOR_SVC_ERROR_PREFIX".DBFailed"},
+       {BATTERY_MONITOR_ERROR_DB_NOT_OPENED, BATTERY_MONITOR_SVC_ERROR_PREFIX".DBNotOpened"},
+       {BATTERY_MONITOR_ERROR_QUERY_SYNTAX_ERROR, BATTERY_MONITOR_SVC_ERROR_PREFIX".QuerySynTaxError"},
+       {BATTERY_MONITOR_ERROR_ITERATOR_END, BATTERY_MONITOR_SVC_ERROR_PREFIX".IteratorEnd"},
+       {BATTERY_MONITOR_ERROR_NOTI_FAILED, BATTERY_MONITOR_SVC_ERROR_PREFIX".NotiFalied"},
+       {BATTERY_MONITOR_ERROR_PERMISSION_DENIED, BATTERY_MONITOR_SVC_ERROR_PREFIX".PermissionDenied"},
+       {BATTERY_MONITOR_ERROR_NULL_POINTER, BATTERY_MONITOR_SVC_ERROR_PREFIX".NullPointer"},
+       {BATTERY_MONITOR_ERROR_INTERNAL, BATTERY_MONITOR_SVC_ERROR_PREFIX".Internal"},
+       {BATTERY_MONITOR_ERROR_PLUGIN_ADD, BATTERY_MONITOR_SVC_ERROR_PREFIX".PluginAdd"},
+       {BATTERY_MONITOR_ERROR_PLUGIN_AVAILABLE, BATTERY_MONITOR_SVC_ERROR_PREFIX".PluginAvailable"},
+       {BATTERY_MONITOR_ERROR_NOT_SUPPORTED, BATTERY_MONITOR_SVC_ERROR_PREFIX".NotSupported"},
+       {BATTERY_MONITOR_ERROR_DATABASE_BUSY, BATTERY_MONITOR_SVC_ERROR_PREFIX".DatabaseBusy"},
+};
+
+static guint bm_get_client_pid(GDBusMethodInvocation* invoc)
+{
+       const char *name = NULL;
+       name = g_dbus_method_invocation_get_sender(invoc);
+       if (name == NULL) {
+               _ERR("g_dbus_method_invocation_get_sender failed");
+               return -1;
+       }
+
+       _INFO("sender=[%s]", name);
+
+       guint pid = -1;
+       GError *error = NULL;
+       GVariant *_ret;
+
+       _INFO("calling GetConnectionUnixProcessID");
+
+       GDBusConnection* conn = g_dbus_method_invocation_get_connection(invoc);
+       _ret = g_dbus_connection_call_sync(conn,
+                       FREE_DESKTOP_BUS_NAME,
+                       FREE_DESKTOP_OBJECT_PATH,
+                       FREE_DESKTOP_INTERFACE_NAME,
+                       FREE_DESKTOP_METHOD_NAME,
+                       g_variant_new("(s)", name),
+                       NULL,
+                       G_DBUS_CALL_FLAGS_NONE,
+                       -1,
+                       NULL,
+                       &error);
+
+       if (_ret != NULL) {
+               g_variant_get(_ret, "(u)", &pid);
+               g_variant_unref(_ret);
+       }
+
+       _INFO("process Id = [%u]", pid);
+       return pid;
+}
+
+GQuark bm_error_quark(void)
+{
+       static volatile gsize quark_volatile = 0;
+
+       g_dbus_error_register_error_domain(BATTERY_MONITOR_SVC_ERROR_DOMAIN, &quark_volatile,
+                                               bm_svc_errors, G_N_ELEMENTS(bm_svc_errors));
+
+       return (GQuark)quark_volatile;
+}
+
+static int bm_check_privilege_by_cynara(const char *client, const char *session, const char *user,
+                                                               const char *privilege)
+{
+       int ret;
+       char err_buf[128] = {0,};
+
+       ret = cynara_check(p_cynara, client, session, user, privilege);
+       switch (ret) {
+       case CYNARA_API_ACCESS_ALLOWED:
+               _DBG("cynara_check success");
+               return BATTERY_MONITOR_ERROR_NONE;
+       case CYNARA_API_ACCESS_DENIED:
+               _ERR("cynara_check permission deined, privilege=%s, error = CYNARA_API_ACCESS_DENIED",
+                                                                               privilege);
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       default:
+               cynara_strerror(ret, err_buf, sizeof(err_buf));
+               _ERR("cynara_check error : %s, privilege=%s, ret = %d", err_buf, privilege, ret);
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+}
+
+static int bm_get_information_for_cynara_check(GDBusMethodInvocation *invocation, char **client,
+                                                       char **user, char **session)
+{
+       GDBusConnection *gdbus_conn = NULL;
+       char* sender = NULL;
+       int ret = -1;
+
+       //get GDBusConnection
+       gdbus_conn = g_dbus_method_invocation_get_connection(invocation);
+       if (gdbus_conn == NULL) {
+               _ERR("g_dbus_method_invocation_get_connection failed");
+               return -1;
+       }
+
+       //get sender(unique_name)
+       sender = (char*) g_dbus_method_invocation_get_sender(invocation);
+       if (sender == NULL) {
+               _ERR("g_dbus_method_invocation_get_sender failed");
+               return -1;
+       }
+
+       ret = cynara_creds_gdbus_get_user(gdbus_conn, sender, USER_METHOD_DEFAULT, user);
+       if (ret != CYNARA_API_SUCCESS) {
+               _ERR("cynara_creds_gdbus_get_user failed, ret = %d", ret);
+               return -1;
+       }
+
+       ret = cynara_creds_gdbus_get_client(gdbus_conn, sender, CLIENT_METHOD_DEFAULT, client);
+       if (ret != CYNARA_API_SUCCESS) {
+               _ERR("cynara_creds_gdbus_get_client failed, ret = %d", ret);
+               return -1;
+       }
+
+       guint pid = bm_get_client_pid(invocation);
+       _INFO("client Id = [%u]", pid);
+
+       *session = cynara_session_from_pid(pid);
+       if (*session == NULL) {
+               _ERR("cynara_session_from_pid failed");
+               return -1;
+       }
+
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+static int bm_check_privilege(GDBusMethodInvocation *invocation, const char* privilege)
+{
+       int ret = -1;
+       char *client = NULL;
+       char *session = NULL;
+       char *user = NULL;
+
+       ret = bm_get_information_for_cynara_check(invocation, &client, &user, &session);
+       if (ret != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("__get_information_for_cynara_check failed");
+               g_free(client);
+               g_free(user);
+               BM_FREE(session);
+
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+
+       ret = bm_check_privilege_by_cynara(client, session, user, privilege);
+       if (ret != BATTERY_MONITOR_ERROR_NONE) {
+               _ERR("__check_privilege_by_cynara failed, ret = %d", ret);
+               g_free(client);
+               g_free(user);
+               BM_FREE(session);
+
+               return BATTERY_MONITOR_ERROR_PERMISSION_DENIED;
+       }
+
+       g_free(client);
+       g_free(user);
+       BM_FREE(session);
+
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+int bm_check_privilege_battery(GDBusMethodInvocation *invocation)
+{
+       return bm_check_privilege(invocation, BATTERY_MONITOR_PRIVILEGE);
+}
+
+int bm_calc_individual_consumption(int resource_val, int total_consumption)
+{
+       _DBG("resource consumption - [%d], total consumption - [%d]", \
+                       resource_val, total_consumption);
+
+       if (resource_val == 0) {
+               _DBG("no consumption");
+               return 0;
+       }
+
+       return ((resource_val/total_consumption)*100);
+}
+
+GVariant* bm_marshal_serialized_data(const bm_total_consumption_h data)
+{
+       ENTER;
+
+       const bm_total_consumption_h in_data = data;
+       GVariantBuilder builder;
+
+       g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT);
+
+       g_variant_builder_add(&builder, "{sv}", BATTERY_MONITOR_BLE_DATA_ID,
+                                       g_variant_new_int32(in_data->ble_val));
+
+       g_variant_builder_add(&builder, "{sv}", BATTERY_MONITOR_WIFI_DATA_ID,
+                                       g_variant_new_int32(in_data->wifi_val));
+
+       g_variant_builder_add(&builder, "{sv}", BATTERY_MONITOR_CPU_DATA_ID,
+                                       g_variant_new_int32(in_data->cpu_val));
+
+       g_variant_builder_add(&builder, "{sv}", BATTERY_MONITOR_DP_DATA_ID,
+                                       g_variant_new_int32(in_data->dp_val));
+
+       g_variant_builder_add(&builder, "{sv}", BATTERY_MONITOR_DN_DATA_ID,
+                                       g_variant_new_int32(in_data->dn_val));
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       g_variant_builder_add(&builder, "{sv}", BATTERY_MONITOR_GPS_DATA_ID,
+                                       g_variant_new_int32(in_data->gps_val));
+
+       g_variant_builder_add(&builder, "{sv}", BATTERY_MONITOR_HRM_DATA_ID,
+                                       g_variant_new_int32(in_data->hrm_val));
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+       g_variant_builder_add(&builder, "{sv}", BATTERY_MONITOR_BATTERY_DATA_ID,
+                                       g_variant_new_int32(in_data->bat_val));
+
+       EXIT;
+       return g_variant_builder_end(&builder);
+}
+
+const char *bm_get_resource_id_string(gint resource_id)
+{
+       ENTER;
+
+       switch (resource_id) {
+       BM_RESOURCE_ID_TO_STR(BM_PLUGIN_ID_BLE, BATTERY_MONITOR_BLE_DATA_ID)
+       BM_RESOURCE_ID_TO_STR(BM_PLUGIN_ID_WIFI, BATTERY_MONITOR_WIFI_DATA_ID)
+       BM_RESOURCE_ID_TO_STR(BM_PLUGIN_ID_CPU, BATTERY_MONITOR_CPU_DATA_ID)
+       BM_RESOURCE_ID_TO_STR(BM_PLUGIN_ID_DISPLAY, BATTERY_MONITOR_DP_DATA_ID)
+       BM_RESOURCE_ID_TO_STR(BM_PLUGIN_ID_DEVICE_NETWORK, BATTERY_MONITOR_DN_DATA_ID)
+       BM_RESOURCE_ID_TO_STR(BM_PLUGIN_ID_GPS_SENSOR, BATTERY_MONITOR_GPS_DATA_ID)
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       BM_RESOURCE_ID_TO_STR(BM_PLUGIN_ID_HRM_SENSOR, BATTERY_MONITOR_HRM_DATA_ID)
+       BM_RESOURCE_ID_TO_STR(BM_PLUGIN_CONST_BATTERY, BATTERY_MONITOR_BATTERY_DATA_ID)
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+       default:
+               EXIT;
+               return "UNKNOWN RESOURCE-ID";
+       }
+}
+
+void bm_data_free(gpointer data)
+{
+       ENTER;
+
+       if (!data) {
+               _ERR("data handle is null");
+               return;
+       }
+
+       _DBG("delete - app_id(%s)", (char *)data);
+
+       BM_GFREE(data);
+
+       EXIT;
+       return;
+}
+
+void bm_atm_st1_free(gpointer data)
+{
+       ENTER;
+
+       if (!data) {
+               _ERR("data handle is null");
+               return;
+       }
+
+       app_time_map_st1 *node = (app_time_map_st1 *)data;
+
+       _DBG("delete - app_id(%s) app_time_map_st1", node->app_id);
+
+       BM_FREE(node);
+
+       EXIT;
+       return;
+}
+
+void bm_atm_st2_free(gpointer data)
+{
+       ENTER;
+
+       if (!data) {
+               _ERR("data handle is null");
+               return;
+       }
+
+       app_time_map_st2 *node = (app_time_map_st2 *)data;
+
+       _DBG("delete - app_id(%s) of app_time_map_st2", node->app_id);
+
+       BM_FREE(node);
+
+       EXIT;
+       return;
+}
+
+void bm_appid_usage_free(appid_usage_s *data)
+{
+       ENTER;
+
+       if (!data) {
+               _ERR("data handle is null");
+               return;
+       }
+
+       BM_FREE(data);
+
+       EXIT;
+       return;
+}
+
+void bm_resourceid_usage_free(resourceid_usage_s *data)
+{
+       ENTER;
+
+       if (!data) {
+               _ERR("data handle is null");
+               return;
+       }
+
+       BM_FREE(data);
+
+       EXIT;
+       return;
+}
+
+long int bm_get_log_time()
+{
+       ENTER;
+
+       long int ret = 0;
+       time_t curr_time;
+
+       time(&curr_time);
+
+       ret = curr_time;
+
+       EXIT;
+       return ret;
+}
+
+void bm_set_free_atm_st2_list(GSList *atm_list)
+{
+       ENTER;
+
+       if (!atm_list) {
+               _WARN("atm-list is empty");
+               return;
+       }
+
+       GSList *atm_list_iterator = NULL;
+
+       for (atm_list_iterator = atm_list; atm_list_iterator;
+                       atm_list_iterator = atm_list_iterator->next) {
+
+               app_time_map_st2 *atm_node = (app_time_map_st2 *)atm_list_iterator->data;
+               if (atm_node != NULL && !atm_node->app_id)
+                       BM_FREE(atm_node->app_id);
+       }
+
+       /* free atm-list */
+       g_slist_free(atm_list);
+
+       EXIT;
+       return;
+}
+
+void bm_set_free_atm_st1_list(GSList *atm_list)
+{
+       ENTER;
+
+       if (!atm_list) {
+               _WARN("atm-list is empty");
+               return;
+       }
+
+       GSList *atm_list_iterator = NULL;
+
+       for (atm_list_iterator = atm_list; atm_list_iterator;
+                       atm_list_iterator = atm_list_iterator->next) {
+
+               app_time_map_st1 *atm_node = (app_time_map_st1 *)atm_list_iterator->data;
+               if (atm_node != NULL && !atm_node->app_id)
+                       BM_FREE(atm_node->app_id);
+       }
+
+       /* free atm-list */
+       g_slist_free(atm_list);
+
+       EXIT;
+       return;
+}
+
+
+void bm_set_free_ble_data_handle(bm_bluetooth_st *handle)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("data-handle not available");
+               return;
+       }
+
+       GSList *atm_list = NULL, *data_list_iterator = NULL;
+
+       _DBG("inside data_handle");
+
+       if (!handle->bt_data_list) {
+               _ERR("data-list is null");
+               return;
+       }
+
+       _DBG("inside data_list");
+
+       /* iterating over data-list */
+       for (data_list_iterator = handle->bt_data_list; data_list_iterator;
+                               data_list_iterator = data_list_iterator->next) {
+
+               atm_list = ((bm_bluetooth_st *)data_list_iterator->data)->atm_list;
+               if (!atm_list)
+                       continue;
+
+               bm_set_free_atm_st2_list(atm_list);
+       }
+
+       _DBG("after atm_list free");
+
+       /* free data-list */
+       g_slist_free(handle->bt_data_list);
+
+       _DBG("after data_list free");
+
+       /* free data-handle */
+       BM_FREE(handle);
+
+       EXIT;
+       return;
+}
+
+void bm_set_free_wifi_data_handle(bm_wifi_st *handle)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("data-handle not available");
+               return;
+       }
+
+       GSList *atm_list = NULL, *data_list_iterator = NULL;
+
+       _DBG("inside data_handle");
+
+       if (!handle->wifi_data_list) {
+               _ERR("data-list is null");
+               return;
+       }
+
+       _DBG("inside data_list");
+
+       /* iterating over data-list */
+       for (data_list_iterator = handle->wifi_data_list; data_list_iterator;
+                               data_list_iterator = data_list_iterator->next) {
+
+               atm_list = ((bm_wifi_st *)data_list_iterator->data)->atm_list;
+               if (!atm_list)
+                       continue;
+
+               bm_set_free_atm_st2_list(atm_list);
+       }
+
+       _DBG("after atm_list free");
+
+       /* free data-list */
+       g_slist_free(handle->wifi_data_list);
+
+       _DBG("after data_list free");
+
+       /* free data-handle */
+       BM_FREE(handle);
+
+       EXIT;
+       return;
+
+}
+
+void bm_set_free_cpu_data_handle(bm_cpu_st *handle)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("data-handle not available");
+               return;
+       }
+
+       GSList *atm_list = NULL, *data_list_iterator = NULL;
+
+       _DBG("inside data_handle");
+
+       if (!handle->cpu_data_list) {
+               _ERR("data-list is null");
+               return;
+       }
+
+       _DBG("inside data_list");
+
+       /* iterating over data-list */
+       for (data_list_iterator = handle->cpu_data_list; data_list_iterator;
+                               data_list_iterator = data_list_iterator->next) {
+
+               atm_list = ((bm_cpu_st *)data_list_iterator->data)->atm_list;
+               if (!atm_list)
+                       continue;
+
+               bm_set_free_atm_st1_list(atm_list);
+       }
+
+       _DBG("after atm_list free");
+
+       /* free data-list */
+       g_slist_free(handle->cpu_data_list);
+
+       _DBG("after data_list free");
+
+       /* free data-handle */
+       BM_FREE(handle);
+
+       EXIT;
+       return;
+}
+
+void bm_set_free_display_data_handle(bm_display_st *handle)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("data-handle not available");
+               return;
+       }
+
+       GSList *atm_list = NULL, *data_list_iterator = NULL;
+
+       _DBG("inside data_handle");
+
+       if (!handle->display_list) {
+               _ERR("data-list is null");
+               return;
+       }
+
+       _DBG("inside data_list");
+
+       /* iterating over data-list */
+       for (data_list_iterator = handle->display_list; data_list_iterator;
+                               data_list_iterator = data_list_iterator->next) {
+
+               atm_list = ((bm_display_st *)data_list_iterator->data)->atm_list;
+               if (!atm_list)
+                       continue;
+
+               bm_set_free_atm_st1_list(atm_list);
+       }
+
+       _DBG("after atm_list free");
+
+       /* free data-list */
+       g_slist_free(handle->display_list);
+
+       _DBG("after data_list free");
+
+       /* free data-handle */
+       BM_FREE(handle);
+
+       EXIT;
+       return;
+}
+
+void bm_set_free_device_network_data_handle(bm_device_network_st *handle)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("data-handle not available");
+               return;
+       }
+
+       GSList *atm_list = NULL, *data_list_iterator = NULL;
+
+       _DBG("inside data_handle");
+
+       if (!handle->dn_data_list) {
+               _ERR("data-list is null");
+               return;
+       }
+
+       _DBG("inside data_list");
+
+       /* iterating over data-list */
+       for (data_list_iterator = handle->dn_data_list; data_list_iterator;
+                               data_list_iterator = data_list_iterator->next) {
+
+               atm_list = ((bm_device_network_st *)data_list_iterator->data)->atm_list;
+               if (!atm_list)
+                       continue;
+
+               bm_set_free_atm_st2_list(atm_list);
+       }
+
+       _DBG("after atm_list free");
+
+       /* free data-list */
+       g_slist_free(handle->dn_data_list);
+
+       _DBG("after data_list free");
+
+       /* free data-handle */
+       BM_FREE(handle);
+
+       EXIT;
+       return;
+}
+
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+void bm_set_free_gps_sensor_data_handle(bm_gps_st *handle)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("data-handle not available");
+               return;
+       }
+
+       GSList *atm_list = NULL, *data_list_iterator = NULL;
+
+       _DBG("inside data_handle");
+
+       if (!handle->gps_data_list) {
+               _ERR("data-list is null");
+               return;
+       }
+
+       _DBG("inside data_list");
+
+       /* iterating over data-list */
+       for (data_list_iterator = handle->gps_data_list; data_list_iterator;
+                               data_list_iterator = data_list_iterator->next) {
+
+               atm_list = ((bm_gps_st *)data_list_iterator->data)->atm_list;
+               if (!atm_list)
+                       continue;
+
+               bm_set_free_atm_st1_list(atm_list);
+       }
+
+       _DBG("after atm_list free");
+
+       /* free data-list */
+       g_slist_free(handle->gps_data_list);
+
+       _DBG("after data_list free");
+
+       /* free data-handle */
+       BM_FREE(handle);
+
+       EXIT;
+       return;
+}
+
+void bm_set_free_hrm_sensor_data_handle(bm_hrm_sensor_st *handle)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("data-handle not available");
+               return;
+       }
+
+       GSList *atm_list = NULL, *data_list_iterator = NULL;
+
+       _DBG("inside data_handle");
+
+       if (!handle->hrm_data_list) {
+               _ERR("data-list is null");
+               return;
+       }
+
+       _DBG("inside data_list");
+
+       /* iterating over data-list */
+       for (data_list_iterator = handle->hrm_data_list; data_list_iterator;
+                               data_list_iterator = data_list_iterator->next) {
+
+               atm_list = ((bm_hrm_sensor_st *)data_list_iterator->data)->atm_list;
+               if (!atm_list)
+                       continue;
+
+               bm_set_free_atm_st1_list(atm_list);
+       }
+
+       _DBG("after atm_list free");
+
+       /* free data-list */
+       g_slist_free(handle->hrm_data_list);
+
+       _DBG("after data_list free");
+
+       /* free data-handle */
+       BM_FREE(handle);
+
+       EXIT;
+       return;
+}
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+void bm_set_free_data_handles(bm_feature_data_h data_h)
+{
+       ENTER;
+
+       if (!data_h) {
+               _ERR("data handles not available");
+               return;
+       }
+
+       bm_set_free_ble_data_handle(data_h->bm_ble_handle);
+       bm_set_free_wifi_data_handle(data_h->bm_wifi_handle);
+       bm_set_free_cpu_data_handle(data_h->bm_cpu_handle);
+       bm_set_free_display_data_handle(data_h->bm_display_handle);
+       bm_set_free_device_network_data_handle(data_h->bm_dn_handle);
+#ifdef DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN
+       bm_set_free_gps_sensor_data_handle(data_h->bm_gps_handle);
+       bm_set_free_hrm_sensor_data_handle(data_h->bm_hrm_handle);
+#endif /* DISABLE_FEATURE_DATA_FROM_GPS_HRM_PLUGIN */
+
+       BM_FREE(data_h);
+
+       EXIT;
+       return;
+}
+