#include "t_safety.h" #include #include #include #include "hal_i2c_acct.h" #include "hal_lock.h" #include "rail_cfg.h" #include "tasks.h" void t_safety_init(safety_snap_t *s) { assert(s != NULL); memset(s, 0, sizeof(*s)); /* 游标对齐到「现在」,否则第一圈会把启动期间(器件初始化)的事务算进来。 */ s->bus_cursor = hal_i2c_acct_bits(); } hal_err_t t_safety_step(safety_snap_t *s) { assert(s != NULL); s->cycles++; hal_err_t err = hal_lock_take(HAL_LOCK_I2C, T_SAFETY_LOCK_TIMEOUT_MS); if (err != HAL_OK) { /* 规矩 1:不死等。这一圈作废,20 ms 后重来。 */ s->skipped++; s->bus_us = hal_i2c_acct_window_us(&s->bus_cursor); return err; } hal_err_t first = HAL_OK; /* 五路 —— 地址查表,**不许算**(rail_cfg.h 那条禁令)。 */ for (int rail = 1; rail <= PHONERAIL_RAIL_COUNT; rail++) { ina226_vi_t vi; const hal_err_t e = ina226_read_vi(rail_cfg(rail)->ina_addr, &vi); s->rail_ok[rail - 1] = (e == HAL_OK); if (e == HAL_OK) { s->rail[rail - 1] = vi; /* 规矩 2:失败就留着上一圈的值,别清零 */ } else { s->i2c_errors++; if (first == HAL_OK) { first = e; } } } /* 第六片:输入侧。 */ { ina226_vi_t vi; const hal_err_t e = ina226_read_vi(INA226_ADDR_INPUT, &vi); s->input_ok = (e == HAL_OK); if (e == HAL_OK) { s->input = vi; } else { s->i2c_errors++; if (first == HAL_OK) { first = e; } } } /* PCA9555 的两个输入端口一次事务读完(自增指针)。 */ { pca9555_in_t in; const hal_err_t e = pca9555_read_inputs(&in); s->io_ok = (e == HAL_OK); if (e == HAL_OK) { s->io = in; } else { s->i2c_errors++; if (first == HAL_OK) { first = e; } } } hal_lock_give(HAL_LOCK_I2C); /* A10 的判据接在这里:越界**直接**写 EFUSE_EN / VBUS_EN(规矩 3), 而且要在放锁之后 —— 那两根线是 GPIO 直连,和 I²C 没关系, 拿着总线锁去操作引脚只会把别的任务多挡一会儿。 */ s->bus_us = hal_i2c_acct_window_us(&s->bus_cursor); return first; } uint32_t t_safety_budget_us(void) { /* 上面那一圈真正发出去的事务,逐条数: 6 片 INA226 × 2 次寄存器读(母线电压 + 电流) 1 次 PCA9555 读(一次事务读回两个输入端口) 每次都是「写 1 字节寄存器号 + 读 2 字节」的形状。 */ const uint32_t txns = INA226_COUNT * 2u + 1u; return (uint32_t)hal_i2c_bits_to_us((uint64_t)txns * hal_i2c_txn_bits(1, 2)); } uint32_t t_safety_load_permille(uint32_t bus_us, uint32_t period_ms) { if (period_ms == 0) { return 0; } return (uint32_t)(((uint64_t)bus_us * 1000ull) / ((uint64_t)period_ms * 1000ull)); } int t_safety_format(const safety_snap_t *s, char *buf, size_t len) { assert(s != NULL && buf != NULL && len > 0); const uint32_t period = task_desc(TASK_SAFETY)->period_ms; const uint32_t pm = t_safety_load_permille(s->bus_us, period); return snprintf(buf, len, "t_safety: cycles=%u skipped=%u i2c_err=%u bus=%u us/%u ms load=%u.%u%%", (unsigned)s->cycles, (unsigned)s->skipped, (unsigned)s->i2c_errors, (unsigned)s->bus_us, (unsigned)period, (unsigned)(pm / 10u), (unsigned)(pm % 10u)); }