Initial source code 18/212418/4
authorKichan Kwon <k_c.kwon@samsung.com>
Wed, 21 Aug 2019 08:08:52 +0000 (17:08 +0900)
committerKichan Kwon <k_c.kwon@samsung.com>
Wed, 28 Aug 2019 01:30:04 +0000 (10:30 +0900)
- Bring from devel repo : PR #34

Change-Id: I3b7baa721b4968ff64f85b943bb4f5d041e15751
Signed-off-by: Kichan Kwon <k_c.kwon@samsung.com>
21 files changed:
CMakeLists.txt [new file with mode: 0644]
LICENSE [new file with mode: 0755]
NOTICE [new file with mode: 0755]
capi-battery-monitor-devel.manifest [new file with mode: 0644]
capi-battery-monitor.manifest [new file with mode: 0644]
capi-battery-monitor.pc.in [new file with mode: 0644]
doc/battery_monitor_doc.h [new file with mode: 0755]
include/battery_monitor.h [new file with mode: 0644]
include/battery_monitor_dbg.h [new file with mode: 0644]
include/battery_monitor_internal.h [new file with mode: 0644]
include/battery_monitor_util.h [new file with mode: 0644]
packaging/battery-monitor.xml [new file with mode: 0644]
packaging/capi-battery-monitor.spec [new file with mode: 0644]
src/battery_monitor.c [new file with mode: 0644]
src/battery_monitor_util.c [new file with mode: 0644]
test/CMakeLists.txt [new file with mode: 0644]
test/test_cli_app/CMakeLists.txt [new file with mode: 0644]
test/test_cli_app/include/bmt_utility.h [new file with mode: 0644]
test/test_cli_app/src/bmt_main.c [new file with mode: 0644]
test/test_cli_app/src/bmt_usage.c [new file with mode: 0644]
test/test_cli_app/src/bmt_utility.c [new file with mode: 0644]

diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0d7503f
--- /dev/null
@@ -0,0 +1,76 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT(capi-battery-monitor)
+
+SET(PREFIX ${CMAKE_INSTALL_PREFIX})
+
+SET(INC_DIR include)
+INCLUDE_DIRECTORIES(${INC_DIR})
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(PKGS REQUIRED
+       dlog
+       glib-2.0
+       gio-unix-2.0
+       libtzplatform-config
+       capi-system-info
+)
+
+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")
+
+INCLUDE_DIRECTORIES(${PKGS_INCLUDE_DIRS})
+LINK_DIRECTORIES(${PKGS_LIBRARY_DIRS})
+
+FOREACH(flag ${PKGS_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -fPIC -Wall -Werror")
+SET(LIB_NAME "${PROJECT_NAME}")
+SET(LIB_PREFIX ${CMAKE_INSTALL_PREFIX})
+SET(LIB_DIR "${LIB_PATH}")
+SET(LIB_INCLUDE_DIR "${LIB_PREFIX}/include")
+SET(LIB_PKGCONFIG_DIR "${LIB_PATH}/pkgconfig")
+
+SET(SRCS
+       ./battery-monitor-stub.c
+       src/battery_monitor.c
+       src/battery_monitor_util.c
+)
+
+INCLUDE_DIRECTORIES(${INC_DIR})
+INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/include)
+
+ADD_LIBRARY(${LIB_NAME} SHARED ${SRCS})
+TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${PKGS_LDFLAGS})
+
+SET_TARGET_PROPERTIES(${LIB_NAME}
+       PROPERTIES
+       VERSION ${FULLVER}
+       SOVERSION ${MAJORVER}
+       CLEAN_DIRECT_OUTPUT 1
+)
+
+INSTALL(TARGETS ${LIB_NAME} DESTINATION ${LIB_DIR})
+INSTALL(
+       DIRECTORY ${INC_DIR}/ DESTINATION ${LIB_INCLUDE_DIR}
+       FILES_MATCHING
+       PATTERN "${INC_DIR}/battery_monitor.h"
+)
+
+SET(PC_NAME ${LIB_NAME})
+SET(PC_REQUIRED ${pc_dependents})
+SET(PC_LDFLAGS -l${LIB_NAME})
+
+CONFIGURE_FILE(
+       ${LIB_NAME}.pc.in
+       ${CMAKE_CURRENT_SOURCE_DIR}/${LIB_NAME}.pc
+       @ONLY
+)
+INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${LIB_NAME}.pc DESTINATION ${LIB_PKGCONFIG_DIR})
+
+ADD_SUBDIRECTORY(test)
diff --git a/LICENSE b/LICENSE
new file mode 100755 (executable)
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+                                 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 100755 (executable)
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/capi-battery-monitor-devel.manifest b/capi-battery-monitor-devel.manifest
new file mode 100644 (file)
index 0000000..81ace0c
--- /dev/null
@@ -0,0 +1,6 @@
+<manifest>
+       <request>
+               <domain name="_"/>
+       </request>
+</manifest>
+
diff --git a/capi-battery-monitor.manifest b/capi-battery-monitor.manifest
new file mode 100644 (file)
index 0000000..81ace0c
--- /dev/null
@@ -0,0 +1,6 @@
+<manifest>
+       <request>
+               <domain name="_"/>
+       </request>
+</manifest>
+
diff --git a/capi-battery-monitor.pc.in b/capi-battery-monitor.pc.in
new file mode 100644 (file)
index 0000000..328ec23
--- /dev/null
@@ -0,0 +1,15 @@
+# Package Information for pkg-config
+
+prefix=@PREFIX@
+exec_prefix=/usr
+libdir=@LIB_INSTALL_DIR@
+includedir=@INCLUDE_INSTALL_DIR@
+
+Name: @PC_NAME@
+Description: @PACKAGE_DESCRIPTION@
+Version: @VERSION@
+Requires: @PC_REQUIRED@
+Libs: -L${libdir} @PC_LDFLAGS@
+Cflags: -I${includedir}
+
+
diff --git a/doc/battery_monitor_doc.h b/doc/battery_monitor_doc.h
new file mode 100755 (executable)
index 0000000..eef5d4e
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * 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 __TIZEN_SERVICE_BATTERY_MONITOR_DOC_H__
+#define __TIZEN_SERVICE_BATTERY_MONITOR_DOC_H__
+
+/**
+ * @ingroup  CAPI_BATTERY_MONITOR_FRAMEWORK
+ * @defgroup CAPI_BATTERY_MONITOR_MODULE Battery Monitor
+ *
+ * @brief    The API's provide per resource battery consumption by the application.
+ *
+ * @section CAPI_BATTERY_MONITOR_MODULE Header
+ * \#include <battery_monitor.h>
+ *
+ * @section CAPI_BATTERY_MONITOR_MODULE Overview
+ * Battery consumption by a device does not only comprises power consumed by CPU,
+ * but it also includes power consumed by other components like - WiFi, Bt, Display, Mobile radio etc.
+ * The user is normally unaware of power consumed by these components & hence when battery drains out,
+ * user treats it as abnormal behaviour of device.
+ *
+ * Under these circumstances, user takes immediate action like killing all power hungry applications,
+ * use minimal display brightness, enable night mode in day time, shutting down some sensors, disabling
+ * background data for applications to restrict power usage & in the worst case - uninstall the application.
+ *
+ * User's decision making at such time is greatly influenced by the accuracy of battery consumption estimation
+ * and statistics provided to him.
+ *
+ * With this battery-monitor framework, power consumed by each & every application is determined along with the
+ * power consumed by individual resources which are used by the application at the time of running.
+ *
+ * The API's provide the following functionality:
+ * - battery consumption in percent for specific resource from available data.
+ * - battery consumption in percent for all resources used by app_id.
+ * - battery consumption in percent by an app-id for a specific resource.
+ * - total battery usage in percent by an app-id for certain time duration.
+ * - battery consumption in percent usage by a resource for certain time duration.
+ *
+ * @section CAPI_BATTERY_MONITOR_MODULE_FEATURE Related Features
+ * The API's defined are related with the following features:\n
+ * - http://tizen.org/feature/battery\n
+ *
+ * It is recommended to design applications with regard to features, for reliability.\n
+ *
+ * To ensure your application is only running on the device with specific features, please define the features in your manifest file using the manifest editor in the SDK.\n
+ *
+ * More details on using features in your application can be found in the <a href="https://developer.tizen.org/development/getting-started/native-application/understanding-tizen-programming/application-filtering"><b>Feature List</b>.</a>
+ *
+ */
+
+#endif /* __TIZEN_SERVICE_BATTERY_MONITOR_DOC_H__ */
+
diff --git a/include/battery_monitor.h b/include/battery_monitor.h
new file mode 100644 (file)
index 0000000..cdc05b9
--- /dev/null
@@ -0,0 +1,245 @@
+/*
+ * 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 __TIZEN_SERVICE_BATTERY_MONITOR_H__
+#define __TIZEN_SERVICE_BATTERY_MONITOR_H__
+
+#include <tizen.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @addtogroup  CAPI_BATTERY_MONITOR_MODULE
+ * @{
+ */
+
+// TODO : this macro will be moved to the tizen_error.h
+#ifndef TIZEN_ERROR_BATTERY_MONITOR
+#define TIZEN_ERROR_BATTERY_MONITOR    -0x03060000
+#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 | 0x09,        /**< NULL Pointer Value */
+       BATTERY_MONITOR_ERROR_INTERNAL = TIZEN_ERROR_BATTERY_MONITOR | 0x0a,            /**< Internal error for generic use */
+       BATTERY_MONITOR_ERROR_PLUGIN_ADD = TIZEN_ERROR_BATTERY_MONITOR | 0x0b,          /**< Plugin add error */
+       BATTERY_MONITOR_ERROR_PLUGIN_AVAILABLE = TIZEN_ERROR_BATTERY_MONITOR | 0x0c,    /**< Plugin already added */
+       BATTERY_MONITOR_ERROR_NOT_SUPPORTED = TIZEN_ERROR_NOT_SUPPORTED,                /**< Not supported */
+       BATTERY_MONITOR_ERROR_DATABASE_BUSY = TIZEN_ERROR_BATTERY_MONITOR | 0x0d,       /**< SQLite busy handler expired */
+} battery_monitor_error_e;
+
+/**
+ * @brief        Enumeration for feature data type.
+ * @since_tizen  5.5
+ */
+typedef enum {
+       BATTERY_MONITOR_RESOURCE_ID_BLE = 0,            /**< Bluetooth Low Energy */
+       BATTERY_MONITOR_RESOURCE_ID_WIFI,               /**< Wi-Fi */
+       BATTERY_MONITOR_RESOURCE_ID_CPU,                /**< CPU */
+       BATTERY_MONITOR_RESOURCE_ID_DISPLAY,            /**< Display */
+       BATTERY_MONITOR_RESOURCE_ID_DEVICE_NETWORK,     /**< Network */
+       BATTERY_MONITOR_RESOURCE_ID_GPS_SENSOR,         /**< GPS */
+       BATTERY_MONITOR_RESOURCE_ID_HRM_SENSOR,         /**< Heart Rate Monitor */
+       BATTERY_MONITOR_RESOURCE_ID_BATTERY,            /**< Battery */
+} battery_monitor_resource_id_e;
+
+/**
+ * @brief        Enumeration for feature data collection period.
+ * @since_tizen  5.5
+ */
+typedef enum {
+       BATTERY_MONITOR_DURATION_TYPE_1DAY = 0,  /**< Set the period from a day ago to now */
+       BATTERY_MONITOR_DURATION_TYPE_1WEEK,     /**< Set the period from a week ago to now */
+} battery_monitor_duration_type_e;
+
+/**
+ * @brief        Handle for total battery consumption structure.
+ * @since_tizen  5.5
+ */
+typedef struct battery_monitor_total_consumption_s* battery_monitor_h;
+
+/**
+ * @brief  Creates a handle to the Battery Consumption for getting resource based usage.
+ * @since_tizen  5.5
+ *
+ * @remarks  Release the handle using battery_monitor_resource_usage_handle_destroy().
+ *
+ * @param[in] handle  Battery usage consumption handle reference for the app-id usage
+ *
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
+ * @retval #BATTERY_MONITOR_ERROR_NONE                  Successful
+ * @retval #BATTERY_MONITOR_ERROR_NOT_SUPPORTED         Feature Not Supported
+ * @retval #BATTERY_MONITOR_ERROR_INVALID_PARAMETER     Invalid Parameter
+ * @retval #BATTERY_MONITOR_ERROR_OUT_OF_MEMORY         Out of Memory
+ */
+int battery_monitor_resource_usage_handle_create(battery_monitor_h *handle);
+
+/**
+ * @brief  Destroys the Battery Consumption handle and releases all its resources.
+ * @since_tizen  5.5
+ *
+ * @param[in] handle  Battery usage consumption handle for the app-id
+ *
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
+ * @retval #BATTERY_MONITOR_ERROR_NONE                  Successful
+ * @retval #BATTERY_MONITOR_ERROR_NOT_SUPPORTED         Feature Not Supported
+ * @retval #BATTERY_MONITOR_ERROR_INVALID_PARAMETER     Invalid Parameter
+ */
+int battery_monitor_resource_usage_handle_destroy(battery_monitor_h handle);
+
+/**
+ * @brief  Gets the battery-percent for specific resource from available data.
+ * @since_tizen  5.5
+ * @privlevel  public
+ * @privilege  %http://tizen.org/privilege/battery.monitor
+ *
+ * @param[in] handle  Battery usage consumption handle for the app-id
+ * @param[in] resource_id  Identifier of resource type . BLE, WiFi, CPU etc
+ * @param[out] battery_usage  Battery usage consumption for resource_id
+ *
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
+ * @retval #BATTERY_MONITOR_ERROR_NONE                  Successful
+ * @retval #BATTERY_MONITOR_ERROR_NOT_SUPPORTED         Feature Not Supported
+ * @retval #BATTERY_MONITOR_ERROR_PERMISSION_DENIED     Permission Denied
+ * @retval #BATTERY_MONITOR_ERROR_INVALID_PARAMETER     Invalid Parameter
+ */
+int battery_monitor_get_usage_for_resource_id(battery_monitor_h handle, battery_monitor_resource_id_e resource_id, int *battery_usage);
+
+/**
+ * @brief  Gets the battery-percent for all resources used by app_id.
+ * @since_tizen  5.5
+ * @privlevel  public
+ * @privilege  %http://tizen.org/privilege/battery.monitor
+ *
+ * @param[in] app_id  App-id for which battery usage is required
+ * @param[in] duration  Time duration for which battery usage is requested
+ * @param[out] handle  Battery usage consumption for the app-id
+ *
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
+ * @retval #BATTERY_MONITOR_ERROR_NONE                  Successful
+ * @retval #BATTERY_MONITOR_ERROR_NOT_SUPPORTED         Feature Not Supported
+ * @retval #BATTERY_MONITOR_ERROR_PERMISSION_DENIED     Permission Denied
+ * @retval #BATTERY_MONITOR_ERROR_INVALID_PARAMETER     Invalid Parameter
+ * @retval #BATTERY_MONITOR_ERROR_DB_NOT_OPENED         DB not Opened
+ * @retval #BATTERY_MONITOR_ERROR_DB_FAILED             DB operation failed
+ * @retval #BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND      Record Not found
+ * @retval #BATTERY_MONITOR_ERROR_INTERNAL              Internal Error
+ */
+int battery_monitor_get_usage_by_app_id_for_all_resource_id(char *app_id, battery_monitor_duration_type_e duration, battery_monitor_h handle);
+
+/**
+ * @brief  Gets the battery-percent by an app-id for a specific resource.
+ * @since_tizen  5.5
+ * @privlevel  public
+ * @privilege  %http://tizen.org/privilege/battery.monitor
+ *
+ * @param[in] app_id  App-id for which battery usage is required
+ * @param[in] resource_id  Identifier of resource type . BLE, WiFi, CPU etc
+ * @param[in] duration  Time duration for which battery usage is requested
+ * @param[out] battery_usage  Battery usage consumption for the app-id
+ *
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
+ * @retval #BATTERY_MONITOR_ERROR_NONE                  Successful
+ * @retval #BATTERY_MONITOR_ERROR_NOT_SUPPORTED         Feature Not Supported
+ * @retval #BATTERY_MONITOR_ERROR_PERMISSION_DENIED     Permission Denied
+ * @retval #BATTERY_MONITOR_ERROR_INVALID_PARAMETER     Invalid Parameter
+ * @retval #BATTERY_MONITOR_ERROR_DB_NOT_OPENED         DB not Opened
+ * @retval #BATTERY_MONITOR_ERROR_DB_FAILED             DB operation failed
+ * @retval #BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND      Record Not found
+ * @retval #BATTERY_MONITOR_ERROR_INTERNAL              Internal Error
+ */
+int battery_monitor_get_usage_by_app_id_for_resource_id(char *app_id, battery_monitor_resource_id_e resource_id, battery_monitor_duration_type_e duration, int *battery_usage);
+
+/**
+ * @brief  Gets the total battery usage in percent by an app-id for certain time duration.
+ * @details  This will be sum of all battery consumed by resources used by application.
+ * @since_tizen  5.5
+ * @privlevel  public
+ * @privilege  %http://tizen.org/privilege/battery.monitor
+ *
+ * @param[in] app_id  App-id for which battery usage is required
+ * @param[in] duration  Time duration for which battery usage is requested
+ * @param[out] battery_usage  Battery usage consumption for the app-id
+ *
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
+ * @retval #BATTERY_MONITOR_ERROR_NONE                  Successful
+ * @retval #BATTERY_MONITOR_ERROR_NOT_SUPPORTED         Feature Not Supported
+ * @retval #BATTERY_MONITOR_ERROR_PERMISSION_DENIED     Permission Denied
+ * @retval #BATTERY_MONITOR_ERROR_INVALID_PARAMETER     Invalid Parameter
+ * @retval #BATTERY_MONITOR_ERROR_DB_NOT_OPENED         DB not Opened
+ * @retval #BATTERY_MONITOR_ERROR_DB_FAILED             DB operation failed
+ * @retval #BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND      Record Not found
+ * @retval #BATTERY_MONITOR_ERROR_INTERNAL              Internal Error
+*/
+int battery_monitor_get_total_usage_by_app_id(char *app_id, battery_monitor_duration_type_e duration, int *battery_usage);
+
+/**
+ * @brief  Gets the battery-percent usage by a resource for certain time duration.
+ * @since_tizen  5.5
+ * @privlevel  public
+ * @privilege  %http://tizen.org/privilege/battery.monitor
+ *
+ * @param[in] resource_id  Resource identifier for which battery usage is requested
+ * @param[in] duration  Time duration for which battery usage is requested
+ * @param[out] battery_usage  Battery usage consumption for resource-id
+ *
+ * @return  @c 0 on success,
+ *          otherwise a negative error value
+ * @retval #BATTERY_MONITOR_ERROR_NONE                  Successful
+ * @retval #BATTERY_MONITOR_ERROR_NOT_SUPPORTED         Feature Not Supported
+ * @retval #BATTERY_MONITOR_ERROR_PERMISSION_DENIED     Permission Denied
+ * @retval #BATTERY_MONITOR_ERROR_INVALID_PARAMETER     Invalid Parameter
+ * @retval #BATTERY_MONITOR_ERROR_DB_NOT_OPENED         DB not Opened
+ * @retval #BATTERY_MONITOR_ERROR_DB_FAILED             DB operation failed
+ * @retval #BATTERY_MONITOR_ERROR_RECORD_NOT_FOUND      Record Not found
+ * @retval #BATTERY_MONITOR_ERROR_INTERNAL              Internal Error
+*/
+int battery_monitor_get_total_usage_by_resource_id(battery_monitor_resource_id_e resource_id, battery_monitor_duration_type_e duration, int *battery_usage);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TIZEN_SERVICE_BATTERY_MONITOR_H__ */
diff --git a/include/battery_monitor_dbg.h b/include/battery_monitor_dbg.h
new file mode 100644 (file)
index 0000000..21ecc0a
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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 __TIZEN_SERVICE_BATTERY_MONITOR_DBG_H__
+#define __TIZEN_SERVICE_BATTERY_MONITOR_DBG_H__
+
+#include <tizen.h>
+#include <dlog.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef  LOG_TAG
+#undef  LOG_TAG
+#endif
+#define LOG_TAG "BMCAPI"
+
+#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 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 /* __TIZEN_SERVICE_BATTERY_MONITOR_DBG_H__ */
diff --git a/include/battery_monitor_internal.h b/include/battery_monitor_internal.h
new file mode 100644 (file)
index 0000000..d8020cf
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * 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 __TIZEN_SERVICE_BATTERY_MONITOR_INTERNAL_H__
+#define __TIZEN_SERVICE_BATTERY_MONITOR_INTERNAL_H__
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief        Structure for total battery consumption
+ * @since_tizen  5.5
+ */
+struct battery_monitor_total_consumption_s {
+       int ble_val;   /**< Battery consumption by BLE(Bluetooth Low Energy) */
+       int wifi_val;  /**< Battery consumption by Wi-Fi */
+       int cpu_val;   /**< Battery consumption by CPU */
+       int dp_val;    /**< Battery consumption by display */
+       int dn_val;    /**< Battery consumption by network */
+       int gps_val;   /**< Battery consumption by GPS */
+       int hrm_val;   /**< Battery consumption by HRM(Heart Rate Monitor) sensor */
+       int bat_val;   /**< Total battery consumption/ Change in battery level */
+};
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TIZEN_SERVICE_BATTERY_MONITOR_INTERNAL_H__ */
diff --git a/include/battery_monitor_util.h b/include/battery_monitor_util.h
new file mode 100644 (file)
index 0000000..3161edc
--- /dev/null
@@ -0,0 +1,149 @@
+/*
+ * 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 __TIZEN_SERVICE_BATTERY_MONITOR_UTIL_H__
+#define __TIZEN_SERVICE_BATTERY_MONITOR_UTIL_H__
+
+#include <stdlib.h>
+#include <stdbool.h>
+#include <glib.h>
+#include <gio/gio.h>
+#include <tzplatform_config.h>
+#include <system_info.h>
+
+#include "battery_monitor_dbg.h"
+#include "battery_monitor.h"
+#include "battery_monitor_internal.h"
+
+#include "../battery-monitor-stub.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* feature supported macros */
+#define BATTERY_FEATURE                                "http://tizen.org/feature/battery"
+
+#define CHECK_BATTERY_FEATURE_SUPPORTED(feature_name) \
+       do { \
+               bool is_supported = false; \
+               if (!system_info_get_platform_bool(feature_name, &is_supported)) { \
+                       if (is_supported == false) { \
+                               LOGE("[%s] feature is disabled", feature_name); \
+                                       return BATTERY_MONITOR_ERROR_NOT_SUPPORTED; \
+                       } \
+               } else { \
+                       LOGE("Error - Feature getting from System Info"); \
+               } \
+       } while (0)
+
+/* dbus macros*/
+#define BATTERY_MONITOR_DBUS_NAME              "org.tizen.battery.monitor"
+#define BATTERY_MONITOR_DBUS_PATH              "/org/tizen/battery/monitor"
+
+#define BATTERY_MONITOR_INCREASE_COUNT(x)      (x++)
+#define BATTERY_MONITOR_DECREASE_COUNT(x)      (x--)
+
+#define BATTERY_MONITOR_SVC_ERROR_DOMAIN       "batterymonitor-svc"
+#define BATTERY_MONITOR_SVC_ERROR_PREFIX       "org.tizen.battery.monitor.Error"
+
+#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"
+
+/* validating input param */
+#define BM_CHECK_INPUT_PARAM(arg) \
+       do { \
+               if (NULL == arg) { \
+                       _ERR("invalid input param"); \
+                       return BATTERY_MONITOR_ERROR_INVALID_PARAMETER; \
+               } \
+       } 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; \
+       } \
+
+#ifndef BM_API
+#define BM_API __attribute__ ((visibility("default")))
+#endif
+
+int battery_monitor_get_error_code(bool is_success, GError *error);
+
+void unmarshal_serialized_data(GVariant *handle, battery_monitor_h data_handle);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __TIZEN_SERVICE_BATTERY_MONITOR_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/capi-battery-monitor.spec b/packaging/capi-battery-monitor.spec
new file mode 100644 (file)
index 0000000..0127aa1
--- /dev/null
@@ -0,0 +1,75 @@
+Name:    capi-battery-monitor
+Summary: Battery Monitor Framework CAPI
+Version: 0.1
+Release: 1
+License: Apache-2.0
+Source0: %{name}-%{version}.tar.gz
+
+BuildRequires:  cmake
+BuildRequires:  pkgconfig(dlog)
+BuildRequires:  pkgconfig(capi-base-common)
+BuildRequires:  pkgconfig(capi-system-info)
+BuildRequires:  pkgconfig(glib-2.0)
+BuildRequires:  pkgconfig(gio-2.0)
+BuildRequires:  pkgconfig(gio-unix-2.0)
+BuildRequires:  pkgconfig(pkgmgr-info)
+BuildRequires:  pkgconfig(libtzplatform-config)
+BuildRequires:  pkgconfig(aul)
+
+%define BATTERY_MONITOR_LIBDIR %{TZ_SYS_GLOBALUSER_DATA}/battery-monitor
+
+%description
+
+%package devel
+Summary: Battery Monitor Framework CAPI (Development)
+Requires: %{name} = %{version}
+
+%description devel
+%devel_desc
+
+%package test
+Summary: Battery Monitor Framework test application
+Group:   TO_BE/FILLED
+Requires: %{name} = %{version}-%{release}
+
+%description test
+This package is for Battery Monitor Framework CAPI test application
+
+%prep
+%setup -q
+
+%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}
+
+make %{?jobs:-j%jobs}
+
+%install
+%make_install
+
+%post -p /sbin/ldconfig
+
+%postun -p /sbin/ldconfig
+
+%files
+%manifest %{name}.manifest
+%defattr(-,root,root,-)
+%license LICENSE
+%attr(644,-,-) %{_libdir}/lib%{name}.so
+%attr(644,-,-) %{_libdir}/lib%{name}.so.*
+
+%files devel
+%manifest %{name}-devel.manifest
+%defattr(-,root,root,-)
+%{_libdir}/pkgconfig/%{name}.pc
+%{_includedir}/*
+
+%files test
+%manifest %{name}.manifest
+%attr(777, service_fw, service_fw) %{_bindir}/bm-test
diff --git a/src/battery_monitor.c b/src/battery_monitor.c
new file mode 100644 (file)
index 0000000..c9fd4b7
--- /dev/null
@@ -0,0 +1,407 @@
+/*
+ * 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 <pthread.h>
+
+#include "battery_monitor.h"
+#include "battery_monitor_util.h"
+
+#define BATTERY_MONITOR_RESOURCE_ID_MAX (BATTERY_MONITOR_RESOURCE_ID_HRM_SENSOR + 1)
+#define BATTERY_MONITOR_DURATION_TYPE_MAX (BATTERY_MONITOR_DURATION_TYPE_1WEEK + 1)
+
+static BatteryMonitor *bm_server = NULL;
+static GDBusConnection *connection = NULL;
+static int instance_count = 0;
+static pthread_mutex_t bm_proxy_instance_mutex = PTHREAD_MUTEX_INITIALIZER;
+
+static void battery_monitor_destroy_instance()
+{
+       ENTER;
+
+       g_object_unref(connection);
+       connection = NULL;
+
+       g_object_unref(bm_server);
+       bm_server = NULL;
+
+       EXIT;
+       return;
+}
+
+static void battery_monitor_release_instance()
+{
+       pthread_mutex_lock(&bm_proxy_instance_mutex);
+       BATTERY_MONITOR_DECREASE_COUNT(instance_count);
+
+       _INFO("instance count - %d", instance_count);
+
+       if (instance_count <= 0)
+               battery_monitor_destroy_instance();
+
+       pthread_mutex_unlock(&bm_proxy_instance_mutex);
+}
+
+static BatteryMonitor* battery_monitor_get_instance()
+{
+       pthread_mutex_lock(&bm_proxy_instance_mutex);
+
+       if (bm_server != NULL) {
+               _DBG("server instance available");
+               BATTERY_MONITOR_INCREASE_COUNT(instance_count);
+               pthread_mutex_unlock(&bm_proxy_instance_mutex);
+               return bm_server;
+       }
+
+#if !GLIB_CHECK_VERSION(2, 35, 0)
+       g_type_init();
+#endif
+
+       GError *error = NULL;
+
+       connection = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
+
+       _INFO("after g_bus_get_sync");
+
+       if (!connection) {
+               if (error) {
+                       _ERR("Unable to connect to gdbus: %s", error->message);
+                       g_clear_error(&error);
+               }
+               pthread_mutex_unlock(&bm_proxy_instance_mutex);
+               return NULL;
+       }
+
+       g_clear_error(&error);
+
+       /* create server object */
+       bm_server = battery_monitor_proxy_new_sync(connection, G_DBUS_PROXY_FLAGS_NONE,
+                               BATTERY_MONITOR_DBUS_NAME, BATTERY_MONITOR_DBUS_PATH, NULL, &error);
+
+       if (!bm_server) {
+               if (error) {
+                       _ERR("Unable account_manager_proxy_new_sync: %s", error->message);
+                       g_clear_error(&error);
+               }
+               if (connection) {
+                       g_object_unref(connection);
+                       connection = NULL;
+               }
+               pthread_mutex_unlock(&bm_proxy_instance_mutex);
+               return NULL;
+       }
+
+       g_clear_error(&error);
+
+       BATTERY_MONITOR_INCREASE_COUNT(instance_count);
+
+       pthread_mutex_unlock(&bm_proxy_instance_mutex);
+
+       EXIT;
+       return bm_server;
+}
+
+BM_API int battery_monitor_resource_usage_handle_create(battery_monitor_h *handle)
+{
+       ENTER;
+
+       CHECK_BATTERY_FEATURE_SUPPORTED(BATTERY_FEATURE);
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       battery_monitor_h data_handle = (battery_monitor_h)calloc(1, sizeof(struct battery_monitor_total_consumption_s));
+
+       if (data_handle == NULL) {
+               _ERR("Memory Allocation Failed");
+               return BATTERY_MONITOR_ERROR_OUT_OF_MEMORY;
+       }
+
+       data_handle->ble_val = 0;
+       data_handle->wifi_val = 0;
+       data_handle->cpu_val = 0;
+       data_handle->dp_val = 0;
+       data_handle->dn_val = 0;
+       data_handle->gps_val = 0;
+       data_handle->hrm_val = 0;
+       data_handle->bat_val = 0;
+
+       *handle = data_handle;
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+BM_API int battery_monitor_resource_usage_handle_destroy(battery_monitor_h handle)
+{
+       ENTER;
+
+       CHECK_BATTERY_FEATURE_SUPPORTED(BATTERY_FEATURE);
+
+       BM_CHECK_INPUT_PARAM(handle);
+
+       battery_monitor_h data_handle = handle;
+
+       BM_FREE(data_handle);
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+BM_API int battery_monitor_get_usage_for_resource_id(battery_monitor_h handle, battery_monitor_resource_id_e resource_id, int *battery_usage)
+{
+       ENTER;
+
+       CHECK_BATTERY_FEATURE_SUPPORTED(BATTERY_FEATURE);
+
+       BM_CHECK_INPUT_PARAM(handle);
+       BM_CHECK_INPUT_PARAM(battery_usage);
+
+       if (resource_id >= BATTERY_MONITOR_RESOURCE_ID_MAX) {
+               _ERR("Unknown resource id specified");
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+       }
+
+       switch (resource_id) {
+       case BATTERY_MONITOR_RESOURCE_ID_BLE:
+               *battery_usage = handle->ble_val;
+               break;
+       case BATTERY_MONITOR_RESOURCE_ID_WIFI:
+               *battery_usage = handle->wifi_val;
+               break;
+       case BATTERY_MONITOR_RESOURCE_ID_CPU:
+               *battery_usage = handle->cpu_val;
+               break;
+       case BATTERY_MONITOR_RESOURCE_ID_DISPLAY:
+               *battery_usage = handle->dp_val;
+               break;
+       case BATTERY_MONITOR_RESOURCE_ID_DEVICE_NETWORK:
+               *battery_usage = handle->dn_val;
+               break;
+       case BATTERY_MONITOR_RESOURCE_ID_GPS_SENSOR:
+               *battery_usage = handle->gps_val;
+               break;
+       case BATTERY_MONITOR_RESOURCE_ID_HRM_SENSOR:
+               *battery_usage = handle->hrm_val;
+               break;
+       case BATTERY_MONITOR_RESOURCE_ID_BATTERY:
+               *battery_usage = handle->bat_val;
+               break;
+       default:
+               break;
+       }
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+BM_API int battery_monitor_get_usage_by_app_id_for_all_resource_id(char* app_id, battery_monitor_duration_type_e duration, battery_monitor_h handle)
+{
+       ENTER;
+
+       CHECK_BATTERY_FEATURE_SUPPORTED(BATTERY_FEATURE);
+
+       BM_CHECK_INPUT_PARAM(app_id);
+       BM_CHECK_INPUT_PARAM(handle);
+       BM_RETURN_VAL((duration < BATTERY_MONITOR_DURATION_TYPE_MAX), {}, BATTERY_MONITOR_ERROR_INVALID_PARAMETER, "invalid duration");
+
+       _INFO("total consumption requested for [%s] for duration [%d]", app_id, duration);
+
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       GError *error = NULL;
+
+       bm_server = battery_monitor_get_instance();
+       BM_CATCH_ERROR((bm_server != NULL), {}, BATTERY_MONITOR_ERROR_PERMISSION_DENIED, "Failed to get dbus.");
+
+       GVariant *handle_variant = NULL;
+
+       _INFO("before IPC call - get_all_resource_usage_sync()");
+
+       bool is_success = battery_monitor_call_get_all_resource_usage_sync(bm_server, app_id, duration,
+                                       (int)getuid(), &handle_variant, NULL, &error);
+
+       battery_monitor_release_instance();
+
+       _INFO("after IPC call - get_all_resource_usage_sync()");
+
+       BM_CATCH_ERROR((is_success != false), {}, battery_monitor_get_error_code(is_success, error), "Failed to get dbus.");
+       g_clear_error(&error);
+
+       battery_monitor_h resource_handle = handle;
+
+       _INFO("before un-marshal data");
+
+       unmarshal_serialized_data(handle_variant, resource_handle);
+       g_variant_unref(handle_variant);
+
+       _INFO("after un-marshal data");
+
+       _INFO("battery_get_usage_by_app_id_for_all_resource_id() - SUCCESS");
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+CATCH:
+       g_clear_error(&error);
+       _ERR("battery_monitor_call_get_all_resource_usage_sync()=[%d]", error_code);
+       return error_code;
+}
+
+BM_API int battery_monitor_get_usage_by_app_id_for_resource_id(char* app_id, battery_monitor_resource_id_e resource_id,
+                                                               battery_monitor_duration_type_e duration, int* battery_usage)
+{
+       ENTER;
+
+       CHECK_BATTERY_FEATURE_SUPPORTED(BATTERY_FEATURE);
+
+       BM_CHECK_INPUT_PARAM(app_id);
+       BM_CHECK_INPUT_PARAM(battery_usage);
+
+       if (resource_id >= BATTERY_MONITOR_RESOURCE_ID_MAX) {
+               _ERR("Unknown resource id specified");
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+       }
+
+       if (duration >= BATTERY_MONITOR_DURATION_TYPE_MAX) {
+               _ERR("Unknown duration specified");
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+       }
+
+       int battery_consumption = 0;
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       GError *error = NULL;
+
+       bm_server = battery_monitor_get_instance();
+       BM_CATCH_ERROR((bm_server != NULL), {}, BATTERY_MONITOR_ERROR_PERMISSION_DENIED, "Failed to get dbus.");
+
+       _INFO("before IPC call - app_id(%s), resource_id(%d), duration(%d)", app_id, resource_id, duration);
+
+       bool is_success = battery_monitor_call_get_usage_by_app_id_for_resource_id_sync(bm_server, app_id, resource_id,
+                                       duration, (int)getuid(), &battery_consumption, NULL, &error);
+
+       battery_monitor_release_instance();
+
+       _INFO("after IPC call - battery_consumption(%d)", battery_consumption);
+
+       BM_CATCH_ERROR((is_success != false), {}, battery_monitor_get_error_code(is_success, error), "Failed to get dbus.");
+       g_clear_error(&error);
+
+       *battery_usage = battery_consumption;
+
+       _INFO("battery_get_usage_by_app_id_for_resource_id() - SUCCESS");
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+CATCH:
+       g_clear_error(&error);
+       _ERR("battery_monitor_call_get_usage_by_app_id_for_resource_id_sync()=[%d]", error_code);
+       return error_code;
+}
+
+BM_API int battery_monitor_get_total_usage_by_app_id(char* app_id, battery_monitor_duration_type_e duration, int* battery_usage)
+{
+       ENTER;
+
+       CHECK_BATTERY_FEATURE_SUPPORTED(BATTERY_FEATURE);
+
+       BM_CHECK_INPUT_PARAM(app_id);
+       BM_CHECK_INPUT_PARAM(battery_usage);
+
+       if (duration >= BATTERY_MONITOR_DURATION_TYPE_MAX) {
+               _ERR("Unknown duration specified");
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+       }
+
+       int battery_consumption = 0;
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       GError *error = NULL;
+
+       bm_server = battery_monitor_get_instance();
+       BM_CATCH_ERROR((bm_server != NULL), {}, BATTERY_MONITOR_ERROR_PERMISSION_DENIED, "Failed to get dbus.");
+
+       _INFO("before IPC call - app_id(%s), duration(%d)", app_id, duration);
+
+       bool is_success = battery_monitor_call_get_total_usage_by_app_id_sync(bm_server, app_id, duration,
+                                       (int)getuid(), &battery_consumption, NULL, &error);
+
+       battery_monitor_release_instance();
+
+       _INFO("after IPC call - battery_consumption(%d)", battery_consumption);
+
+       *battery_usage = battery_consumption;
+
+       BM_CATCH_ERROR((is_success != false), {}, battery_monitor_get_error_code(is_success, error), "Failed to get dbus.");
+       g_clear_error(&error);
+
+       _INFO("battery_monitor_call_get_total_usage_by_app_id_sync() - SUCCESS");
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+CATCH:
+       g_clear_error(&error);
+       _ERR("battery_monitor_call_get_total_usage_by_app_id_sync()=[%d]", error_code);
+       return error_code;
+}
+
+BM_API int battery_monitor_get_total_usage_by_resource_id(battery_monitor_resource_id_e resource_id,
+                                                       battery_monitor_duration_type_e duration, int* battery_usage)
+{
+       ENTER;
+
+       CHECK_BATTERY_FEATURE_SUPPORTED(BATTERY_FEATURE);
+
+       BM_CHECK_INPUT_PARAM(battery_usage);
+
+       if (resource_id >= BATTERY_MONITOR_RESOURCE_ID_MAX) {
+               _ERR("Unknown resource id specified");
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+       }
+
+       if (duration >= BATTERY_MONITOR_DURATION_TYPE_MAX) {
+               _ERR("Unknown duration specified");
+               return BATTERY_MONITOR_ERROR_INVALID_PARAMETER;
+       }
+
+       int battery_consumption = 0;
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       GError *error = NULL;
+
+       bm_server = battery_monitor_get_instance();
+       BM_CATCH_ERROR((bm_server != NULL), {}, BATTERY_MONITOR_ERROR_PERMISSION_DENIED, "Failed to get dbus.");
+
+       _INFO("before IPC call - resource_id(%d), duration(%d)", resource_id, duration);
+
+       bool is_success = battery_monitor_call_get_total_usage_by_resource_id_sync(bm_server, resource_id, duration,
+                                       (int)getuid(), &battery_consumption, NULL, &error);
+
+       battery_monitor_release_instance();
+
+       _INFO("after IPC call - battery_consumption(%d)", battery_consumption);
+
+       *battery_usage = battery_consumption;
+
+       BM_CATCH_ERROR((is_success != false), {}, battery_monitor_get_error_code(is_success, error), "Failed to get dbus.");
+       g_clear_error(&error);
+
+       _INFO("battery_get_total_usage_by_resource_id() - SUCCESS");
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+CATCH:
+       g_clear_error(&error);
+       _ERR("battery_monitor_call_get_total_usage_by_resource_id_sync()=[%d]", error_code);
+       return error_code;
+}
diff --git a/src/battery_monitor_util.c b/src/battery_monitor_util.c
new file mode 100644 (file)
index 0000000..5b474c9
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * 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 <pthread.h>
+
+#include "battery_monitor_util.h"
+
+GDBusErrorEntry battery_monitor_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"},
+};
+
+
+int battery_monitor_get_error_code(bool is_success, GError *error)
+{
+       ENTER;
+
+       if (!is_success) {
+               _INFO("Received error Domain[%d] Message[%s] Code[%d]", error->domain, error->message, error->code);
+
+               if (g_dbus_error_is_remote_error(error)) {
+                       gchar *remote_error = g_dbus_error_get_remote_error(error);
+                       if (remote_error) {
+                               _INFO("Remote error[%s]", remote_error);
+
+                               int error_enum_count = G_N_ELEMENTS(battery_monitor_svc_errors);
+                               int i = 0;
+                               for (i = 0; i < error_enum_count; i++) {
+                                       if (g_strcmp0(battery_monitor_svc_errors[i].dbus_error_name, remote_error) == 0) {
+                                               _INFO("Remote error code matched[%d]", battery_monitor_svc_errors[i].error_code);
+                                               g_free(remote_error);
+                                               return battery_monitor_svc_errors[i].error_code;
+                                               }
+                                       }
+                               g_free(remote_error);
+                               }
+                       }
+                       return BATTERY_MONITOR_ERROR_INTERNAL;
+               }
+
+       EXIT;
+       return BATTERY_MONITOR_ERROR_NONE;
+}
+
+void unmarshal_serialized_data(GVariant *handle, battery_monitor_h data_handle)
+{
+       ENTER;
+
+       if (!handle) {
+               _ERR("null handle received");
+               return;
+       }
+
+       GVariantIter iter;
+       g_variant_iter_init(&iter, handle);
+
+       gchar *key = NULL;
+       GVariant *value = NULL;
+
+       battery_monitor_h data = data_handle;
+
+       while (g_variant_iter_loop(&iter, "{sv}", &key, &value)) {
+               if (g_strcmp0(key, BATTERY_MONITOR_BLE_DATA_ID) == 0) {
+                       data->ble_val = g_variant_get_int32(value);
+                       _INFO("ble_val - [%d]", data->ble_val);
+               } else if (g_strcmp0(key, BATTERY_MONITOR_WIFI_DATA_ID) == 0) {
+                       data->wifi_val = g_variant_get_int32(value);
+                       _INFO("wifi_val - [%d]", data->wifi_val);
+               } else if (g_strcmp0(key, BATTERY_MONITOR_CPU_DATA_ID) == 0) {
+                       data->cpu_val = g_variant_get_int32(value);
+                       _INFO("cpu_val - [%d]", data->cpu_val);
+               } else if (g_strcmp0(key, BATTERY_MONITOR_DP_DATA_ID) == 0) {
+                       data->dp_val = g_variant_get_int32(value);
+                       _INFO("dp_val - [%d]", data->dp_val);
+               } else if (g_strcmp0(key, BATTERY_MONITOR_DN_DATA_ID) == 0) {
+                       data->dn_val = g_variant_get_int32(value);
+                       _INFO("dn_val - [%d]", data->dn_val);
+               } else if (g_strcmp0(key, BATTERY_MONITOR_GPS_DATA_ID) == 0) {
+                       data->gps_val = g_variant_get_int32(value);
+                       _INFO("gps_val - [%d]", data->gps_val);
+               } else if (g_strcmp0(key, BATTERY_MONITOR_HRM_DATA_ID) == 0) {
+                       data->hrm_val = g_variant_get_int32(value);
+                       _INFO("hrm_val - [%d]", data->hrm_val);
+               } else if (g_strcmp0(key, BATTERY_MONITOR_BATTERY_DATA_ID) == 0) {
+                       data->hrm_val = g_variant_get_int32(value);
+                       _INFO("hrm_val - [%d]", data->bat_val);
+               } else {
+                       ;
+               }
+       }
+
+       EXIT;
+       return;
+}
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
new file mode 100644 (file)
index 0000000..06cd5de
--- /dev/null
@@ -0,0 +1,3 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+
+ADD_SUBDIRECTORY(test_cli_app)
diff --git a/test/test_cli_app/CMakeLists.txt b/test/test_cli_app/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0f893c8
--- /dev/null
@@ -0,0 +1,31 @@
+SET(test "bm-test")
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(${test} REQUIRED
+       glib-2.0
+)
+
+FOREACH(flag ${${test}_CFLAGS})
+    SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS} -Wall")
+
+FILE(GLOB TEST_SRCS
+       src/bmt_usage.c
+       src/bmt_utility.c
+       src/bmt_main.c
+)
+
+INCLUDE_DIRECTORIES(
+       ${CMAKE_SOURCE_DIR}/test/test_cli_app/include
+       ${CMAKE_SOURCE_DIR}/batterymonitor-client/include
+)
+
+SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--as-needed -pie")
+
+ADD_EXECUTABLE(${test} ${TEST_SRCS})
+
+TARGET_LINK_LIBRARIES(${test} ${PROJECT_NAME} ${test_LDFLAGS})
+
+INSTALL(TARGETS ${test} DESTINATION bin)
diff --git a/test/test_cli_app/include/bmt_utility.h b/test/test_cli_app/include/bmt_utility.h
new file mode 100644 (file)
index 0000000..992f149
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+* Battery Monitor Test App
+*
+* 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_TEST_UTILITY_H
+#define BM_TEST_UTILITY_H
+
+#include <glib.h>
+
+typedef enum {
+       BM_MAIN_MENU = 0x0,
+       BM_USAGE_MENU,
+/*
+BM_DUMMY_MENU
+*/
+} battery_monitor_menu_e;
+
+void testapp_print(char *fmt, ...);
+void testapp_show_menu(battery_monitor_menu_e menu);
+void testapp_show_prompt(battery_monitor_menu_e menu);
+
+/* export API */
+void testapp_usage_main();
+
+#endif
diff --git a/test/test_cli_app/src/bmt_main.c b/test/test_cli_app/src/bmt_main.c
new file mode 100644 (file)
index 0000000..840b4c0
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+* Battery Monitor Test App
+*
+* 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 <glib.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <sys/time.h>
+
+#include "bmt_utility.h"
+
+static void testapp_system_signal_handler(int signal_number);
+
+static gboolean testapp_initialize_testing()
+{
+       if (signal(SIGINT, testapp_system_signal_handler) == SIG_ERR) {
+               testapp_print("register signal handler fail\n");
+               return FALSE;
+       }
+
+       if (signal(SIGQUIT, testapp_system_signal_handler) == SIG_ERR) {
+               testapp_print("register signal handler fail\n");
+               return FALSE;
+       }
+
+       if (signal(SIGTSTP, testapp_system_signal_handler) == SIG_ERR) {
+               testapp_print("register signal handler fail\n");
+               return FALSE;
+       }
+
+       if (signal(SIGTERM, testapp_system_signal_handler) == SIG_ERR) {
+               testapp_print("register signal handler fail\n");
+               return FALSE;
+       }
+
+       int interval = 0;
+       testapp_print("\t Proceed time %d us\n", interval);
+
+
+       return TRUE;
+}
+
+static gboolean testapp_finalize_testing()
+{
+       int error = 0;
+
+       testapp_print("testapp_finalize_testing() [%d]\n", error);
+
+       return TRUE;
+}
+
+static gboolean testapp_interpret_command(int menu_number)
+{
+       gboolean go_to_loop = TRUE;
+
+       switch (menu_number) {
+       case 1:
+               testapp_usage_main();
+               break;
+
+/*
+       case 2:
+               testapp_mail_main();
+               break;
+*/
+
+       case 0:
+               go_to_loop = FALSE;
+               break;
+       default:
+               break;
+       }
+
+       return go_to_loop;
+}
+
+static void testapp_system_signal_handler (int signal_number)
+{
+       testapp_print("signal:%d\n", signal_number);
+       switch (signal_number) {
+       case SIGQUIT:
+       case SIGINT:
+       case SIGTSTP:
+       case SIGTERM:
+               testapp_finalize_testing();
+               break;
+
+       default:
+               testapp_print("unhandled signal:%d\n", signal_number);
+               break;
+       }
+
+       exit(0);
+}
+
+int main()
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+
+       if (testapp_initialize_testing() == FALSE) {
+               testapp_print("Service not is not ready\n");
+               exit(0);
+       }
+
+       while (go_to_loop) {
+               testapp_show_menu(BM_MAIN_MENU);
+               testapp_show_prompt(BM_MAIN_MENU);
+               if (0 >= scanf("%d", &menu_number))
+                       testapp_print("Invalid input");
+               go_to_loop = testapp_interpret_command(menu_number);
+       }
+
+       testapp_finalize_testing();
+
+       exit(0);
+}
diff --git a/test/test_cli_app/src/bmt_usage.c b/test/test_cli_app/src/bmt_usage.c
new file mode 100644 (file)
index 0000000..6a7c403
--- /dev/null
@@ -0,0 +1,279 @@
+/*
+ *  Battery Monitor Test App
+ *
+ * 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.
+ *
+ */
+
+/* common header */
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+/* open header */
+#include <glib.h>
+
+/* internal header */
+#include "bmt_utility.h"
+#include <sys/time.h>
+#include <sys/times.h>
+#include <tzplatform_config.h>
+
+#include "battery_monitor.h"
+#include "battery_monitor_util.h"
+
+#define BATTERY_MONITOR_RESOURCE_ID_MAX (BATTERY_MONITOR_RESOURCE_ID_HRM_SENSOR + 1)
+
+static gboolean bmt_testapp_get_total_usage_by_app_id()
+{
+/*
+ * @brief  Gets the total battery usage in percent by an app-id for certain time duration.
+ * This will be sum of all battery consumed by resources used by application.
+ * app_id - app-id for which battery usage is required
+ * duration - time duration for which battery usage is requested
+ * battery_usage - battery usage consumption for the app-id
+*/
+
+       char app_name[56];
+       int duration = -1;
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       int battery_usage = -1;
+
+       testapp_print("\n Input AppID using Look Up table:\n");
+       if (0 >= scanf("%s", app_name)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       testapp_print("\n Input Duration using Look Up table:\n");
+       if (0 >= scanf("%d", &duration)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       error_code = battery_monitor_get_total_usage_by_app_id(app_name, duration, &battery_usage);
+       if (error_code == BATTERY_MONITOR_ERROR_NONE)
+               testapp_print(" battery_monitor_get_total_usage_by_app_id for APPID [%s] returned Usage of [%d] & Error Code [%d] \n", app_name, battery_usage, error_code);
+
+       return FALSE;
+}
+
+static gboolean bmt_testapp_get_total_usage_by_resource_id()
+{
+/*
+ * @brief  Gets the battery-percent usage by a resource for certain time duration.
+ * resource_id - resource identifier for which battery usage is requested
+ * duration - time duration for which battery usage is requested
+ * battery_usage - battery usage consumption for resource-id
+*/
+
+       int duration = -1;
+       int resource_id = -1;
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+       int battery_usage = -1;
+
+       testapp_print("\n Input Resource Id using Look Up Table: \n");
+       if (0 >= scanf("%d", &resource_id)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       testapp_print("\n Input Duration using Look Up table:\n");
+       if (0 >= scanf("%d", &duration)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       error_code = battery_monitor_get_total_usage_by_resource_id(resource_id, duration, &battery_usage);
+       if (error_code == BATTERY_MONITOR_ERROR_NONE)
+               testapp_print(" battery_monitor_get_total_usage_by_resource_id for RID [%d], returned Usage of [%d] & Error Code [%d] \n", resource_id, battery_usage, error_code);
+
+       return FALSE;
+}
+
+static gboolean bmt_testapp_get_total_usage_by_app_id_for_all_resource_id()
+{
+/*
+ * @brief  Gets the battery-percent for all resources used by app_id
+ * app_id -  app-id for which battery usage is required
+ * duration - time duration for which battery usage is requested
+ * battery_usage - battery usage consumption for the app-id
+*/
+
+       int duration = -1;
+       char app_name[56];
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+
+       battery_monitor_h data_handle = NULL;
+
+       error_code = battery_monitor_resource_usage_handle_create(&data_handle);
+       if (error_code != BATTERY_MONITOR_ERROR_NONE) {
+               testapp_print(" \n Memory Allocation failed \n");
+               return FALSE;
+       }
+
+       testapp_print("\n Input AppID using Look Up table:\n");
+       if (0 >= scanf("%s", app_name)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       testapp_print("\n Input Duration using Look Up table:\n");
+       if (0 >= scanf("%d", &duration)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       error_code = battery_monitor_get_usage_by_app_id_for_all_resource_id(app_name, duration, data_handle);
+
+       if (error_code == BATTERY_MONITOR_ERROR_NONE) {
+               testapp_print ("Valid Handle Received, Value of error_code is [%d] \n", error_code);
+
+               int battery_usage;
+               for (int id = BATTERY_MONITOR_RESOURCE_ID_BLE; id < BATTERY_MONITOR_RESOURCE_ID_MAX; id++) {
+
+                       battery_usage = -1;
+                       error_code = battery_monitor_get_usage_for_resource_id(data_handle, id, &battery_usage);
+
+                       if (error_code != BATTERY_MONITOR_ERROR_NONE)
+                               testapp_print ("Error Received, Value of error_code is [%d] \n", error_code);
+
+                       else {
+                               switch (id) {
+                               case BATTERY_MONITOR_RESOURCE_ID_BLE:
+                                       testapp_print ("Resource ID : BT App Usage Value = [%d] \n", battery_usage);
+                                       break;
+                               case BATTERY_MONITOR_RESOURCE_ID_WIFI:
+                                       testapp_print ("Resource ID : WIFI App Usage Value = [%d] \n", battery_usage);
+                                       break;
+                               case BATTERY_MONITOR_RESOURCE_ID_CPU:
+                                       testapp_print ("Resource ID : CPU App Usage Value = [%d] \n", battery_usage);
+                                       break;
+                               case BATTERY_MONITOR_RESOURCE_ID_DISPLAY:
+                                       testapp_print ("Resource ID : DISPLAY App Usage Value = [%d] \n", battery_usage);
+                                       break;
+                               case BATTERY_MONITOR_RESOURCE_ID_DEVICE_NETWORK:
+                                       testapp_print ("Resource ID : DEVICE NETWORK App Usage Value = [%d] \n", battery_usage);
+                                       break;
+                               case BATTERY_MONITOR_RESOURCE_ID_GPS_SENSOR:
+                                       testapp_print ("Resource ID : GPS App Usage Value = [%d] \n", battery_usage);
+                                       break;
+                               case BATTERY_MONITOR_RESOURCE_ID_HRM_SENSOR:
+                                       testapp_print ("Resource ID : HRM App Usage Value = [%d] \n", battery_usage);
+                                       break;
+
+                               default:
+                                       break;
+                               }
+                       }
+               }
+       }
+
+       error_code = battery_monitor_resource_usage_handle_destroy(data_handle);
+       if (error_code != BATTERY_MONITOR_ERROR_NONE)
+               testapp_print ("Handle Destroy Failed");
+
+       return FALSE;
+}
+
+static gboolean bmt_testapp_get_total_usage_by_app_id_for_resource_id()
+{
+/*
+ * @brief  Gets the battery-percent by an app-id for a specific resource.
+ * app_id -  app-id for which battery usage is required
+ * resource_id - identifier of resource type . BLE, WiFi, CPU etc
+ * duration - time duration for which battery usage is requested
+ * battery_usage - battery usage consumption for the app-id
+ */
+
+       int duration = -1;
+       char app_name[56];
+       int battery_usage = -1;
+       int resource_id = -1;
+       int error_code = BATTERY_MONITOR_ERROR_NONE;
+
+       testapp_print("\n Input AppID using Look Up table:\n");
+       if (0 >= scanf("%s", app_name)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       testapp_print("\n Input Duration using Look Up table:\n");
+       if (0 >= scanf("%d", &duration)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       testapp_print("\n Input Resource Id using Look Up Table: \n");
+       if (0 >= scanf("%d", &resource_id)) {
+               testapp_print("Invalid input ");
+               return FALSE;
+       }
+
+       error_code = battery_monitor_get_usage_by_app_id_for_resource_id(app_name, resource_id, duration, &battery_usage);
+
+       if (error_code == BATTERY_MONITOR_ERROR_NONE)
+               testapp_print (" Battery Usage for APPID [%s], of RID [%d] is [%d]", app_name, resource_id, battery_usage);
+
+       return FALSE;
+}
+
+static gboolean testapp_test_interpret_command(int selected_number)
+{
+       gboolean go_to_loop = TRUE;
+
+       switch (selected_number) {
+       case 1:
+               bmt_testapp_get_total_usage_by_app_id();
+               break;
+
+       case 2:
+               bmt_testapp_get_total_usage_by_resource_id();
+               break;
+
+       case 3:
+               bmt_testapp_get_total_usage_by_app_id_for_all_resource_id();
+               break;
+
+       case 4:
+               bmt_testapp_get_total_usage_by_app_id_for_resource_id();
+               break;
+
+       case 0:
+               go_to_loop = FALSE;
+               break;
+
+       default:
+               break;
+       }
+
+       return go_to_loop;
+}
+
+void testapp_usage_main()
+{
+       gboolean go_to_loop = TRUE;
+       int menu_number = 0;
+
+       while (go_to_loop) {
+               testapp_show_menu(BM_USAGE_MENU);
+               testapp_show_prompt(BM_USAGE_MENU);
+
+               if (0 >= scanf("%d", &menu_number))
+                       testapp_print("Invalid input");
+
+               go_to_loop = testapp_test_interpret_command(menu_number);
+       }
+}
diff --git a/test/test_cli_app/src/bmt_utility.c b/test/test_cli_app/src/bmt_utility.c
new file mode 100644 (file)
index 0000000..d7510d2
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+* Battery Monitor Test App
+*
+* 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.
+*
+*/
+
+/* common header */
+#include <stdarg.h>
+#include <string.h>
+
+/* open header */
+#include <glib.h>
+#include <glib/gprintf.h>
+
+/* internal header */
+#include "bmt_utility.h"
+
+/* internal data struct */
+void testapp_print(char *fmt, ...)
+{
+       va_list args = {0};
+       va_start(args, fmt);
+       vfprintf(stdout, fmt, args);
+       va_end(args);
+       fflush(stdout);
+}
+
+void testapp_show_menu(battery_monitor_menu_e menu)
+{
+       switch (menu) {
+       case BM_MAIN_MENU:
+               testapp_print("==========================================\n");
+               testapp_print("    Battery Monitor test application \n");
+               testapp_print("==========================================\n");
+               testapp_print("1. Usage Test\n");
+               testapp_print("2. Dummy test entry (Don't Use)\n");
+               testapp_print("0. Exit \n");
+               testapp_print("------------------------------------------\n");
+               break;
+
+       case BM_USAGE_MENU:
+               testapp_print("==========================================\n");
+               testapp_print("    USAGE MENU \n");
+               testapp_print("==========================================\n");
+               testapp_print(" 1.  Get Total Usage By App ID\n");
+               testapp_print(" 2.  Get Total Usage By Resource ID\n");
+               testapp_print(" 3.  Get App Usage for All Resource IDs\n");
+               testapp_print(" 4.  Get App Usage for a Resource ID\n");
+               testapp_print(" 5.  Dummy menu entry (Don't Use)\n");
+               testapp_print(" 0.  Go to Main Menu\n");
+               testapp_print("------------------------------------------\n\n");
+
+               testapp_print(" USE THE BELOW LOOK UP TABLES FOR GIVING VALUES \n");
+               testapp_print("==========================================\n");
+               testapp_print("    RESOURCE LOOK UP TABLE \n");
+               testapp_print("==========================================\n");
+               testapp_print(" 0 ==> BM_RESOURCE_ID_BLE \n");
+               testapp_print(" 1 ==> BM_RESOURCE_ID_WIFI \n");
+               testapp_print(" 2 ==> BM_RESOURCE_ID_CPU \n");
+               testapp_print(" 3 ==> BM_RESOURCE_ID_DISPLAY \n");
+               testapp_print(" 4 ==> BM_RESOURCE_ID_DEVICE_NETWORK \n");
+               testapp_print(" 5 ==> BM_RESOURCE_ID_GPS_SENSOR \n");
+               testapp_print(" 6 ==> BM_RESOURCE_ID_HRM_SENSOR \n");
+               testapp_print("==========================================\n");
+               testapp_print("    TIME LOOK UP TABLE \n");
+               testapp_print("==========================================\n");
+               testapp_print(" 0 ==> BM_DURATION_TYPE_1DAY \n");
+               testapp_print(" 1 ==> BM_DURATION_TYPE_1WEEK \n");
+               testapp_print("==========================================\n");
+               testapp_print("    APP ID LOOK UP TABLE \n");
+               testapp_print("==========================================\n");
+               testapp_print(" appidX \n");
+               testapp_print(" appidY \n");
+               testapp_print(" appidZ \n");
+               testapp_print("------------------------------------------\n");
+               testapp_print("------------------------------------------\n");
+               break;
+
+/*
+       case BM_DUMMY_MENU:
+               testapp_print("==========================================\n");
+               testapp_print("   DUMMY TEST\n");
+               testapp_print("==========================================\n");
+               testapp_print("1. Dummy\n");
+               testapp_print("0.  Go to Main Menu\n");
+               testapp_print("------------------------------------------\n");
+               break;
+*/
+
+       default:
+               break;
+       }
+
+}
+
+void testapp_show_prompt(battery_monitor_menu_e menu)
+{
+       switch (menu) {
+       case BM_MAIN_MENU:
+               testapp_print("[MAIN]# ");
+               break;
+
+
+       case BM_USAGE_MENU:
+               testapp_print("[BATTERY USAGE]# ");
+               break;
+
+/*
+       case BM_DUMMY_MENU:
+               testapp_print("[DUMMY]# ");
+               break;
+*/
+
+       default:
+               break;
+       }
+}