healthd: fix the over estimated battery capacity

Overwrite the gauge capacity with the backup one if the gauge capacity
reset to nominal.

Test: fake /sys/class/power_supply/bms/charge_full to nominal and
      check if it can be restored from /persist/battery/qcom_charge_full
Bug: 158838006
Signed-off-by: Jack Wu <wjack@google.com>
Change-Id: I4b85dd5e0c3ca929044aa8776294b841db7214e1
diff --git a/health/LearnedCapacityBackupRestore.cpp b/health/LearnedCapacityBackupRestore.cpp
index cf8de8d..a3111d3 100644
--- a/health/LearnedCapacityBackupRestore.cpp
+++ b/health/LearnedCapacityBackupRestore.cpp
@@ -21,6 +21,7 @@
 namespace wahoo {
 namespace health {
 
+static constexpr char kChgFullDesignFile[] = "sys/class/power_supply/bms/charge_full_design";
 static constexpr char kChgFullFile[] = "sys/class/power_supply/bms/charge_full";
 static constexpr char kSysCFPersistFile[] = "/persist/battery/qcom_charge_full";
 static constexpr int kBuffSize = 256;
@@ -29,13 +30,15 @@
 
 void LearnedCapacityBackupRestore::Restore() {
     ReadFromStorage();
+    ReadNominalCapacity();
     ReadFromSRAM();
     if (sw_cap_ == 0) {
         // First backup
         sw_cap_ = hw_cap_;
         SaveToStorage();
-    } else {
-        // Always restore backup value
+    } else if (hw_cap_ == nom_cap_) {
+        // Restore backup value when capacity is reset to nominal
+        hw_cap_ = sw_cap_;
         SaveToSRAM();
     }
 }
@@ -74,11 +77,27 @@
         LOG(ERROR) << "Write file error: " << strerror(errno);
 }
 
+void LearnedCapacityBackupRestore::ReadNominalCapacity() {
+    std::string buffer;
+
+    if (!android::base::ReadFileToString(std::string(kChgFullDesignFile), &buffer)) {
+        LOG(ERROR) << "Read nominal capacity error: " << strerror(errno);
+        return;
+    }
+
+    buffer = android::base::Trim(buffer);
+
+    if (sscanf(buffer.c_str(), "%d", &nom_cap_) < 1)
+        LOG(ERROR) << "Failed to parse nominal capacity: " << buffer;
+    else
+        LOG(INFO) << "nominal capacity: " << buffer;
+}
+
 void LearnedCapacityBackupRestore::ReadFromSRAM() {
     std::string buffer;
 
     if (!android::base::ReadFileToString(std::string(kChgFullFile), &buffer)) {
-        LOG(ERROR) << "Read cycle counter error: " << strerror(errno);
+        LOG(ERROR) << "Read capacity error: " << strerror(errno);
         return;
     }
 
diff --git a/health/LearnedCapacityBackupRestore.h b/health/LearnedCapacityBackupRestore.h
index da9e564..b35396d 100644
--- a/health/LearnedCapacityBackupRestore.h
+++ b/health/LearnedCapacityBackupRestore.h
@@ -36,9 +36,11 @@
   private:
     int sw_cap_;
     int hw_cap_;
+    int nom_cap_;
 
     void ReadFromStorage();
     void SaveToStorage();
+    void ReadNominalCapacity();
     void ReadFromSRAM();
     void SaveToSRAM();
 };