You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

122 lines
3.3 KiB

/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2025-10-20 Administrator the first version
*/
#ifndef APPLICATIONS_DB_DB_SQLITE_H_
#define APPLICATIONS_DB_SQLITE_SYS_H_
#include <rtthread.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ========================
* 配置参数
* ======================== */
#ifndef MAX_SQL_LEN
#define MAX_SQL_LEN (1024) /**< SQL 语句最大长度 */
#endif
#ifndef MAX_RESULT_LEN
#define MAX_RESULT_LEN (1024) /**< 结果字符串最大长度 */
#endif
#ifndef DB_MAX_WAITING_MS
#define DB_MAX_WAITING_MS (5000) /**< 命令最大等待时间(毫秒),默认 5 秒 */
#endif
#ifndef DB_QUEUE_SIZE
#define DB_QUEUE_SIZE (8) /**< 消息队列容量(最多缓存 8 条命令) */
#endif
/* 补充常见错误码(如果 RT-Thread 未定义) */
#ifndef RT_ENODEV
#define RT_ENODEV (-5)
#endif
#ifndef RT_ETIMEOUT
#define RT_ETIMEOUT (-4)
#endif
/* ========================
* 命令类型枚举
* ======================== */
enum db_cmd_type
{
DB_CMD_INSERT, /**< 插入数据 */
DB_CMD_DELETE, /**< 删除数据 */
DB_CMD_UPDATE, /**< 更新数据 */
DB_CMD_SELECT, /**< 查询数据(返回结果字符串) */
DB_CMD_EXEC, /**< 执行任意 SQL(无结果集) */
DB_CMD_EXIT /**< 退出数据库线程(内部使用) */
};
/* ========================
* 数据库命令结构体
* ======================== */
struct db_command
{
enum db_cmd_type type; /**< 命令类型 */
char sql[MAX_SQL_LEN]; /**< SQL 语句内容 */
rt_uint32_t result_code; /**< 返回码(SQLite code 或负的 RT-Error) */
char result[MAX_RESULT_LEN]; /**< 结果或错误信息 */
rt_sem_t reply_sem; /**< 回应信号量(由调用方创建,用于同步) */
rt_tick_t send_tick; /**< 发送时刻的系统 tick,用于超时检测 */
};
/* ========================
* 全局变量声明
* ======================== */
/**
* 消息队列句柄:用于向数据库线程发送命令
* 必须在 .c 文件中定义为:rt_mq_t db_mq = RT_NULL;
*/
extern rt_mq_t db_mq;
/* ========================
* 函数接口声明
* ======================== */
/**
* @brief 启动数据库处理线程
*
* 创建一个名为 "data_sqlite" 的线程,初始化 SQLite 数据库,
* 并开始监听 db_mq 中的 SQL 请求。
*
* @note 若已运行,多次调用无效。
*/
void thread_DB_SQLite(void);
/**
* @brief 立即关闭数据库并禁止后续操作
*
* 关闭当前数据库连接,并设置禁用标志。
* 之后所有新请求将立即失败,返回“数据库已禁用”。
*
* @note 此函数是线程安全的。
*/
void close_db_immediately(void);
/**
* @brief 向数据库发送命令并等待响应
*
* @param type 命令类型(INSERT/SELECT等)
* @param sql SQL 语句字符串
* @param timeout_ms 超时时间(毫秒),0 表示不等待
* @return RT_EOK 成功,RT_ETIMEOUT 超时,RT_ERROR 失败
*/
rt_err_t db_send_command(enum db_cmd_type type, const char* sql, rt_int32_t timeout_ms);
#ifdef __cplusplus
}
#endif
#endif /* APPLICATIONS_DB_DB_SQLITE_H_ */