Add persistent T-Beam charge voltage controls and report Mesh Solar limits

This commit is contained in:
mikecarper committed 2026-10-06 10:56:32 -07:00
1 parent 3177ccfafa
commit 613d9d7c43
15 files changed
+1275 -9

No files matched your search

+12
View File
@@ -239,6 +239,18 @@ public:
// True while a board can identify an active battery-charging source.
virtual bool isChargerActive() { return false; }
// Actual charger voltage, in millivolts. Battery reporting and protection
// thresholds are separate capabilities. A successful setter must verify
// hardware readback and persist the setting for the next boot.
virtual bool getBatteryChargeTarget(uint16_t& millivolts) { return false; }
virtual bool supportsBatteryChargeTarget(uint16_t millivolts) { return false; }
virtual bool setBatteryChargeTarget(uint16_t millivolts) { return false; }
virtual const char* getBatteryChargeTargetOptions() const { return nullptr; }
virtual bool batteryChargeTargetRestoreFailed() const { return false; }
virtual const char* getBatteryChargeTargetUnsupportedReason() const {
return "charge.voltage is not supported on this board";
}
// Optional, source-specific power detection. Boards that can distinguish a USB
// supply from a solar charger override these; defaults keep every other board
// unaffected (the generic CLI prints "n/a" when a capability is absent).
+101
View File
@@ -0,0 +1,101 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
namespace mesh {
namespace power {
// Parse volts without floating-point rounding, signs, exponents, or ignored
// suffixes. Millivolt precision keeps unsupported targets from being rounded
// into a supported charger setting.
inline bool parseChargeVolts(const char* value, uint16_t& millivolts) {
if (!value || *value < '0' || *value > '9') return false;
uint32_t whole = 0, fraction = 0;
while (*value >= '0' && *value <= '9') {
whole = whole * 10 + (*value++ - '0');
if (whole > 65) return false;
}
unsigned digits = 0;
if (*value == '.') {
++value;
while (*value >= '0' && *value <= '9') {
if (++digits > 3) return false;
fraction = fraction * 10 + (*value++ - '0');
}
if (digits == 0) return false;
}
while (*value == ' ' || *value == '\t') ++value;
if (*value) return false;
while (digits++ < 3) fraction *= 10;
const uint32_t result = whole * 1000 + fraction;
if (result > 65535) return false;
millivolts = static_cast<uint16_t>(result);
return true;
}
inline bool chargeCommandKey(const char* text, const char* key) {
const size_t length = strlen(key);
return strncmp(text, key, length) == 0
&& (text[length] == 0 || text[length] == ' ' || text[length] == '\t');
}
// Shared by infrastructure, Companion, and Terminal Chat. Board code owns
// hardware validation and persistence; the CLI must not alter BMS protection
// settings to simulate an unsupported charger voltage.
template <typename Board>
bool handleBatteryChargeCommand(Board& board, const char* command,
char* reply, size_t reply_capacity) {
if (!command || !reply || !reply_capacity) return false;
while (*command == ' ' || *command == '\t') ++command;
const bool get = strncmp(command, "get ", 4) == 0;
const bool set = strncmp(command, "set ", 4) == 0;
if (!get && !set) return false;
const char* key = command + 4;
const bool options = get && chargeCommandKey(key, "charge.voltage.options");
if (!options && !chargeCommandKey(key, "charge.voltage")) return false;
const char* value = key + strlen(options ? "charge.voltage.options" : "charge.voltage");
while (*value == ' ' || *value == '\t') ++value;
if (get && *value) {
snprintf(reply, reply_capacity, "Error: usage get charge.voltage[.options]");
return true;
}
const char* targets = board.getBatteryChargeTargetOptions();
if (!targets) {
snprintf(reply, reply_capacity, "Error: %s", board.getBatteryChargeTargetUnsupportedReason());
return true;
}
if (options) {
snprintf(reply, reply_capacity, "> %s V", targets);
return true;
}
uint16_t millivolts = 0;
if (get) {
if (!board.getBatteryChargeTarget(millivolts)) {
snprintf(reply, reply_capacity, "Error: charger read failed");
} else {
snprintf(reply, reply_capacity, "> %u.%03u V%s",
static_cast<unsigned>(millivolts / 1000),
static_cast<unsigned>(millivolts % 1000),
board.batteryChargeTargetRestoreFailed() ? " (boot restore failed)" : "");
}
return true;
}
if (!parseChargeVolts(value, millivolts)) {
snprintf(reply, reply_capacity, "Error: usage set charge.voltage <volts>");
} else if (!board.supportsBatteryChargeTarget(millivolts)) {
snprintf(reply, reply_capacity, "Error: unsupported target; allowed %s V", targets);
} else if (!board.setBatteryChargeTarget(millivolts)) {
snprintf(reply, reply_capacity, "Error: charge target not confirmed saved; check get charge.voltage");
} else {
snprintf(reply, reply_capacity, "OK - charge.voltage %u.%03u V (saved)",
static_cast<unsigned>(millivolts / 1000),
static_cast<unsigned>(millivolts % 1000));
}
return true;
}
} // namespace power
} // namespace mesh
+2
View File
@@ -4,6 +4,7 @@
#include "UsbLoggingWatchdog.h"
#include "HilStartupTrace.h"
#include <helpers/ui/DisplayPowerSettings.h>
#include <helpers/BatteryChargeCLI.h>
#include "CLICommandUtils.h"
#include "GpsPowerPolicy.h"
#include "FloodAdvertCLI.h"
@@ -2840,6 +2841,7 @@ uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) {
void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
PrefsSaveReplyGuard save_reply(_prefs_save_failures, reply);
mesh::cli::normalizeCommandVerb(command);
if (mesh::power::handleBatteryChargeCommand(*_board, command, reply, 160)) return;
if (mesh::handleUsbLoggingWatchdogCommand(command, reply, 160)) return;
if (handleManagementCommand(command, reply)) return;
if (mesh::wireless::control().handle(command, reply, 160, millis(),
+120 -7
View File
@@ -2,15 +2,19 @@
#include <Arduino.h>
#include "TBeamBoard.h"
#include "TBeamChargeTarget.h"
#include <nvs.h>
//#include <RadioLib.h>
uint32_t deviceOnline = 0x00;
#if !defined(PORTABLE_MQTT_OBSERVER) || defined(TBEAM_SUPREME_SX1262)
bool pmuInterrupt;
static void setPmuFlag()
{
pmuInterrupt = true;
}
#endif
void TBeamBoard::begin() {
@@ -26,7 +30,9 @@ void TBeamBoard::begin() {
Wire.begin(PIN_BOARD_SDA, PIN_BOARD_SCL);
#endif
power_init();
charge_pmu_ready = power_init();
charge_target_restore_failed = !charge_pmu_ready;
if (charge_pmu_ready) restoreBatteryChargeTarget();
//Configure user button
pinMode(PIN_USER_BTN, INPUT);
@@ -39,8 +45,8 @@ void TBeamBoard::begin() {
esp_reset_reason_t reason = esp_reset_reason();
if (reason == ESP_RST_DEEPSLEEP) {
long wakeup_source = esp_sleep_get_ext1_wakeup_status();
if (wakeup_source & (1 << P_LORA_DIO_1)) { // received a LoRa packet (while in deep sleep)
uint64_t wakeup_source = esp_sleep_get_ext1_wakeup_status();
if (wakeup_source & (1ULL << P_LORA_DIO_1)) { // received a LoRa packet (while in deep sleep)
startup_reason = BD_STARTUP_RX_PACKET;
}
@@ -139,13 +145,14 @@ void TBeamBoard::printPMU()
}
#endif
#if defined(PORTABLE_MQTT_OBSERVER) && !defined(TBEAM_SUPREME_SX1262)
static bool pmuRead(uint8_t reg, uint8_t& value) {
PMU_WIRE_PORT.beginTransmission(I2C_PMU_ADD);
PMU_WIRE_PORT.write(reg);
if (PMU_WIRE_PORT.endTransmission(false) != 0 ||
PMU_WIRE_PORT.requestFrom(I2C_PMU_ADD, 1) != 1) return false;
value = PMU_WIRE_PORT.read();
const int received = PMU_WIRE_PORT.read();
if (received < 0) return false;
value = static_cast<uint8_t>(received);
return true;
}
@@ -156,6 +163,111 @@ static bool pmuWrite(uint8_t reg, uint8_t value) {
return PMU_WIRE_PORT.endTransmission() == 0;
}
namespace {
struct ChargePmuIO {
bool read(uint8_t reg, uint8_t& value) { return pmuRead(reg, value); }
bool write(uint8_t reg, uint8_t value) { return pmuWrite(reg, value); }
};
class ChargeTargetStore {
nvs_handle_t handle = 0;
bool opened = false;
bool absent_namespace = false;
static constexpr const char* key = "target_mv";
public:
ChargeTargetStore(const char* name, bool read_only) {
if (!name) return;
const esp_err_t result = nvs_open(name, read_only ? NVS_READONLY : NVS_READWRITE,
&handle);
opened = result == ESP_OK;
absent_namespace = read_only && result == ESP_ERR_NVS_NOT_FOUND;
}
~ChargeTargetStore() { if (opened) nvs_close(handle); }
bool read(uint16_t& value, bool& present) {
if (absent_namespace) {
value = 0;
present = false;
return true;
}
if (!opened) return false;
const esp_err_t result = nvs_get_u16(handle, key, &value);
if (result == ESP_ERR_NVS_NOT_FOUND) {
value = 0;
present = false;
return true;
}
if (result != ESP_OK) return false;
present = true;
return true;
}
bool write(uint16_t value) {
if (!opened || nvs_set_u16(handle, key, value) != ESP_OK ||
nvs_commit(handle) != ESP_OK) return false;
uint16_t actual = 0;
bool present = false;
return read(actual, present) && present && actual == value;
}
bool erase() {
if (!opened) return false;
const esp_err_t result = nvs_erase_key(handle, key);
if (result != ESP_OK && result != ESP_ERR_NVS_NOT_FOUND) return false;
if (result == ESP_OK && nvs_commit(handle) != ESP_OK) return false;
uint16_t actual = 0;
bool present = false;
return read(actual, present) && !present;
}
};
} // namespace
uint8_t TBeamBoard::getChargeTargetModel() const {
if (!charge_pmu_ready) return 0;
#if defined(PORTABLE_MQTT_OBSERVER) && !defined(TBEAM_SUPREME_SX1262)
return pmu_model;
#else
if (!PMU) return 0;
if (PMU->getChipModel() == XPOWERS_AXP192) return mesh::tbeam_charge::AXP192;
if (PMU->getChipModel() == XPOWERS_AXP2101) return mesh::tbeam_charge::AXP2101;
return 0;
#endif
}
bool TBeamBoard::getBatteryChargeTarget(uint16_t& millivolts) {
ChargePmuIO io;
return mesh::tbeam_charge::read(io, getChargeTargetModel(), millivolts);
}
bool TBeamBoard::supportsBatteryChargeTarget(uint16_t millivolts) {
return mesh::tbeam_charge::supports(getChargeTargetModel(), millivolts);
}
const char* TBeamBoard::getBatteryChargeTargetOptions() const {
return mesh::tbeam_charge::options(getChargeTargetModel());
}
bool TBeamBoard::setBatteryChargeTarget(uint16_t millivolts) {
const uint8_t model = getChargeTargetModel();
if (!mesh::tbeam_charge::supports(model, millivolts)) return false;
ChargePmuIO io;
ChargeTargetStore store(mesh::tbeam_charge::storeNamespace(model), false);
const bool success = mesh::tbeam_charge::setPersistent(io, store, model, millivolts);
if (success) charge_target_restore_failed = false;
return success;
}
void TBeamBoard::restoreBatteryChargeTarget() {
const uint8_t model = getChargeTargetModel();
ChargePmuIO io;
ChargeTargetStore store(mesh::tbeam_charge::storeNamespace(model), true);
#if defined(PORTABLE_MQTT_OBSERVER) && !defined(TBEAM_SUPREME_SX1262)
const bool apply_fresh_default = false;
#else
const bool apply_fresh_default = true;
#endif
charge_target_restore_failed =
!mesh::tbeam_charge::configureBoot(io, store, model, apply_fresh_default);
}
#if defined(PORTABLE_MQTT_OBSERVER) && !defined(TBEAM_SUPREME_SX1262)
static bool pmuUpdate(uint8_t reg, uint8_t clear_mask, uint8_t set_mask) {
uint8_t value;
return pmuRead(reg, value) && pmuWrite(reg, (value & ~clear_mask) | set_mask);
@@ -163,7 +275,10 @@ static bool pmuUpdate(uint8_t reg, uint8_t clear_mask, uint8_t set_mask) {
bool TBeamBoard::power_init() {
PMU_WIRE_PORT.begin(PIN_BOARD_SDA, PIN_BOARD_SCL);
pmu_model = 0;
if (!pmuRead(0x03, pmu_model)) return false;
if (pmu_model != mesh::tbeam_charge::AXP192 &&
pmu_model != mesh::tbeam_charge::AXP2101) return false;
if (pmu_model == 0x4A) {
// AXP2101: ALDO2 and ALDO3 at 3.3 V, plus battery voltage ADC.
@@ -234,7 +349,6 @@ bool TBeamBoard::power_init()
PMU->disableIRQ(XPOWERS_AXP192_ALL_IRQ); //Disable PMU IRQ
PMU->setChargerConstantCurr(XPOWERS_AXP192_CHG_CUR_450MA); //Set battery charging current
PMU->setChargeTargetVoltage(XPOWERS_AXP192_CHG_VOL_4V2); //Set battery charge-stop voltage
}
else if(PMU->getChipModel() == XPOWERS_AXP2101){
#ifdef TBEAM_SUPREME_SX1262
@@ -315,7 +429,6 @@ bool TBeamBoard::power_init()
PMU->disableIRQ(XPOWERS_AXP2101_ALL_IRQ); //Disable all PMU interrupts
PMU->setChargerConstantCurr(XPOWERS_AXP2101_CHG_CUR_500MA); //Set battery charging current to 500mA
PMU->setChargeTargetVoltage(XPOWERS_AXP2101_CHG_VOL_4V2); //Set battery charging cutoff voltage to 4.2V
}
+13 -2
View File
@@ -118,6 +118,10 @@ enum {
};
bool power_init();
bool charge_pmu_ready = false;
bool charge_target_restore_failed = false;
uint8_t getChargeTargetModel() const;
void restoreBatteryChargeTarget();
//void radiotype_detect();
public:
@@ -127,6 +131,13 @@ public:
void scanDevices(TwoWire *w);
#endif
void begin();
bool getBatteryChargeTarget(uint16_t& millivolts) override;
bool supportsBatteryChargeTarget(uint16_t millivolts) override;
bool setBatteryChargeTarget(uint16_t millivolts) override;
const char* getBatteryChargeTargetOptions() const override;
bool batteryChargeTargetRestoreFailed() const override {
return charge_target_restore_failed;
}
#ifndef TBEAM_SUPREME_SX1262
void onBeforeTransmit() override{
@@ -138,9 +149,9 @@ public:
#endif
uint16_t getBattMilliVolts(){
if (!charge_pmu_ready) return 0;
#if defined(PORTABLE_MQTT_OBSERVER) && !defined(TBEAM_SUPREME_SX1262)
uint8_t high_reg = pmu_model == 0x4A ? 0x34 : 0x78;
uint8_t low_reg = high_reg + 1;
PMU_WIRE_PORT.beginTransmission(I2C_PMU_ADD);
PMU_WIRE_PORT.write(high_reg);
if (PMU_WIRE_PORT.endTransmission(false) != 0 ||
@@ -150,7 +161,7 @@ public:
if (pmu_model == 0x4A) return ((high & 0x1F) << 8) | low;
return (uint16_t)((((high << 4) | (low & 0x0F)) * 11) / 10);
#else
return PMU->getBattVoltage();
return PMU ? PMU->getBattVoltage() : 0;
#endif
}
+151
View File
@@ -0,0 +1,151 @@
#pragma once
#include <stdint.h>
namespace mesh {
namespace tbeam_charge {
enum : uint8_t { AXP192 = 0x03, AXP2101 = 0x4A };
struct Setting {
uint8_t reg;
uint8_t mask;
uint8_t bits;
};
// These are the discrete hardware targets, not a voltage range. In particular,
// neither PMU supports the 3.65 V termination voltage used by LiFePO4 cells.
inline bool encode(uint8_t model, uint16_t millivolts, Setting& setting) {
if (model == AXP192) {
setting.reg = 0x33;
setting.mask = 0x60;
switch (millivolts) {
case 4100: setting.bits = 0x00; return true;
case 4150: setting.bits = 0x20; return true;
case 4200: setting.bits = 0x40; return true;
case 4360: setting.bits = 0x60; return true;
default: return false;
}
}
if (model == AXP2101) {
setting.reg = 0x64;
setting.mask = 0x07;
switch (millivolts) {
case 4000: setting.bits = 1; return true;
case 4100: setting.bits = 2; return true;
case 4200: setting.bits = 3; return true;
case 4350: setting.bits = 4; return true;
case 4400: setting.bits = 5; return true;
default: return false;
}
}
return false;
}
inline bool supports(uint8_t model, uint16_t millivolts) {
Setting setting;
return encode(model, millivolts, setting);
}
inline const char* options(uint8_t model) {
if (model == AXP192) return "4.10,4.15,4.20,4.36";
if (model == AXP2101) return "4.00,4.10,4.20,4.35,4.40";
return nullptr;
}
inline const char* storeNamespace(uint8_t model) {
if (model == AXP192) return "tbeam192_chg";
if (model == AXP2101) return "tbeam2101_chg";
return nullptr;
}
inline bool decode(uint8_t model, uint8_t value, uint16_t& millivolts) {
if (model == AXP192) {
static const uint16_t targets[] = {4100, 4150, 4200, 4360};
millivolts = targets[(value & 0x60) >> 5];
return true;
}
if (model == AXP2101) {
static const uint16_t targets[] = {4000, 4100, 4200, 4350, 4400};
const uint8_t code = value & 0x07;
if (code < 1 || code > 5) return false;
millivolts = targets[code - 1];
return true;
}
return false;
}
template<typename IO>
bool read(IO& io, uint8_t model, uint16_t& millivolts) {
Setting setting;
if (!encode(model, 4200, setting)) return false;
uint8_t detected, value;
if (!io.read(0x03, detected) || detected != model ||
!io.read(setting.reg, value)) return false;
return decode(model, value, millivolts);
}
template<typename IO>
bool write(IO& io, uint8_t model, uint16_t millivolts) {
Setting setting;
if (!encode(model, millivolts, setting)) return false;
uint8_t detected, previous;
if (!io.read(0x03, detected) || detected != model ||
!io.read(setting.reg, previous)) return false;
const uint8_t value = (previous & ~setting.mask) | setting.bits;
if (value != previous && !io.write(setting.reg, value)) return false;
uint8_t actual;
return io.read(setting.reg, actual) && actual == value;
}
// Store reads distinguish an absent key from an I/O failure; writes include
// commit and readback. The caller must keep the store open for the transaction.
template<typename IO, typename Store>
bool setPersistent(IO& io, Store& store, uint8_t model, uint16_t millivolts) {
if (!supports(model, millivolts)) return false;
uint16_t previousHardware, previousStored = 0;
bool existed = false;
if (!read(io, model, previousHardware) ||
!store.read(previousStored, existed)) return false;
if (!write(io, model, millivolts)) {
// A failed readback may follow a successful physical write.
write(io, model, previousHardware);
return false;
}
if (existed && previousStored == millivolts) return true;
if (store.write(millivolts)) return true;
// Restore persistence before restoring hardware, so a successful rollback
// cannot leave the requested target to be silently reapplied on next boot.
const bool restoredStore = existed ? store.write(previousStored) : store.erase();
if (restoredStore) {
write(io, model, previousHardware);
} else {
// A failed commit has an uncertain durable result. Match a readable saved
// setting where possible; otherwise keep the last verified requested
// hardware target and report failure, never pretend the state is unchanged.
uint16_t stored = 0;
bool present = false;
if (store.read(stored, present)) {
if (!present) write(io, model, previousHardware);
else if (supports(model, stored)) write(io, model, stored);
}
}
return false;
}
template<typename IO, typename Store>
bool configureBoot(IO& io, Store& store, uint8_t model, bool apply_fresh_default) {
uint16_t stored = 0;
bool present = false;
if (!store.read(stored, present)) return false;
// A missing preference is the only condition that permits the existing full
// driver's 4.2 V default. Unreadable/invalid saved settings must never raise
// the charger target; preserve the PMU state and surface a boot failure.
if (!present) return !apply_fresh_default || write(io, model, 4200);
return supports(model, stored) && write(io, model, stored);
}
} // namespace tbeam_charge
} // namespace mesh