From d5f9b2acab69fd9d83cea6233e707fbdb5ea8d64 Mon Sep 17 00:00:00 2001
From: Stefan Haun <tux@netz39.de>
Date: Sun, 25 Aug 2019 01:00:49 +0200
Subject: [PATCH] Add battery capacity to python API

---
 Documentation/pycardium/power.rst |  7 +++++++
 pycardium/modules/power.c         | 16 ++++++++++++++++
 pycardium/modules/qstrdefs.h      |  1 +
 3 files changed, 24 insertions(+)

diff --git a/Documentation/pycardium/power.rst b/Documentation/pycardium/power.rst
index eb661764..de90a3dd 100644
--- a/Documentation/pycardium/power.rst
+++ b/Documentation/pycardium/power.rst
@@ -32,6 +32,13 @@ in your scripts.
 
    .. versionadded:: 1.4
 
+.. py:function:: read_battery_capacity()
+
+   Calculate the remaining battery capacity in percent.
+
+   Uses 42 logarithmic values from a look-up table to estimate
+   the remaining capacity in percent based on the battery voltage.
+
 .. py:function:: read_chargein_voltage()
 
    Read the charge voltage in V.
diff --git a/pycardium/modules/power.c b/pycardium/modules/power.c
index 6a377aaf..02fbfdcd 100644
--- a/pycardium/modules/power.c
+++ b/pycardium/modules/power.c
@@ -32,6 +32,20 @@ static MP_DEFINE_CONST_FUN_OBJ_0(
 	power_read_battery_current_obj, mp_power_read_battery_current
 );
 
+static mp_obj_t mp_power_read_battery_capacity()
+{
+	float result;
+	int status = epic_read_battery_capacity(&result);
+	if (status < 0) {
+		mp_raise_OSError(-status);
+		return mp_const_none;
+	}
+	return mp_obj_new_float(result);
+}
+static MP_DEFINE_CONST_FUN_OBJ_0(
+	power_read_battery_capacity_obj, mp_power_read_battery_capacity
+);
+
 static mp_obj_t mp_power_read_chargein_voltage()
 {
 	float result;
@@ -94,6 +108,8 @@ static const mp_rom_map_elem_t power_module_globals_table[] = {
 	  MP_ROM_PTR(&power_read_battery_voltage_obj) },
 	{ MP_ROM_QSTR(MP_QSTR_read_battery_current),
 	  MP_ROM_PTR(&power_read_battery_current_obj) },
+	{ MP_ROM_QSTR(MP_QSTR_read_battery_capacity),
+	  MP_ROM_PTR(&power_read_battery_capacity_obj) },
 	{ MP_ROM_QSTR(MP_QSTR_read_chargein_voltage),
 	  MP_ROM_PTR(&power_read_chargein_voltage_obj) },
 	{ MP_ROM_QSTR(MP_QSTR_read_chargein_current),
diff --git a/pycardium/modules/qstrdefs.h b/pycardium/modules/qstrdefs.h
index 0ff0a8ca..0a909647 100644
--- a/pycardium/modules/qstrdefs.h
+++ b/pycardium/modules/qstrdefs.h
@@ -79,6 +79,7 @@ Q(z)
 Q(power)
 Q(read_battery_voltage)
 Q(read_battery_current)
+Q(read_battery_capacity)
 Q(read_chargein_voltage)
 Q(read_chargein_current)
 Q(read_system_voltage)
-- 
GitLab