31#include "../../SensorBuildOpt.h"
32#if !SENSORLIB_EXCLUDE_GAUGE_BQ27220
35#include "../GaugeBase.hpp"
38static constexpr uint8_t BQ27220_SLAVE_ADDRESS = (0x55);
43 bool isConfigUpdateMode;
44 bool isBtpThresholdExceeded;
45 bool isCapacityAccumulationThrottled;
46 bool isInitializationComplete;
47 bool isDischargeCycleCompliant;
48 bool isBatteryVoltageBelowEdv2;
49 uint8_t securityAccessLevel;
50 bool isCalibrationModeEnabled;
54 isConfigUpdateMode = (value & 0x0400) != 0;
56 isBtpThresholdExceeded = (value & 0x80) != 0;
58 isCapacityAccumulationThrottled = (value & 0x40) != 0;
60 isInitializationComplete = (value & 0x20) != 0;
62 isDischargeCycleCompliant = (value & 0x10) != 0;
64 isBatteryVoltageBelowEdv2 = (value & 0x08) != 0;
66 securityAccessLevel = (value >> 1) & 0x03;
68 isCalibrationModeEnabled = (value & 0x01) != 0;
73 return isConfigUpdateMode;
78 return isBtpThresholdExceeded;
83 return isCapacityAccumulationThrottled;
88 return isInitializationComplete;
93 return isDischargeCycleCompliant;
98 return isBatteryVoltageBelowEdv2;
103 return securityAccessLevel;
108 return isCalibrationModeEnabled;
159 uint8_t hsb = (bitmaps >> 8) & 0xFF;
160 uint8_t lsb = bitmaps & 0xFF;
186 return status.fullDischargeDetected;
194 return status.ocvMeasurementUpdateComplete;
203 return status.ocvReadFailedDueToCurrent;
212 return status.inSleepMode;
221 return status.overTemperatureDuringCharging;
230 return status.overTemperatureDuringDischarge;
239 return status.fullChargeDetected;
248 return status.chargeInhibited;
257 return status.chargingTerminationAlarm;
265 return status.goodOcvMeasurement;
273 return status.batteryInserted;
281 return status.batteryPresent;
290 return status.dischargeTerminationAlarm;
299 return status.systemShutdownRequired;
308 return status.inDischargeMode;
366 rawA = (registerValue >> 16);
368 temps = (rawA >> 7) & 1;
369 reserved1 = (rawA >> 6) & 1;
370 batg_pol = (rawA >> 5) & 1;
371 batg_en = (rawA >> 4) & 1;
372 reserved2 = (rawA >> 3) & 1;
373 sleep = (rawA >> 2) & 1;
374 slpwakechg = (rawA >> 1) & 1;
378 bienable = (rawA >> 15) & 1;
379 reserved3 = (rawA >> 14) & 1;
380 bl_pup_en = (rawA >> 13) & 1;
381 pfc_cfg = (rawA >> 11) & 3;
382 wake_en = (rawA >> 10) & 1;
383 wk_th1 = (rawA >> 9) & 1;
384 wk_th0 = (rawA >> 8) & 1;
387 rawB = (registerValue & 0xFFFF);
390 defaultSeal = (rawB >> 3) & 1;
391 nonRemovable = (rawB >> 2) & 1;
394 intBrem = (rawB >> 15) & 1;
395 intBatL = (rawB >> 14) & 1;
396 intState = (rawB >> 13) & 1;
397 intOcv = (rawB >> 12) & 1;
398 intOt = (rawB >> 10) & 1;
399 intPol = (rawB >> 9) & 1;
400 intFocv = (rawB >> 8) & 1;
596 uint16_t AtRateTimeToEmpty;
597 uint16_t Temperature;
604 uint16_t RemainingCapacity;
605 uint16_t FullChargeCapacity;
609 uint16_t TimeToEmpty;
611 int16_t StandbyCurrent;
612 uint16_t StandbyTimeToEmpty;
613 int16_t MaxLoadCurrent;
614 uint16_t MaxLoadTimeToEmpty;
615 uint16_t RawCoulombCount;
616 int16_t AveragePower;
620 uint16_t InternalTemperature;
622 uint16_t StateOfCharge;
623 uint16_t StateOfHealth;
624 uint16_t ChargingVoltage;
625 uint16_t ChargingCurrent;
626 uint16_t BTPDischargeSet;
627 uint16_t BTPChargeSet;
629 uint16_t OperationStatus;
630 uint16_t DesignCapacity;
646 bool begin(TwoWire &wire,
int sda = -1,
int scl = -1)
651#elif defined(ESP_PLATFORM)
653#if defined(SENSORLIB_USE_I2C_LEGACY)
654 bool begin(i2c_port_t port_num,
int sda = -1,
int scl = -1)
659 bool begin(i2c_master_bus_handle_t handle)
685 uint8_t *ptr = (uint8_t *)&
data;
687 uint16_t value = (buffer[
i + 1] << 8) | buffer[
i];
688 *(uint16_t *)ptr = value;
695 data.OperationStatus = (buffer[1] << 8) | buffer[0];
696 data.DesignCapacity = (buffer[3] << 8) | buffer[2];
934 return performConfigUpdate<bool>([
this, newDesignCapacity, newFullChargeCapacity]() {
966 return performConfigUpdate<OperationConfig>([
this]() {
973 uint16_t bitmapsA = (buffer[0] << 8) | buffer[1];
974 uint16_t bitmapsB = (buffer[2] << 8) | buffer[3];
986 uint8_t buffer[2] = {0};
990 if (this->getMACData(buffer,
arraySize(buffer)) < 0) {
993 return static_cast<uint16_t
>((buffer[1] << 8) | buffer[0]);
1008 constexpr uint8_t value = 0x00;
1010 if (this->getMACData(buffer,
arraySize(buffer)) < 0) {
1013 return static_cast<uint16_t
>((buffer[1] << 8) | buffer[0]);
1031 if (this->getMACData(buffer,
arraySize(buffer)) < 0) {
1034 return (buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8) | buffer[0];
1064 int getMACData(uint8_t *buffer, uint8_t request_len)
1067 if (request_len > max_size) {
1079 uint16_t getMACDataSum()
1090 uint16_t getMACDataLen()
1092 uint8_t length = 0x00;
1100 int sendSubCommand(uint16_t subCmd,
bool waitConfirm =
false)
1113 constexpr uint8_t statusReg = 0x00;
1116 while (waitCount--) {
1118 uint16_t *value =
reinterpret_cast<uint16_t *
>(buffer);
1119 if (*value == 0xFFA5) {
1131 uint8_t cmd1[] = {0x00, 0x14, 0x04};
1136 uint8_t cmd2[] = {0x00, 0x72, 0x36};
1145 int unsealFullAccess()
1169 template<
typename ResultType,
typename Func>
1170 ResultType performConfigUpdate(Func specificOperation)
1172 bool isSealed =
false;
1189 bool isConfigUpdate =
false;
1190 uint32_t timeout =
hal->millis() + 1500UL;
1191 while (timeout >
hal->millis()) {
1192 status = getOperationStatusNow();
1194 isConfigUpdate =
true;
1199 if (!isConfigUpdate) {
1200 SENSORLIB_LOG_E(
"The update mode has timed out. It may also be that the access key for full permissions is invalid!");
1201 if (std::is_same<ResultType, bool>::value) {
1203 }
else if (std::is_same<ResultType, OperationConfig>::value) {
1208 ResultType result = specificOperation();
1215 timeout =
hal->millis() + 3000UL;
1216 while (timeout >
hal->millis()) {
1217 status = getOperationStatusNow();
1219 timeout =
hal->millis() + 1000;
1224 if (
hal->millis() > timeout) {
1226 if (std::is_same<ResultType, bool>::value) {
1228 }
else if (std::is_same<ResultType, OperationConfig>::value) {
1243 bool setCapacity(uint16_t newCapacity, uint8_t msbAccessValue, uint8_t lsbAccessValue)
1245 constexpr uint8_t fixedDataLength = 0x06;
1258 uint8_t capacityRaw[] = {newCapacityMsb, newCapacityLsb};
1262 uint8_t newChksum = 0xFF - ((msbAccessValue + lsbAccessValue + newCapacityMsb + newCapacityLsb) & 0xFF);
1273 int getHalfWord(uint8_t reg)
1275 uint8_t buffer[2] = {0};
1280 return (buffer[1] << 8) | buffer[0];
1283 bool initImpl(uint8_t param)
override
constexpr size_t arraySize(const T(&arr)[N])
Returns the number of elements in a C‑style array at compile time.
#define SENSORLIB_LOG_E(...)
#define SENSORLIB_LOG_D(...)
bool overTemperatureDuringDischarge
bool isInSleepMode() const
Check if the device is in sleep mode.
bool dischargeTerminationAlarm
bool ocvReadFailedDueToCurrent
bool isBatteryPresent() const
Check if a battery is present.
bool isChargeInhibited() const
Check if charging is inhibited.
struct BatteryStatus::@0 status
bool isInDischargeMode() const
Check if the device is in discharge mode.
bool ocvMeasurementUpdateComplete
bool fullDischargeDetected
bool isOverTemperatureDuringCharging() const
Check if over-temperature is detected during charging.
bool isDischargeTerminationAlarm() const
Check if the discharge termination alarm is triggered.
bool isFullChargeDetected() const
Check if full charge is detected.
bool isSystemShutdownRequired() const
Check if system shutdown is required.
bool isGoodOcvMeasurement() const
Check if a good OCV measurement was made.
bool chargingTerminationAlarm
bool isOcvReadFailedDueToCurrent() const
Check if the OCV read failed due to current.
bool isChargingTerminationAlarm() const
Check if the charging termination alarm is triggered.
bool isOverTemperatureDuringDischarge() const
Check if over-temperature is detected during discharge.
BatteryStatus(uint16_t bitmaps)
Constructor for BatteryStatus class.
bool systemShutdownRequired
bool isFullDischargeDetected() const
Check if full discharge is detected.
bool isOcvMeasurementUpdateComplete() const
Check if the OCV measurement update is complete.
bool isBatteryInserted() const
Check if a battery is inserted.
bool overTemperatureDuringCharging
std::unique_ptr< SensorHal > hal
bool getIsInitializationComplete() const
bool getIsCalibrationModeEnabled() const
bool getIsBatteryVoltageBelowEdv2() const
bool getIsBtpThresholdExceeded() const
FuelGaugeOperationStatus(uint16_t value)
bool getIsCapacityAccumulationThrottled() const
bool getIsDischargeCycleCompliant() const
uint8_t getSecurityAccessLevel() const
bool getIsConfigUpdateMode() const
bool isDischarging() override
Check if battery is discharging.
static constexpr uint16_t BQ27220_SUB_CMD_HW_VERSION
static constexpr uint8_t BQ27220_REG_MAC_DATA_SUM
int getHardwareVersion()
Get the hardware version of the device.
static constexpr uint16_t BQ27220_SUB_CMD_BOARD_OFFSET
static constexpr uint8_t BQ27220_REG_STA_CHARGING_VOLTAGE
uint16_t getMaxLoadTimeToEmpty() const
Get the estimated time until the battery is empty at maximum load current discharge rate.
static constexpr uint8_t BQ27220_REG_STA_AVG_POWER
void reset() override
Reset the device.
static constexpr uint8_t BQ27220_REG_STA_STANDBY_TIME_TO_EMPTY
uint16_t getTimeToFull() override
Get the estimated time until the battery is fully charged.
uint16_t getChipID() override
Retrieve the unique identifier of the chip.
uint16_t getBTPDischargeSet() const
Get the BTP discharge set value.
uint16_t getStandbyTimeToEmpty() const
Get the estimated time until the battery is empty at standby discharge rate.
uint16_t getAtRateTimeToEmpty() const
Get the AtRateTimeToEmpty value.
static constexpr uint16_t BQ27220_SUB_CMD_SET_PROFILE_6
static constexpr uint16_t BQ27220_SUB_CMD_DEVICE_NUMBER
static constexpr uint8_t BQ27220_REG_STA_STANDBY_CURRENT
static constexpr uint16_t BQ27220_SUB_CMD_CTRL_STATUS
uint16_t getFullChargeCapacity() const
Get the full charge capacity of the battery.
uint16_t getStateOfHealth() const
Get the state of health value.
static constexpr uint16_t BQ27220_SUB_CMD_SET_PROFILE_5
uint16_t getStateOfCharge() override
Get the state of charge value.
static constexpr uint16_t BQ27220_SUB_CMD_FW_VERSION
static constexpr uint8_t BQ27220_REG_STA_NTC_TEMP
static constexpr uint8_t BQ27220_REG_STA_STATE_OF_HEALTH
static constexpr uint8_t BQ27220_REG_STA_BTP_DISC_SET
uint16_t getRawCoulombCount() const
Get the raw coulomb count value.
static constexpr uint16_t BQ27220_CHIP_ID
OperationConfig getOperationConfig()
Retrieve the operation configuration of the device.
static constexpr uint8_t BQ27220_REG_STA_BTP_CHARGE_SET
static constexpr uint16_t BQ27220_SUB_CMD_BAT_REMOVE
int16_t getAveragePower() const
Get the average power value.
static constexpr uint16_t BQ27220_SUB_CMD_SET_PROFILE_1
BatteryStatus getBatteryStatus() const
Get the battery status.
static constexpr uint16_t BQ27220_SUB_CMD_SEALED
uint16_t getRemainingCapacity() const
Get the remaining battery capacity.
static constexpr uint16_t BQ27220_SUB_CMD_CC_OFFSET
static constexpr uint8_t BQ27220_REG_ANALOG_COUNT
static constexpr uint8_t BQ27220_REG_STA_INTER_TEMP
uint16_t getCycleCount() const
Get the cycle count value.
static constexpr uint8_t BQ27220_REG_STA_BAT_VOLTAGE
static constexpr uint8_t BQ27220_REG_STA_AT_RATE
static constexpr uint8_t BQ27220_REG_STA_DESIGN_CAPACITY_LSB
uint16_t getRequestChargingCurrent() const
Get the requested charging current value.
static constexpr uint8_t BQ27220_REG_RAW_VOLTAGE
static constexpr uint16_t BQ27220_SUB_CMD_EXIT_CFG_UPDATE_REINIT
static constexpr uint8_t BQ27220_REG_STA_CYCLE_COUNT
static constexpr uint8_t BQ27220_REG_STA_DESIGN_CAPACITY_MSB
static constexpr uint16_t BQ27220_SUB_CMD_BAT_INSERT
bool refresh() override
Refresh the battery data by reading from the registers.
bool begin(SensorCommCustom::CustomCallback callback, SensorCommCustomHal::CustomHalCallback hal_callback)
static constexpr uint16_t BQ27220_SUB_CMD_RESET
static constexpr uint16_t BQ27220_SUB_CMD_CAL_TOGGLE
static constexpr uint8_t BQ27220_REG_MAC_BUFFER_END
static constexpr uint8_t BQ27220_REG_STA_COULOMB_COUNT
static constexpr uint8_t BQ27220_REG_STA_TIME_TO_EMPTY
int getFirmwareVersion()
Get the firmware version of the device.
static constexpr uint16_t BQ27220_SUB_CMD_SET_SNOOZE
static constexpr uint8_t BQ27220_REG_STA_FULL_CHARGE_CAPACITY
float getTemperature() override
Get the temperature value.
static constexpr uint8_t BQ27220_REG_MAC_BUFFER_START
static constexpr uint8_t BQ27220_REG_STA_MAX_LOAD_TO_EMPTY
static constexpr uint8_t BQ27220_REG_STA_REMAINING_CAPACITY
static constexpr uint16_t BQ27220_SUB_CMD_CLEAR_SNOOZE
static constexpr uint16_t BQ27220_SUB_CMD_RETURN_TO_ROM
uint16_t getAtRate() const
Get the AtRate value.
const uint8_t REGISTER_COUNT
static constexpr uint16_t BQ27220_SUB_CMD_EXIT_CAL
uint16_t getDesignCapacity() const
Get the design capacity value.
FuelGaugeOperationStatus getOperationStatus() const
Get the operation status.
static constexpr uint16_t BQ27220_SUB_CMD_ENTER_CAL
void setAccessKey(uint32_t key)
Set the access key for the device.
static constexpr uint16_t BQ27220_ROM_OPERATION_CONFIG_A
static constexpr uint16_t BQ27220_SUB_CMD_SET_PROFILE_2
uint16_t getRequestChargingVoltage() const
Get the requested charging voltage value.
static constexpr uint16_t BQ27220_SUB_CMD_OCV_CMD
static constexpr uint8_t BQ27220_REG_STA_DESIGN_CAPACITY
float getCurrent() override
Get the instantaneous current value.
float getInternalTemperature() const
Get the internal temperature value.
static constexpr uint16_t BQ27220_SUB_CMD_CC_OFFSET_SAVE
static constexpr uint8_t BQ27220_REG_STA_AT_RATE_TIME_TO_EMPTY
static constexpr uint8_t BQ27220_REG_STA_BAT_STATUS
static constexpr uint16_t BQ27220_SUB_CMD_EXIT_CFG_UPDATE
static constexpr uint16_t BQ27220_ROM_DESIGN_CAPACITY
static constexpr uint16_t BQ27220_SUB_CMD_ENTER_CFG_UPDATE
static constexpr uint8_t BQ27220_REG_STA_CHARGING_CURRENT
static constexpr uint8_t BQ27220_REG_ROM_START
int16_t getMaxLoadCurrent() const
Get the maximum load current value.
static constexpr uint8_t BQ27220_REG_RAW_CURRENT
static constexpr uint16_t BQ27220_SUB_CMD_SET_PROFILE_4
static constexpr uint16_t BQ27220_ROM_OPERATION_CONFIG_B
uint16_t getVoltage() override
Get the battery voltage value.
static constexpr uint8_t BQ27220_REG_STA_OPERATION_STATUS
static constexpr uint8_t BQ27220_REG_STA_STATE_OF_CHARGE
uint16_t getTimeToEmpty() override
Get the estimated time until the battery is empty.
bool setNewCapacity(uint16_t newDesignCapacity, uint16_t newFullChargeCapacity)
Set the new design capacity and full charge capacity of the battery.
static constexpr uint16_t BQ27220_SUB_CMD_SET_PROFILE_3
uint16_t getBTPChargeSet() const
Get the BTP charge set value.
static constexpr uint8_t BQ27220_REG_STA_MAX_LOAD_CURRENT
bool isCharging() override
Check if battery is charging.
static constexpr uint8_t BQ27220_REG_STA_TIME_TO_FULL
const uint8_t START_REGISTER
static constexpr uint8_t BQ27220_REG_MAC_DATA_LEN
static constexpr uint16_t BQ27220_ROM_FULL_CHARGE_CAPACITY
static constexpr uint8_t BQ27220_REG_STA_CURRENT
int16_t getStandbyCurrent() const
Get the standby current value.
Base class for battery gauge implementations.
bool begin(SensorCommCustom::CustomCallback cb, SensorCommCustomHal::CustomHalCallback hal_cb, uint8_t addr)
Initialize the sensor using custom callback interface.
bool isNonRemovableSet() const
Check if the non - removable option is set.
bool isIntBremEnabled() const
Check if the INT_BREM function is enabled.
bool isIntStateEnabled() const
Check if the INT_STATE function is enabled.
bool isTempsSet() const
Check if the external thermistor is selected for temperature measurement.
uint16_t getConfigB() const
Get the value in configuration register B.
bool canEnterSleep() const
Check if the fuel gauge can enter the SLEEP state.
bool isWakeEnEnabled() const
Check if the wake - up function is enabled.
bool isDefaultSealEnabled() const
Check if the default seal option is enabled (sealed after POR).
bool isIntBatLEnabled() const
Check if the INT_BATL function is enabled.
bool isWrtempEnabled() const
Check if the write temperature function is enabled.
int getPfcCfg() const
Get the Pin Function Code (PFC) mode.
bool isBlPupEnEnabled() const
Check if the battery insertion pin pull - up is enabled.
bool isIntFocvEnabled() const
Check if the INT_FOCV function is enabled.
OperationConfig(uint32_t registerValue)
Constructor for OperationConfig class.
uint16_t getConfigA() const
Get the value in configuration register A.
bool isIntPolHigh() const
Check if the INT_POL function is enabled (high - level polarity).
bool isBienableEnabled() const
Check if battery insertion detection is enabled.
int getWkTh0() const
Get the Wake - up threshold 0 value.
bool isBatgPolHigh() const
Check the BATT_GD pin polarity.
bool isBatgEnEnabled() const
Check if the BATT_GD function is enabled.
bool isIntOtEnabled() const
Check if the INT_OT function is enabled.
int getWkTh1() const
Get the Wake - up threshold 1 value.
bool isIntOcvEnabled() const
Check if the INT_OCV function is enabled.
bool isSlpwakechgEnabled() const
Check if the slpwakechg function is enabled.
uint32_t(*)(Operation op, void *param1, void *param2) CustomHalCallback
bool(*)(uint8_t addr, uint8_t reg, uint8_t *buf, size_t len, bool writeReg, bool isWrite) CustomCallback
int writeBuff(uint8_t *buf, size_t len)
int writeRegBuff(uint8_t reg, uint8_t *buf, size_t len)
int writeReg(uint8_t reg, uint8_t val)
int writeThenRead(const uint8_t *write_buffer, size_t write_len, uint8_t *read_buffer, size_t read_len)
int readRegBuff(uint8_t reg, uint8_t *buf, size_t len) const
uint32_t hal_callback(SensorCommCustomHal::Operation op, void *param1, void *param2)
constexpr uint32_t _bv(uint8_t b)
constexpr uint8_t _lowByte(uint16_t w)
constexpr uint8_t _highByte(uint16_t w)