3 changed files with 200 additions and 208 deletions
@@ -19,9 +19,11 @@
#include "ql_atcmd.h" #include "ql_atcmd.h"
#include "app_inc.h" #include "app_inc.h"
#include "ql_uart.h" #include "ql_uart.h"
#include "ql_application.h" #include "ql_application.h"
#include "ql_log.h" #include "ql_log.h"
#include "hal_api.h" #include "ql_adc.h"
#include "ql_power.h"
#include "hal_api.h"
// 电量阈值定义 // 电量阈值定义
#define BAT_VOLTAGE_100 4200 #define BAT_VOLTAGE_100 4200
@@ -36,25 +38,24 @@
#define BAT_VOLTAGE_10 3550 #define BAT_VOLTAGE_10 3550
#define BAT_VOLTAGE_MIN 3500 #define BAT_VOLTAGE_MIN 3500
// ========== 新增:10分钟电压历史记录用于判断充放电状态 ========== #define BAT_LOW_WARN_MV 3550
#define VOLTAGE_HISTORY_SIZE 60 // 10分钟 = 60个10秒采样点 #define BAT_LOW_PROBE_EXIT_MV 3600
#define VOLTAGE_RISE_THRESHOLD 15 // 10分钟内上升超过15mV判定为充电 #define BAT_SHUTDOWN_MV 3500
#define VOLTAGE_DROP_THRESHOLD 15 // 10分钟内下降超过15mV判定为放电 #define BAT_VALID_MIN_MV 2500
#define VOLTAGE_STABLE_RANGE 10 // 变化在±10mV内判定为稳定 #define BAT_VALID_MAX_MV 5000
#define BAT_SHUTDOWN_CONFIRM_COUNT 3
#define BAT_NORMAL_SAMPLE_CALLS 6
unsigned short g_vbat_vol = 0; unsigned short g_vbat_vol = 0;
unsigned short vbat_sample[6] = {0}; // 修改:样本数改为6 unsigned short vbat_sample[6] = {0}; // 修改:样本数改为6
unsigned char battery_first_update_flag = 0; unsigned char battery_first_update_flag = 0;
static unsigned short g_vbat_vol_last = 0; static bat_level_t g_bat_level_last = BAT_LEVEL_100;
static bat_level_t g_bat_level_last = BAT_LEVEL_100; static unsigned char g_bat_level_valid = 0;
static unsigned char g_low_voltage_count = 0;
// ========== 新增:电压历史记录环形缓冲区 ========== static unsigned char g_low_probe_active = 0;
static unsigned short g_voltage_history[VOLTAGE_HISTORY_SIZE] = {0}; static unsigned char g_low_power_warned = 0;
static unsigned char g_history_index = 0;
static unsigned char g_history_count = 0; // 已记录的有效点数
static int g_charging_state = 0; // 当前判定的充电状态:1-充电, 0-未充电
static unsigned char g_charging_stable_cnt = 0; // 状态稳定计数
bat_level_t calc_battery_level(uint16_t voltage_mv) bat_level_t calc_battery_level(uint16_t voltage_mv)
{ {
@@ -71,101 +72,64 @@ bat_level_t calc_battery_level(uint16_t voltage_mv)
else return BAT_LEVEL_0; else return BAT_LEVEL_0;
} }
/** bat_level_t battery_get_level(void)
* @brief 基于10分钟电压历史判断充放电状态 {
* @return 1-充电中, 0-未充电/放电 return g_bat_level_valid ? g_bat_level_last : calc_battery_level(g_vbat_vol);
*/ }
static int detect_charging_by_trend(void)
{ static bat_level_t limit_level_jump(bat_level_t raw_level)
if (g_history_count < VOLTAGE_HISTORY_SIZE) { {
printf("[BAT] history not full (%d/%d), keep state:%d\r\n", bat_level_t result = g_bat_level_last;
g_history_count, VOLTAGE_HISTORY_SIZE, g_charging_state);
return g_charging_state; if (!g_bat_level_valid) {
} g_bat_level_valid = 1;
g_bat_level_last = raw_level;
unsigned char old_index = (g_history_index + 1) % VOLTAGE_HISTORY_SIZE; printf("[BAT] first level initialized: %d\r\n", raw_level);
unsigned short vbat_now = g_voltage_history[(g_history_index + VOLTAGE_HISTORY_SIZE - 1) % VOLTAGE_HISTORY_SIZE]; return raw_level;
unsigned short vbat_10min_ago = g_voltage_history[old_index]; }
short delta = (short)vbat_now - (short)vbat_10min_ago; if (raw_level > g_bat_level_last) {
result = (raw_level >= g_bat_level_last + BAT_LEVEL_10)
printf("[BAT] trend: now=%d, 10min_ago=%d, delta=%d\r\n", ? (bat_level_t)(g_bat_level_last + BAT_LEVEL_10)
vbat_now, vbat_10min_ago, delta); : raw_level;
} else if (raw_level < g_bat_level_last) {
int new_state = g_charging_state; result = (raw_level <= g_bat_level_last - BAT_LEVEL_10)
? (bat_level_t)(g_bat_level_last - BAT_LEVEL_10)
if (delta > VOLTAGE_RISE_THRESHOLD) { : raw_level;
new_state = 1; }
printf("[BAT] trend: CHARGING detected (rise %dmV)\r\n", delta);
} printf("[BAT] level update: last=%d raw=%d result=%d\r\n",
else if (delta < -VOLTAGE_DROP_THRESHOLD) { g_bat_level_last, raw_level, result);
new_state = 0; g_bat_level_last = result;
printf("[BAT] trend: DISCHARGING detected (drop %dmV)\r\n", -delta); return result;
} }
else {
printf("[BAT] trend: STABLE (delta %dmV), keep state:%d\r\n", delta, g_charging_state); static void battery_check_critical_voltage(unsigned short voltage_mv)
} {
if (voltage_mv < BAT_LOW_WARN_MV) {
if (new_state == g_charging_state) { g_low_probe_active = 1;
g_charging_stable_cnt = 0; } else if (voltage_mv >= BAT_LOW_PROBE_EXIT_MV) {
} else { g_low_probe_active = 0;
g_charging_stable_cnt++; }
if (g_charging_stable_cnt < 3) {
printf("[BAT] state change pending: %d -> %d (%d/3)\r\n", if (voltage_mv < BAT_SHUTDOWN_MV) {
g_charging_state, new_state, g_charging_stable_cnt); if (g_low_voltage_count < BAT_SHUTDOWN_CONFIRM_COUNT) {
return g_charging_state; g_low_voltage_count++;
} }
g_charging_stable_cnt = 0;
printf("[BAT] state changed: %d -> %d (confirmed)\r\n", g_charging_state, new_state); printf("[BAT] critical voltage:%d, confirm:%d/%d\r\n",
} voltage_mv, g_low_voltage_count, BAT_SHUTDOWN_CONFIRM_COUNT);
return new_state; if (g_low_voltage_count >= BAT_SHUTDOWN_CONFIRM_COUNT) {
} printf("[BAT] critical voltage confirmed, poweroff now\r\n");
app_play_tips_file(15);
static void update_voltage_history(unsigned short voltage) ql_rtos_task_sleep_s(5);
{ ql_power_down(1);
g_voltage_history[g_history_index] = voltage; }
g_history_index = (g_history_index + 1) % VOLTAGE_HISTORY_SIZE; } else {
if (g_history_count < VOLTAGE_HISTORY_SIZE) { g_low_voltage_count = 0;
g_history_count++; }
} }
}
static int is_charging(void)
{
// 如有硬件检测引脚,可优先使用
return detect_charging_by_trend();
}
static bat_level_t limit_level_jump(bat_level_t raw_level, bat_level_t last_level, int charging)
{
bat_level_t result = last_level;
if (charging) {
if (raw_level > last_level) {
if (raw_level - last_level == 1) {
result = raw_level;
printf("[BAT] level up (charging): %d -> %d\r\n", last_level, raw_level);
} else if (raw_level - last_level > 1) {
result = (bat_level_t)(last_level + 1);
printf("[BAT] level up limited (charging): %d -> %d (raw:%d)\r\n",
last_level, result, raw_level);
}
}
} else {
if (raw_level < last_level) {
if (last_level - raw_level == 1) {
result = raw_level;
printf("[BAT] level down (discharging): %d -> %d\r\n", last_level, raw_level);
} else if (last_level - raw_level > 1) {
result = (bat_level_t)(last_level - 1);
printf("[BAT] level down limited (discharging): %d -> %d (raw:%d)\r\n",
last_level, result, raw_level);
}
}
}
return result;
}
/* 修改后的 battery_check:分阶段采样,采样窗口为6次 */ /* 修改后的 battery_check:分阶段采样,采样窗口为6次 */
void battery_check(void) void battery_check(void)
@@ -174,15 +138,17 @@ void battery_check(void)
static unsigned char sample_idx = 0; // 当前已采集样本数 (0~5) static unsigned char sample_idx = 0; // 当前已采集样本数 (0~5)
static unsigned short sample_buf[6] = {0}; // 本地缓冲(也可用全局 vbat_sample,此处直接用局部) static unsigned short sample_buf[6] = {0}; // 本地缓冲(也可用全局 vbat_sample,此处直接用局部)
call_count++; call_count++;
/* 判断本次是否执行ADC采样 */ /* 判断本次是否执行ADC采样 */
unsigned char do_sample = 0; unsigned char do_sample = 0;
if (call_count <= 24) { // 开机2分钟内 (24次*5s=120s) if (call_count <= 24) { // 开机2分钟内 (24次*5s=120s)
do_sample = 1; do_sample = 1;
} else { } else if (g_low_probe_active) {
// 2分钟后,每36次调用采样一次 (36*5s=180s=3分钟) do_sample = 1; // 低电风险时每5秒快速确认
if ((call_count - 25) % 36 == 0) { } else {
// 2分钟后,每6次调用采样一次 (6*5s=30秒)
if (call_count % BAT_NORMAL_SAMPLE_CALLS == 0) {
do_sample = 1; do_sample = 1;
} }
} }
@@ -195,9 +161,21 @@ void battery_check(void)
u16 vbat_vol = 0; u16 vbat_vol = 0;
ql_adc_onff(1); ql_adc_onff(1);
ql_rtos_task_sleep_ms(5); ql_rtos_task_sleep_ms(5);
ql_adc_onff(0); ql_adc_onff(0);
vbat_vol = ql_get_battery_vol(); vbat_vol = ql_get_battery_vol();
sample_buf[sample_idx] = vbat_vol;
printf("[BAT][SAMPLE] voltage=%d, low_probe=%d\r\n",
vbat_vol, g_low_probe_active);
if (vbat_vol < BAT_VALID_MIN_MV || vbat_vol > BAT_VALID_MAX_MV) {
printf("[BAT] invalid voltage sample ignored:%d\r\n", vbat_vol);
g_low_voltage_count = 0;
return;
}
battery_check_critical_voltage(vbat_vol);
sample_buf[sample_idx] = vbat_vol;
sample_idx++; sample_idx++;
/* 当收集满6个样本时进行平均处理 */ /* 当收集满6个样本时进行平均处理 */
@@ -215,47 +193,29 @@ void battery_check(void)
vol_all = vol_all - min - max; vol_all = vol_all - min - max;
vbat_vol = vol_all / 4; // 6个样本去掉最大最小,剩余4个平均 vbat_vol = vol_all / 4; // 6个样本去掉最大最小,剩余4个平均
/* 更新电压历史(用于充电趋势判断) */ g_vbat_vol = vbat_vol;
update_voltage_history(vbat_vol); printf("vbat_vol:%d\r\n", g_vbat_vol);
/* 判断充电状态 */ /* 计算电量等级并限制跳变 */
int charging = is_charging(); bat_level_t raw_level = calc_battery_level(g_vbat_vol);
g_charging_state = charging; bat_level_t level = limit_level_jump(raw_level);
/* 非充电状态下,电压不允许上升 */ printf("[BAT] raw_level:%d, limited_level:%d\r\n",
if (!charging) { raw_level, level);
if (g_vbat_vol_last > 0 && vbat_vol > g_vbat_vol_last) {
printf("[BAT] voltage rise blocked: %d -> %d (not charging)\r\n",
g_vbat_vol_last, vbat_vol);
vbat_vol = g_vbat_vol_last;
}
}
g_vbat_vol = vbat_vol;
g_vbat_vol_last = vbat_vol;
printf("vbat_vol:%d, charging:%d\r\n", g_vbat_vol, charging);
/* 计算电量等级并限制跳变 */
bat_level_t raw_level = calc_battery_level(g_vbat_vol);
bat_level_t level = limit_level_jump(raw_level, g_bat_level_last, charging);
g_bat_level_last = level;
printf("[BAT] raw_level:%d, limited_level:%d, charging:%d\r\n",
raw_level, level, charging);
if (battery_first_update_flag == 0) { if (battery_first_update_flag == 0) {
battery_first_update_flag = 1; battery_first_update_flag = 1;
} }
/* 低电量处理 */ /* 极低电关机由原始电压独立处理,普通低电提示只播放一次 */
if (level == BAT_LEVEL_0) { if (level <= BAT_LEVEL_10) {
printf("poweroff now\r\n"); if (!g_low_power_warned) {
app_play_tips_file(15); g_low_power_warned = 1;
ql_rtos_task_sleep_s(5); app_play_tips_file(14);
ql_power_down(1); }
} else if (level <= BAT_LEVEL_10) { } else if (level >= BAT_LEVEL_20) {
app_play_tips_file(14); g_low_power_warned = 0;
} }
sample_idx = 0; // 重置样本索引,准备下一轮采集 sample_idx = 0; // 重置样本索引,准备下一轮采集
} }
@@ -36,7 +36,7 @@ const char *mp3_file[] ={
"ai_active_zh.mp3",//18 "ai_active_zh.mp3",//18
}; };
//http://175.24.73.253/assets/roles/zhuli/zh/tts_error.mp3 //http://banban.api.talkingq.com:8080/assets/roles/banban/tts_error.mp3
//#define PCM_FILE "http://47.113.99.138:7050/output_16k.pcm" //#define PCM_FILE "http://47.113.99.138:7050/output_16k.pcm"
@@ -194,7 +194,7 @@ void app_file_check_download(void)
if(ql_access(filename_buff, 0)!=0){ if(ql_access(filename_buff, 0)!=0){
printf("downing mp3 file %d,%s\r\n", index,filename_buff); printf("downing mp3 file %d,%s\r\n", index,filename_buff);
down_loop: down_loop:
sprintf(url_buff, "http://101.35.224.118:8080/assets/roles/banban/%s", mp3_file[index]); sprintf(url_buff, "http://banban.api.talkingq.com:8080/assets/roles/banban/%s", mp3_file[index]);
ret = http_file_download(url_buff); ret = http_file_download(url_buff);
if(ret!=0&&cnt++<3) goto down_loop; if(ret!=0&&cnt++<3) goto down_loop;
@@ -72,7 +72,8 @@ int g_nfc_bind_status = 0;
extern u8 g_cur_volume; extern u8 g_cur_volume;
extern u8 g_pre_volume; extern u8 g_pre_volume;
extern unsigned short g_vbat_vol; extern unsigned short g_vbat_vol;
extern bat_level_t battery_get_level(void);
extern sleep_config_t g_sleep_cfg; extern sleep_config_t g_sleep_cfg;
extern uint8_t g_sleep_config_valid; extern uint8_t g_sleep_config_valid;
@@ -368,7 +369,7 @@ int parse_event_response(const char *json_str, response_t *resp)
} }
else { else {
// ===== 原有逻辑: NFC事件 - 动态查找 url_x 字段 ===== // ===== 原有逻辑: NFC事件 - 动态查找 url_x 字段 =====
for (int i = 1; i <= 5; i++) { for (int i = 1; i <= 10; i++) {
char key[16]; char key[16];
snprintf(key, sizeof(key), "url_%d", i); snprintf(key, sizeof(key), "url_%d", i);
cJSON *url = cJSON_GetObjectItem(params, key); cJSON *url = cJSON_GetObjectItem(params, key);
@@ -391,11 +392,12 @@ int parse_event_response(const char *json_str, response_t *resp)
/* [FIX] 安全处理 topic 名称,避免越界访问 */ /* [FIX] 安全处理 topic 名称,避免越界访问 */
static void messageArrived(MessageData* data) static void messageArrived(MessageData* data)
{ {
int ret; int ret;
uint32 queue_count = 0; int payload_log_len;
app_work_item *work_item; uint32 queue_count = 0;
app_work_item *work_item;
// 安全获取 topic 字符串(复制到本地缓冲区) // 安全获取 topic 字符串(复制到本地缓冲区)
char topic_buf[128] = {0}; char topic_buf[128] = {0};
@@ -403,10 +405,16 @@ static void messageArrived(MessageData* data)
if (topic_len >= sizeof(topic_buf)) { if (topic_len >= sizeof(topic_buf)) {
topic_len = sizeof(topic_buf) - 1; topic_len = sizeof(topic_buf) - 1;
} }
memcpy(topic_buf, data->topicName->lenstring.data, topic_len); memcpy(topic_buf, data->topicName->lenstring.data, topic_len);
topic_buf[topic_len] = '\0'; topic_buf[topic_len] = '\0';
// 比较 topic 类型 payload_log_len = data->message->payloadlen > 512 ? 512 : (int)data->message->payloadlen;
printf("[MQTT-RX] topic=%s len=%d payload=%.*s%s\r\n",
topic_buf, (int)data->message->payloadlen, payload_log_len,
(const char *)data->message->payload,
data->message->payloadlen > (unsigned int)payload_log_len ? "..." : "");
// 比较 topic 类型
int is_command = (strstr(topic_buf, "command") != NULL); int is_command = (strstr(topic_buf, "command") != NULL);
int is_event_resp = (strstr(topic_buf, "event_resp") != NULL) || (strstr(topic_buf, imei_buf) != NULL); int is_event_resp = (strstr(topic_buf, "event_resp") != NULL) || (strstr(topic_buf, imei_buf) != NULL);
@@ -618,15 +626,33 @@ sub_exit:
//0:代表respone command //0:代表respone command
//1:代表send event //1:代表send event
/* [FIX] 将连接状态检查和发送放在同一锁保护区内,避免竞争 */ /* [FIX] 将连接状态检查和发送放在同一锁保护区内,避免竞争 */
int app_mqtt_publish(char *buf, int len, int type) int app_mqtt_publish(char *buf, int len, int type)
{ {
static uint32_t mqtt_pub_cnt_err=0; static uint32_t mqtt_pub_cnt_err=0;
int rc = -1; int rc = -1;
MQTTMessage message; int payload_log_len;
int cnt = 0; MQTTMessage message;
static uint8_t publish_error = 0; int cnt = 0;
static uint8_t publish_error = 0;
// 锁保护:检查连接状态并发送 const char *publish_topic = NULL;
if (type == 0) {
publish_topic = respone_topicName;
} else if (type == 1) {
publish_topic = event_topicName;
} else if (type == 2) {
publish_topic = event_register;
} else {
RLOGE("invalid MQTT publish type=%d", type);
return -1;
}
payload_log_len = len > 512 ? 512 : len;
printf("[MQTT-TX] topic=%s len=%d payload=%.*s%s\r\n",
publish_topic, len, payload_log_len, buf,
len > payload_log_len ? "..." : "");
// 锁保护:检查连接状态并发送
int lock_ret = ql_rtos_mutex_lock(g_mqtt_public_mutex, 5000); int lock_ret = ql_rtos_mutex_lock(g_mqtt_public_mutex, 5000);
if (lock_ret != 0) { if (lock_ret != 0) {
RLOGE("MQTT mutex lock timeout"); RLOGE("MQTT mutex lock timeout");
@@ -643,18 +669,13 @@ int app_mqtt_publish(char *buf, int len, int type)
message.payload = buf; message.payload = buf;
message.payloadlen = len; message.payloadlen = len;
while (cnt++ < 3) { while (cnt++ < 3) {
u32 start = ql_rtos_get_systicks(); u32 start = ql_rtos_get_systicks();
if (type == 0) { rc = MQTTPublish(&client, publish_topic, &message);
rc = MQTTPublish(&client, respone_topicName, &message);
} else if (type == 1) { RLOGD("Pulish time:%d len: %d\n", (ql_rtos_get_systicks()-start)*5, len);
rc = MQTTPublish(&client, event_topicName, &message); printf("[MQTT-TX] topic=%s attempt=%d rc=%d\r\n", publish_topic, cnt, rc);
} else if (type == 2) { if (rc != 0) {
rc = MQTTPublish(&client, event_register, &message);
}
RLOGD("Pulish time:%d len: %d\n", (ql_rtos_get_systicks()-start)*5, len);
if (rc != 0) {
mqtt_pub_cnt_err++; mqtt_pub_cnt_err++;
mqtt_public_error = 1; mqtt_public_error = 1;
RLOGE("ERROR Return code from MQTT publish is %d, cnt %d", rc, mqtt_pub_cnt_err); RLOGE("ERROR Return code from MQTT publish is %d, cnt %d", rc, mqtt_pub_cnt_err);
@@ -1250,23 +1271,34 @@ void handle_nfc_trigger(const char *uuid)
free(json_str); free(json_str);
} }
void handle_nfc_bind(const char *uuid) void handle_nfc_bind(const char *uuid)
{ {
cJSON *root = cJSON_CreateObject(); char iccid[QL_SIM_ICCID_LEN * 2 + 1] = {0};
cJSON *data = cJSON_CreateObject(); QL_SIM_ERROR_CODE sim_ret;
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "msg_id", "006"); cJSON *data = cJSON_CreateObject();
cJSON_AddStringToObject(root, "status", "success");
cJSON_AddStringToObject(root, "msg_id", "006");
cJSON_AddStringToObject(data, "uuid", uuid); cJSON_AddStringToObject(root, "status", "success");
cJSON_AddItemToObject(root, "data", data);
cJSON_AddStringToObject(data, "uuid", uuid);
char *json_str = cJSON_PrintUnformatted(root);
cJSON_Delete(root); sim_ret = ql_sim_get_iccid(iccid, sizeof(iccid));
if (sim_ret == QL_SIM_SUCCESS && iccid[0] != '\0') {
app_mqtt_publish(json_str, strlen(json_str), 0); printf("NFC bind ICCID:%s\r\n", iccid);
free(json_str); cJSON_AddStringToObject(data, "iccid", iccid);
} } else {
printf("NFC bind get ICCID failed, ret:%d\r\n", sim_ret);
}
cJSON_AddItemToObject(root, "data", data);
char *json_str = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
app_mqtt_publish(json_str, strlen(json_str), 0);
free(json_str);
}
@@ -1446,7 +1478,7 @@ static void app_mqtt_task_event_thread(void *arvg)
app_heartbeat_time_record = hal_os_up_time_ms(); app_heartbeat_time_record = hal_os_up_time_ms();
// 采集设备信息 // 采集设备信息
info.power = calc_battery_level(g_vbat_vol); // 10,20,30...100 info.power = battery_get_level(); // 使用与设备内部一致的最终电量档位
info.voice = g_cur_volume; // 40,60,80,100 info.voice = g_cur_volume; // 40,60,80,100