battery status: enable use of legacy code

Use 'TW_USE_LEGACY_BATTERY_SERVICES := true'
to use legacy code for battery readout in TWRP.

Some older/legacy devices cannot use health services
to accurately display battery status.

Change-Id: Ic4ed5f5f8c5ba155b53b41260d3cf3ffa7e804e4
diff --git a/Android.mk b/Android.mk
index cc6c5ad..a939c87 100644
--- a/Android.mk
+++ b/Android.mk
@@ -373,8 +373,12 @@
 ifneq ($(TW_DEFAULT_BRIGHTNESS),)
 	LOCAL_CFLAGS += -DTW_DEFAULT_BRIGHTNESS=$(TW_DEFAULT_BRIGHTNESS)
 endif
+ifeq ($(TW_USE_LEGACY_BATTERY_SERVICES),true)
+    LOCAL_CFLAGS += -DTW_USE_LEGACY_BATTERY_SERVICES
+endif
 ifneq ($(TW_CUSTOM_BATTERY_PATH),)
-	LOCAL_CFLAGS += -DTW_CUSTOM_BATTERY_PATH=$(TW_CUSTOM_BATTERY_PATH)
+    TW_USE_LEGACY_BATTERY_SERVICES := true
+    LOCAL_CFLAGS += -DTW_CUSTOM_BATTERY_PATH=$(TW_CUSTOM_BATTERY_PATH)
 endif
 ifneq ($(TW_CUSTOM_CPU_TEMP_PATH),)
 	LOCAL_CFLAGS += -DTW_CUSTOM_CPU_TEMP_PATH=$(TW_CUSTOM_CPU_TEMP_PATH)
diff --git a/twrp.cpp b/twrp.cpp
index 0362b80..b257780 100644
--- a/twrp.cpp
+++ b/twrp.cpp
@@ -425,6 +425,38 @@
 	// Function to monitor battery in the background
 	auto monitorBatteryInBackground = [&]() {
 		while (true) {
+#ifdef TW_USE_LEGACY_BATTERY_SERVICES
+			char cap_s[4];
+#ifdef TW_CUSTOM_BATTERY_PATH
+			string capacity_file = EXPAND(TW_CUSTOM_BATTERY_PATH);
+			capacity_file += "/capacity";
+			FILE * cap = fopen(capacity_file.c_str(),"rt");
+#else
+			FILE * cap = fopen("/sys/class/power_supply/battery/capacity","rt");
+#endif
+			if (cap) {
+				fgets(cap_s, 4, cap);
+				fclose(cap);
+				lastVal = atoi(cap_s);
+				if (lastVal > 100)	lastVal = 101;
+				if (lastVal < 0)	lastVal = 0;
+			}
+#ifdef TW_CUSTOM_BATTERY_PATH
+			string status_file = EXPAND(TW_CUSTOM_BATTERY_PATH);
+			status_file += "/status";
+			cap = fopen(status_file.c_str(),"rt");
+#else
+			cap = fopen("/sys/class/power_supply/battery/status","rt");
+#endif
+			if (cap) {
+				fgets(cap_s, 2, cap);
+				fclose(cap);
+				if (cap_s[0] == 'C')
+					charging = '+';
+				else
+					charging = ' ';
+			}
+#else
 			auto battery_info = GetBatteryInfo();
 			if (battery_info.charging) {
 				charging = '+';
@@ -432,6 +464,7 @@
 				charging = ' ';
 			}
 			lastVal = battery_info.capacity;
+#endif
 			// Format the value based on the background updates
 			value = std::to_string(lastVal) + "%" + charging;
 			DataManager::SetValue("tw_battery", value);