#include "battery.h" #include "battery_status.h" #include namespace { i2c_master_dev_handle_t device = nullptr; uint32_t last_poll = 0; int cached = battery_status::unknown; bool cached_charging = false; bool polled = false; bool read_reg(uint8_t reg, uint8_t &value) { return i2c_master_transmit_receive(device, ®, 1, &value, 1, 10) == ESP_OK; } } bool battery_init(i2c_master_bus_handle_t bus) { if (!bus) return false; i2c_device_config_t config = {}; config.dev_addr_length = I2C_ADDR_BIT_LEN_7; config.device_address = 0x34; config.scl_speed_hz = 100000; if (i2c_master_bus_add_device(bus, &config, &device) != ESP_OK) return false; uint8_t id = 0; if (!read_reg(0x03, id) || id != 0x4a) { i2c_master_bus_rm_device(device); device = nullptr; Serial.println("BATTERY AXP2101 unavailable"); return false; } // Do not alter charging voltage/current, gauge calibration, or power rails. Serial.println("BATTERY AXP2101 ready"); battery_percent(); return true; } int battery_percent() { const uint32_t now = millis(); if (!device || (polled && static_cast(now - last_poll) < 5000)) return cached; last_poll = now; const int previous = cached; const bool previous_charging = cached_charging; const bool first = !polled; polled = true; uint8_t status = 0, status2 = 0, percent = 0; cached = battery_status::unknown; cached_charging = false; // Vendor XPowersLib: STATUS1 (0x00) bit 3 = battery connected; // BAT_PERCENT_DATA (0xa4) is the gauge's 0..100 percent, not a voltage guess. if (read_reg(0x00, status)) { if (!(status & (1u << 3))) cached = battery_status::disconnected; else { if (read_reg(0xa4, percent)) cached = battery_status::decode(status, percent); if (read_reg(0x01, status2)) cached_charging = battery_status::charging(status, status2); } } if (first || cached != previous || cached_charging != previous_charging) { char label[8]; battery_status::format(label, sizeof(label), cached); Serial.printf("BATTERY %s charging=%d\n", label, cached_charging); } return cached; } bool battery_charging() { battery_percent(); // Shares the same cached poll; never another immediate I2C read. return cached_charging; }