【OpenHarmony】轻量级公共基础库commonlibrary_utils_lite

OpenHarmony 轻量级公共基础库 (commonlibrary_utils_lite) 模块


目录

  1. 模块概述
  2. 模块结构
  3. 模块间交互
  4. 状态机转换图
  5. 接口设计

1. 模块概述

1.1 功能与目标

主要功能

轻量级公共基础库(commonlibrary_utils_lite)是OpenHarmony系统中的通用基础组件库,提供以下核心功能:

功能模块 描述 支持平台
文件操作 提供统一的文件操作接口,屏蔽底层不同芯片组件的差异 LiteOS-M内核
定时器 提供统一的定时器操作接口,支持单次和周期性定时 LiteOS-M/LiteOS-A内核
KV存储 提供键值对存储功能,支持缓存机制 LiteOS-A内核
JS API 提供设备信息查询、数据存储的JavaScript接口 LiteOS-A内核
双向链表 提供高效的双向链表数据结构操作 通用
内存池管理 提供分类型的内存池管理接口 通用
设计目标
  1. 跨平台兼容性: 通过HAL(硬件抽象层)屏蔽底层硬件差异
  2. 轻量化设计: 适配资源受限的嵌入式设备
  3. 高可靠性: 提供完善的错误处理机制
  4. 易用性: 提供简洁统一的API接口
使用场景
  • 物联网设备的文件存储与读取
  • 定时任务调度与管理
  • 应用配置数据的持久化存储
  • 设备信息的查询与获取

1.2 系统位置

系统架构定位

本模块属于OpenHarmony系统的公共基础子系统(commonlibrary) ,是系统的核心基础模块,为上层应用和其他子系统提供基础服务支持。

复制代码
┌─────────────────────────────────────────────────────────────────────┐
│                        应用层 (Application Layer)                    │
│                    ┌─────────────────────────────┐                  │
│                    │      JS 应用程序             │                  │
│                    └─────────────────────────────┘                  │
├─────────────────────────────────────────────────────────────────────┤
│                        框架层 (Framework Layer)                      │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐                 │
│  │  ACE Lite   │  │  Ability    │  │  UI Lite    │                 │
│  │  Engine     │  │  Framework  │  │             │                 │
│  └──────┬──────┘  └──────┬──────┘  └─────────────┘                 │
├─────────┼────────────────┼──────────────────────────────────────────┤
│         │                │                                          │
│         ▼                ▼                                          │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │              commonlibrary_utils_lite                        │   │
│  │  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐    │   │
│  │  │ 文件操作  │ │  定时器   │ │ KV存储   │ │  JS API      │    │   │
│  │  └──────────┘ └──────────┘ └──────────┘ └──────────────┘    │   │
│  │  ┌──────────┐ ┌──────────┐                                   │   │
│  │  │ 双向链表  │ │ 内存池   │                                   │   │
│  │  └──────────┘ └──────────┘                                   │   │
│  └─────────────────────────────────────────────────────────────┘   │
│                        公共基础子系统                                │
├─────────────────────────────────────────────────────────────────────┤
│                        内核层 (Kernel Layer)                        │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │                    LiteOS-M / LiteOS-A                       │   │
│  └─────────────────────────────────────────────────────────────┘   │
├─────────────────────────────────────────────────────────────────────┤
│                        硬件抽象层 (HAL)                              │
│  ┌─────────────────────────────────────────────────────────────┐   │
│  │           HAL File / HAL Timer / HAL Memory                  │   │
│  └─────────────────────────────────────────────────────────────┘   │
├─────────────────────────────────────────────────────────────────────┤
│                        硬件层 (Hardware Layer)                      │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐                 │
│  │   Hi3861    │  │   Hi3516    │  │   Hi3518    │                 │
│  └─────────────┘  └─────────────┘  └─────────────┘                 │
└─────────────────────────────────────────────────────────────────────┘
与其他模块的关系
依赖模块 关系类型 说明
ability_lite 被依赖 提供应用数据路径获取
ace_engine_lite 被依赖 提供JS引擎支持
graphic_utils_lite 被依赖 提供图形相关工具
bounds_checking_function 依赖 安全字符串处理函数
musl 依赖 C标准库支持
init 被依赖 系统初始化服务

1.3 设计思路与模式

设计思路
  1. 分层架构设计

    • 接口层:对外暴露统一的API接口
    • 实现层:具体功能实现
    • 适配层(HAL):硬件平台适配
  2. 模块化设计

    • 各功能模块相互独立,可按需裁剪
    • 通过feature开关控制功能编译
  3. 跨语言支持

    • C层:核心功能实现
    • C++层:JS API封装
    • JS层:应用接口
设计模式
设计模式 应用场景 说明
适配器模式 HAL层 将不同硬件平台的文件/定时器操作适配为统一接口
单例模式 内存池管理 确保内存池的唯一性和全局访问
工厂模式 定时器创建 通过KalTimerCreate创建不同类型的定时器
回调模式 JS异步操作 通过success/fail/complete回调处理异步结果
门面模式 JS API NativeapiFs/NativeapiKv等类封装底层复杂操作

2. 模块结构

2.1 源文件与头文件

目录结构
复制代码
commonlibrary/utils_lite/
├── BUILD.gn                          # 顶层构建文件
├── bundle.json                       # 组件描述文件
├── include/                          # 公共头文件目录
│   ├── kv_store.h                    # KV存储接口
│   ├── ohos_errno.h                  # 错误码定义
│   ├── ohos_init.h                   # 系统初始化宏
│   ├── ohos_types.h                  # 基础类型定义
│   ├── utils_config.h                # 配置文件
│   ├── utils_file.h                  # 文件操作接口
│   └── utils_list.h                  # 双向链表接口
├── file/                             # 文件操作模块
│   └── src/file_impl_hal/
│       └── file.c                    # 文件操作实现
├── hals/                             # 硬件抽象层
│   └── file/
│       ├── hal_file.h                # HAL文件接口
│       └── hal_file.c                # HAL文件实现
├── kal/                              # 内核抽象层
│   └── timer/
│       ├── include/kal.h             # KAL定时器接口
│       └── src/kal.c                 # KAL定时器实现
├── timer_task/                       # 定时任务模块
│   ├── include/nativeapi_timer_task.h
│   └── src/nativeapi_timer_task.c
├── memory/                           # 内存管理模块
│   └── include/ohos_mem_pool.h       # 内存池接口
└── js/builtin/                       # JS API模块
    ├── common/                       # 公共组件
    │   ├── include/
    │   │   ├── nativeapi_common.h
    │   │   └── nativeapi_config.h
    │   └── src/nativeapi_common.cpp
    ├── filekit/                      # 文件Kit
    │   ├── include/
    │   │   ├── nativeapi_fs.h
    │   │   └── nativeapi_fs_impl.h
    │   └── src/
    │       ├── nativeapi_fs.cpp
    │       └── nativeapi_fs_impl.c
    ├── kvstorekit/                   # KV存储Kit
    │   ├── include/
    │   │   ├── nativeapi_kv.h
    │   │   └── nativeapi_kv_impl.h
    │   └── src/
    │       ├── nativeapi_kv.cpp
    │       └── nativeapi_kv_impl.c
    └── deviceinfokit/                # 设备信息Kit
        ├── include/nativeapi_deviceinfo.h
        └── src/
            ├── nativeapi_deviceinfo.cpp
            └── nativeapi_ohos_deviceinfo.cpp
文件功能说明
文件 功能描述
include/ohos_types.h 定义基础数据类型(uint8, uint16, uint32等)
include/ohos_errno.h 定义系统错误码枚举
include/ohos_init.h 定义系统初始化宏(CORE_INIT, SYS_SERVICE_INIT等)
include/utils_file.h 声明文件操作API(打开、关闭、读写、删除等)
include/utils_list.h 声明双向链表操作API和宏
include/kv_store.h 声明KV存储API(获取、设置、删除)
include/utils_config.h 定义KV存储配置参数
hals/file/hal_file.h 声明HAL层文件操作接口
hals/file/hal_file.c 实现HAL层文件操作(调用POSIX接口)
file/src/file_impl_hal/file.c 文件操作的HAL适配实现
kal/timer/include/kal.h 声明KAL定时器接口
kal/timer/src/kal.c 实现KAL定时器(基于POSIX timer)
timer_task/include/nativeapi_timer_task.h 声明定时任务接口
timer_task/src/nativeapi_timer_task.c 实现定时任务管理
memory/include/ohos_mem_pool.h 声明内存池管理接口
js/builtin/common/include/nativeapi_common.h JS API公共回调处理
js/builtin/common/include/nativeapi_config.h JS API配置常量定义
js/builtin/filekit/include/nativeapi_fs.h JS文件操作API声明
js/builtin/kvstorekit/include/nativeapi_kv.h JS KV存储API声明
js/builtin/deviceinfokit/include/nativeapi_deviceinfo.h JS设备信息API声明

2.2 类、结构体、函数与方法

2.2.1 核心结构体
UTILS_DL_LIST(双向链表节点)
c 复制代码
// 文件: include/utils_list.h
typedef struct UTILS_DL_LIST {
    struct UTILS_DL_LIST *pstPrev;  // 指向前一个节点的指针
    struct UTILS_DL_LIST *pstNext;  // 指向后一个节点的指针
} UTILS_DL_LIST;
KalTimer(定时器结构)
c 复制代码
// 文件: kal/timer/src/kal.c
typedef struct {
    timer_t timerPtr;        // POSIX定时器句柄
    KalTimerType type;       // 定时器类型(单次/周期)
    unsigned int millisec;   // 定时时间(毫秒)
    KalTimerProc func;       // 回调函数
    union sigval arg;        // 回调参数
    int isRunning;           // 运行状态标志
} KalTimer;
KalTimerType(定时器类型枚举)
c 复制代码
// 文件: kal/timer/include/kal.h
typedef enum {
    KAL_TIMER_ONCE = 0,      // 单次定时器
    KAL_TIMER_PERIODIC = 1   // 周期定时器
} KalTimerType;
KalErrCode(错误码枚举)
c 复制代码
// 文件: kal/timer/include/kal.h
typedef enum {
    KAL_OK = 0,              // 成功
    KAL_ERR_PARA = 1,        // 参数错误
    KAL_ERR_INNER = 2,       // 内部错误
    KAL_ERR_TIMER_STATE = 0x100,  // 定时器状态错误
} KalErrCode;
OHOSLiteErrorCode(系统错误码)
c 复制代码
// 文件: include/ohos_errno.h
enum OHOSLiteErrorCode {
    EC_SUCCESS = 0,          // 成功
    EC_FAILURE = -1,         // 执行失败
    EC_BADPTR = -2,          // 错误指针
    EC_NOMEMORY = -3,        // 内存不足
    EC_ADDRESS = -4,         // 地址错误
    EC_IOERROR = -5,         // I/O错误
    EC_BUSBUSY = -6,         // 总线忙
    EC_NORESPONCE = -7,      // 无响应
    EC_NODEVICE = -8,        // 无设备
    EC_INVALID = -9,         // 无效参数
    EC_BUSY = -10,           // 设备忙
    EC_NOSERVICE = -11,      // 无服务
    EC_PERMISSION = -12,     // 权限拒绝
    EC_NOFILE = -13,         // 文件不存在
    EC_NOSPACE = -14,        // 空间不足
    EC_NODIR = -15,          // 非目录
    EC_ROFILE = -16,         // 只读文件系统
    EC_NAMETOOLONG = -17,    // 文件名过长
    EC_OPBLOCK = -18,        // 操作阻塞
    EC_TIMEOUT = -19,        // 超时
    EC_COMMU = -20,          // 通信错误
    EC_PROTOCOL = -21,       // 协议错误
    EC_CANCELED = -22,       // 操作取消
    EC_NOKEY = -23,          // 无密钥
    EC_NOHANDLER = -24,      // 无处理器
    EC_FLOWCTRL = -25,       // 流控制
    EC_NOINIT = -26,         // 未初始化
    EC_NORESOURCE = -27,     // 资源错误
    // ...
};
MemType(内存池类型枚举)
c 复制代码
// 文件: memory/include/ohos_mem_pool.h
typedef enum {
    MEM_TYPE_BEGIN = 100,
    MEM_TYPE_UIKIT = MEM_TYPE_BEGIN,  // UIKIT内存池
    MEM_TYPE_UIKIT_LSRAM,             // UIKIT低速内存池
    MEM_TYPE_APPFMK,                  // 应用框架内存池
    MEM_TYPE_APPFMK_LSRAM,            // 应用框架低速内存池
    MEM_TYPE_ACE,                     // ACE内存池
    MEM_TYPE_ACE_LSRAM,               // ACE低速内存池
    MEM_TYPE_JERRY,                   // JerryScript内存池
    MEM_TYPE_JERRY_LSRAM,             // JerryScript低速内存池
    MEM_TYPE_JERRY_HEAP,              // JerryScript堆内存池
    MEM_TYPE_HICHAIN,                 // 安全内存池
    MEM_TYPE_SOFTBUS_LSRAM,           // 软总线低速内存池
    MEM_TYPE_I18N_LSRAM,              // 国际化低速内存池
    MEM_TYPE_CJSON_LSRAM,             // cJSON低速内存池
    MEM_TYPE_APP_VERIFY_LSRAM,        // 应用验证低速内存池
    MEM_TYPE_MAX                      // 最大值
} MemType;
FuncParams(JS回调参数结构)
cpp 复制代码
// 文件: js/builtin/common/include/nativeapi_common.h
namespace OHOS {
namespace ACELite {
struct FuncParams {
    JSIValue args = JSI::CreateUndefined();     // 参数
    JSIValue thisVal = JSI::CreateUndefined();  // this指针
    bool flag = false;                          // 标志位
};
}
}
2.2.2 核心类
NativeapiCommon(公共回调处理类)
cpp 复制代码
// 文件: js/builtin/common/include/nativeapi_common.h
namespace OHOS {
namespace ACELite {
class NativeapiCommon {
public:
    // 失败回调处理
    static void FailCallBack(const JSIValue thisVal, const JSIValue args, int ret);
    // 成功回调处理
    static void SuccessCallBack(const JSIValue thisVal, const JSIValue args, JSIValue jsiValue);
    // 验证JSI值有效性
    static bool IsValidJSIValue(const JSIValue* args, uint8_t argsNum);
private:
    NativeapiCommon() = default;
    ~NativeapiCommon() = default;
};
}
}
NativeapiFs(文件操作JS API类)
cpp 复制代码
// 文件: js/builtin/filekit/include/nativeapi_fs.h
namespace OHOS {
namespace ACELite {
class NativeapiFs {
public:
    NativeapiFs() = default;
    ~NativeapiFs() = default;

    static JSIValue MoveFile(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue CopyFile(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue DeleteFile(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue GetFileList(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue GetFileInfo(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue WriteTextFile(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue ReadTextFile(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue Access(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue CreateDir(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue RemoveDir(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
#if (JS_FWK_TYPEDARRAY == NATIVE_FEATURE_ON)
    static JSIValue ReadArrayFile(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue WriteArrayFile(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
#endif
};
}
}
NativeapiKv(KV存储JS API类)
cpp 复制代码
// 文件: js/builtin/kvstorekit/include/nativeapi_kv.h
namespace OHOS {
namespace ACELite {
class NativeapiKv {
public:
    NativeapiKv() = default;
    ~NativeapiKv() = default;

    static JSIValue Get(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue Set(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue Delete(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static JSIValue Clear(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
};
}
}
NativeapiDeviceInfo(设备信息JS API类)
cpp 复制代码
// 文件: js/builtin/deviceinfokit/include/nativeapi_deviceinfo.h
namespace OHOS {
namespace ACELite {
class NativeapiDeviceInfo {
public:
    NativeapiDeviceInfo() = default;
    ~NativeapiDeviceInfo() = default;

    static JSIValue GetDeviceInfo(const JSIValue thisVal, const JSIValue* args, uint8_t argsNum);
    static bool GetProductInfo(JSIValue result);
private:
    static bool GetLanguage(JSIValue result);
    static bool GetRegion(JSIValue result);
    static bool GetAPILevel(JSIValue result);
    static bool GetDeviceType(JSIValue result);
};
}
}
2.2.3 核心函数
文件操作函数
函数 描述 参数 返回值
UtilsFileOpen 打开或创建文件 path: 文件路径 oflag: 打开标志 mode: 模式 文件描述符,失败返回-1
UtilsFileClose 关闭文件 fd: 文件描述符 0成功,-1失败
UtilsFileRead 读取文件 fd: 文件描述符 buf: 缓冲区 len: 长度 读取字节数,-1失败
UtilsFileWrite 写入文件 fd: 文件描述符 buf: 数据 len: 长度 写入字节数,-1失败
UtilsFileDelete 删除文件 path: 文件路径 0成功,-1失败
UtilsFileStat 获取文件大小 path: 文件路径 fileSize: 输出大小 0成功,-1失败
UtilsFileSeek 调整读写位置 fd: 文件描述符 offset: 偏移 whence: 起始位置 当前位置,-1失败
UtilsFileCopy 复制文件 src: 源文件 dest: 目标文件 0成功,-1失败
UtilsFileMove 移动文件 src: 源文件 dest: 目标文件 0成功,-1失败
定时器函数
函数 描述 参数 返回值
KalTimerCreate 创建定时器 func: 回调函数 type: 类型 arg: 参数 millisec: 时间 定时器ID,NULL失败
KalTimerStart 启动定时器 timerId: 定时器ID KAL_OK成功
KalTimerChange 修改定时器 timerId: 定时器ID millisec: 新时间 KAL_OK成功
KalTimerStop 停止定时器 timerId: 定时器ID KAL_OK成功
KalTimerDelete 删除定时器 timerId: 定时器ID KAL_OK成功
KalTimerIsRunning 查询运行状态 timerId: 定时器ID 1运行中,0停止
KV存储函数
函数 描述 参数 返回值
UtilsGetValue 获取键值 key: 键名 value: 输出值 len: 缓冲区大小 值长度,-9参数错误,-1其他错误
UtilsSetValue 设置键值 key: 键名 value: 值 0成功,-9参数错误,-1其他错误
UtilsDeleteValue 删除键值 key: 键名 0成功,-9参数错误,-1其他错误
ClearKVCache 清空缓存 0成功,-1失败
内存池函数
函数 描述 参数 返回值
OhosMalloc 申请内存 type: 内存池类型 size: 大小 内存地址,NULL失败
OhosFree 释放内存 ptr: 内存地址
双向链表函数
函数/宏 描述
UtilsListInit 初始化链表
UtilsListAdd 插入节点
UtilsListTailInsert 尾部插入
UtilsListHeadInsert 头部插入
UtilsListDelete 删除节点
UtilsListEmpty 判断是否为空
UTILS_DL_LIST_ENTRY 获取包含链表的结构体指针
UTILS_DL_LIST_FOR_EACH 遍历链表
UTILS_DL_LIST_FOR_EACH_SAFE 安全遍历链表

2.3 类图

uses uses uses calls calls calls calls uses implements implements NativeapiFs +MoveFile() +CopyFile() +DeleteFile() +GetFileList() +GetFileInfo() +WriteTextFile() +ReadTextFile() +Access() +CreateDir() +RemoveDir() NativeapiKv +Get() +Set() +Delete() +Clear() NativeapiDeviceInfo +GetDeviceInfo() +GetProductInfo() -GetLanguage() -GetRegion() -GetAPILevel() -GetDeviceType() NativeapiCommon +FailCallBack(thisVal, args, ret) +SuccessCallBack(thisVal, args, jsiValue) +IsValidJSIValue(args, argsNum) nativeapi_fs_impl +CopyFileImpl() +DeleteFileImpl() +AccessImpl() +StatImpl() +GetFileNum() +GetFileListImpl() +WriteTextFile() +ReadFileImpl() +CreateDirImpl() +RemoveDirImpl() nativeapi_kv_impl +InitKv() +GetValue() +SetValue() +DeleteValue() +ClearKVStore() KalTimer +timerPtr +type +millisec +func +arg +isRunning HAL_File +HalFileOpen() +HalFileClose() +HalFileRead() +HalFileWrite() +HalFileDelete() +HalFileStat() +HalFileSeek() KAL_Timer +KalTimerCreate() +KalTimerStart() +KalTimerChange() +KalTimerStop() +KalTimerDelete() +KalTimerIsRunning() <<interface>> POSIX_Layer open() close() read() write() unlink() stat() lseek() timer_create() timer_settime() timer_delete()

2.4 模块内部依赖框图

commonlibrary_utils_lite JS Builtin Module Timer Task Module KAL Module File Module HAL Module Include Module Memory Module ohos_mem_pool.h ohos_types.h ohos_errno.h ohos_init.h utils_file.h utils_list.h kv_store.h utils_config.h hal_file.c file.c kal.c nativeapi_timer_task deviceinfokit filekit kvstorekit common

依赖关系说明:

  • 箭头方向表示依赖方向
  • 子图边界表示模块边界

3. 模块间交互

3.1 交互描述

3.1.1 与外部模块的交互
外部模块 交互方式 说明
ACE Lite Engine C++函数调用 通过JSI接口注册JS API
Ability Framework C函数调用 获取应用数据路径
Graphic Utils C函数调用 获取屏幕信息
Parameter Service C函数调用 获取设备参数信息
Global I18N C函数调用 获取语言和地区信息
3.1.2 异步处理机制

JS API层采用异步回调模式处理耗时操作:

cpp 复制代码
// 异步任务分发流程
JSIValue ExecuteAsyncWork(thisVal, args, argsNum, ExecuteFunc, flag) {
    1. 验证参数有效性
    2. 创建FuncParams参数结构
    3. 保存thisVal和args引用
    4. 调用JsAsyncWork::DispatchAsyncWork分发任务
    5. 返回undefined
}

// 异步执行函数(在工作线程执行)
void ExecuteXxx(void* data) {
    1. 解析FuncParams参数
    2. 执行实际操作
    3. 根据结果调用SuccessCallBack或FailCallBack
    4. 释放资源
}
3.1.3 回调机制

JS API支持三种回调:

javascript 复制代码
// JS调用示例
file.readText({
    uri: 'internal://app/test.txt',
    success: function(data) {
        // 成功回调
        console.log(data.text);
    },
    fail: function(data, code) {
        // 失败回调
        console.log('Error: ' + data + ', Code: ' + code);
    },
    complete: function() {
        // 完成回调(无论成功失败都会调用)
    }
});

3.2 外部依赖框图

复制代码
┌─────────────────────────────────────────────────────────────────────────────┐
│                            External Dependencies                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                        Third Party Libraries                         │    │
│  │  ┌──────────────────────────┐  ┌──────────────────────────┐         │    │
│  │  │  bounds_checking_function │  │         musl             │         │    │
│  │  │  (securec.h)              │  │    (C Standard Library)  │         │    │
│  │  │  - memset_s               │  │    - malloc/free         │         │    │
│  │  │  - strcpy_s               │  │    - open/close/read     │         │    │
│  │  │  - sprintf_s              │  │    - timer_create        │         │    │
│  │  └──────────────────────────┘  └──────────────────────────┘         │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                      │                                       │
│                                      ▼                                       │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                                                                      │    │
│  │                    commonlibrary_utils_lite                          │    │
│  │                                                                      │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                      │                                       │
│                                      ▼                                       │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │                       OpenHarmony Components                         │    │
│  │                                                                      │    │
│  │  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐     │    │
│  │  │   ability_lite  │  │  ace_engine_lite│  │graphic_utils_lite│     │    │
│  │  │                 │  │                 │  │                  │     │    │
│  │  │ - GetDataPath() │  │ - JSI API       │  │ - Screen Info    │     │    │
│  │  │ - AbilityEnv    │  │ - JsAsyncWork   │  │                  │     │    │
│  │  └─────────────────┘  └─────────────────┘  └─────────────────┘     │    │
│  │                                                                      │    │
│  │  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐     │    │
│  │  │   ui_lite       │  │resource_mgmt_lite│ │      init       │     │    │
│  │  │                 │  │                 │  │                  │     │    │
│  │  │ - UI Components │  │ - Resource Mgmt │  │ - System Init    │     │    │
│  │  └─────────────────┘  └─────────────────┘  └─────────────────┘     │    │
│  │                                                                      │    │
│  │  ┌─────────────────┐  ┌─────────────────┐                           │    │
│  │  │    parameter    │  │     global      │                           │    │
│  │  │                 │  │                 │                           │    │
│  │  │ - GetBrand()    │  │ - GLOBAL_Get    │                           │    │
│  │  │ - GetModel()    │  │   Language()    │                           │    │
│  │  │ - GetDeviceType │  │ - GLOBAL_Get    │                           │    │
│  │  │ - GetSdkApi     │  │   Region()      │                           │    │
│  │  │   Version()     │  │                 │                           │    │
│  │  └─────────────────┘  └─────────────────┘                           │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
└─────────────────────────────────────────────────────────────────────────────┘

4. 状态机转换图

4.1 定时器状态机模型

4.1.1 状态机树图

Timer State
Machine Root Uninitialized
(NULL) Initialized Deleted Stopped
(isRunning = 0) Running
(isRunning = 1) Paused
(isRunning = 0)

4.1.2 状态切换规则
当前状态 事件/条件 目标状态 说明
Uninitialized KalTimerCreate() 成功 Stopped 创建定时器
Uninitialized KalTimerCreate() 失败 Uninitialized 创建失败保持原状态
Stopped KalTimerStart() 成功 Running 启动定时器
Stopped KalTimerDelete() Deleted 删除定时器
Running 单次定时器超时 Stopped 自动停止
Running 周期定时器超时 Running 保持运行,触发回调
Running KalTimerStop() Stopped 手动停止
Running KalTimerChange(0) Stopped 设置0毫秒停止
Running KalTimerChange(n) Running 更新定时时间
Running KalTimerDelete() Deleted 删除定时器
Any KalTimerDelete() Deleted 释放资源

4.2 定时器状态机转换图

KalTimerCreate() 成功
func != NULL KalTimerCreate() 失败 KalTimerStart()
millisec > 0 KalTimerDelete() 单次定时器超时
执行回调, isRunning=0 周期定时器超时
执行回调, 保持Running KalTimerStop()
KalTimerChange(0) KalTimerDelete() Uninitialized Stopped Running Deleted NULL状态 isRunning = 0 isRunning = 1 资源已释放

4.3 文件操作状态机

UtilsFileOpen()
fd >= 0 UtilsFileOpen() 失败 读写操作 操作完成 UtilsFileClose() UtilsFileClose() Closed Opened Error ReadWrite fd = -1 fd >= 0 Read/Write Operations fd = -1


5. 接口设计

5.1 公共接口

5.1.1 文件操作接口
UtilsFileOpen
c 复制代码
/**
 * @brief 打开或创建文件
 * @param path 文件路径
 * @param oflag 打开标志,支持以下组合:
 *        - O_RDONLY_FS (00): 只读
 *        - O_WRONLY_FS (01): 只写
 *        - O_RDWR_FS (02): 读写
 *        - O_CREAT_FS (0100): 不存在则创建
 *        - O_EXCL_FS (0200): 配合O_CREAT使用,文件存在则失败
 *        - O_TRUNC_FS (01000): 清空文件内容
 *        - O_APPEND_FS (02000): 追加模式
 * @param mode 文件权限(当前未使用)
 * @return 成功返回文件描述符(>=0),失败返回-1
 */
int UtilsFileOpen(const char* path, int oflag, int mode);
UtilsFileClose
c 复制代码
/**
 * @brief 关闭文件
 * @param fd 文件描述符
 * @return 成功返回0,失败返回-1
 */
int UtilsFileClose(int fd);
UtilsFileRead
c 复制代码
/**
 * @brief 读取文件数据
 * @param fd 文件描述符
 * @param buf 存储读取数据的缓冲区
 * @param len 要读取的字节数
 * @return 成功返回实际读取的字节数,失败返回-1
 */
int UtilsFileRead(int fd, char* buf, unsigned int len);
UtilsFileWrite
c 复制代码
/**
 * @brief 写入文件数据
 * @param fd 文件描述符
 * @param buf 要写入的数据
 * @param len 要写入的字节数
 * @return 成功返回实际写入的字节数,失败返回-1
 */
int UtilsFileWrite(int fd, const char* buf, unsigned int len);
UtilsFileDelete
c 复制代码
/**
 * @brief 删除文件
 * @param path 文件路径
 * @attention 最多同时打开32个文件,超过则需先关闭
 * @return 成功返回0,失败返回-1
 */
int UtilsFileDelete(const char* path);
UtilsFileStat
c 复制代码
/**
 * @brief 获取文件大小
 * @param path 文件路径
 * @param fileSize [out] 文件大小
 * @return 成功返回0,失败返回-1
 */
int UtilsFileStat(const char* path, unsigned int* fileSize);
UtilsFileSeek
c 复制代码
/**
 * @brief 调整文件读写位置
 * @param fd 文件描述符
 * @param offset 偏移量
 * @param whence 起始位置:
 *        - SEEK_SET_FS (0): 文件头
 *        - SEEK_CUR_FS (1): 当前位置
 *        - SEEK_END_FS (2): 文件尾
 * @return 成功返回当前位置,失败返回-1
 */
int UtilsFileSeek(int fd, int offset, unsigned int whence);
UtilsFileCopy
c 复制代码
/**
 * @brief 复制文件
 * @param src 源文件路径
 * @param dest 目标文件路径
 * @attention 需要两个可用的文件描述符
 * @return 成功返回0,失败返回-1
 */
int UtilsFileCopy(const char* src, const char* dest);
UtilsFileMove
c 复制代码
/**
 * @brief 移动文件
 * @param src 源文件路径
 * @param dest 目标文件路径
 * @attention 需要两个可用的文件描述符
 * @return 成功返回0,失败返回-1
 */
int UtilsFileMove(const char* src, const char* dest);
5.1.2 KV存储接口
UtilsGetValue
c 复制代码
/**
 * @brief 获取键值
 * @param key 键名(最长32字节,仅支持小写字母、数字、下划线、点)
 * @param value [out] 值缓冲区
 * @param len 缓冲区大小
 * @return 成功返回值长度,参数错误返回-9,其他错误返回-1,
 *         从缓存获取返回0
 */
int UtilsGetValue(const char* key, char* value, unsigned int len);
UtilsSetValue
c 复制代码
/**
 * @brief 设置键值
 * @param key 键名(最长32字节)
 * @param value 值(最长128字节)
 * @return 成功返回0,参数错误返回-9,其他错误返回-1
 */
int UtilsSetValue(const char* key, const char* value);
UtilsDeleteValue
c 复制代码
/**
 * @brief 删除键值
 * @param key 键名
 * @return 成功返回0,参数错误返回-9,其他错误返回-1
 */
int UtilsDeleteValue(const char* key);
ClearKVCache
c 复制代码
/**
 * @brief 清空KV缓存
 * @attention 仅在FEATURE_KV_CACHE启用时可用
 * @return 成功返回0,失败返回-1
 */
int ClearKVCache(void);
5.1.3 定时器接口
KalTimerCreate
c 复制代码
/**
 * @brief 创建定时器
 * @param func 回调函数
 * @param type 定时器类型(KAL_TIMER_ONCE/KAL_TIMER_PERIODIC)
 * @param arg 回调参数
 * @param millisec 定时时间(毫秒)
 * @return 成功返回定时器ID,失败返回NULL
 */
KalTimerId KalTimerCreate(KalTimerProc func, KalTimerType type, 
                          void* arg, unsigned int millisec);
KalTimerStart
c 复制代码
/**
 * @brief 启动定时器
 * @param timerId 定时器ID
 * @return KAL_OK成功,KAL_ERR_PARA参数错误
 */
KalErrCode KalTimerStart(KalTimerId timerId);
KalTimerChange
c 复制代码
/**
 * @brief 修改定时器时间
 * @param timerId 定时器ID
 * @param millisec 新的定时时间
 * @return KAL_OK成功,KAL_ERR_PARA参数错误,KAL_ERR_INNER内部错误
 */
KalErrCode KalTimerChange(KalTimerId timerId, unsigned int millisec);
KalTimerStop
c 复制代码
/**
 * @brief 停止定时器
 * @param timerId 定时器ID
 * @return KAL_OK成功,KAL_ERR_PARA参数错误,KAL_ERR_INNER内部错误
 */
KalErrCode KalTimerStop(KalTimerId timerId);
KalTimerDelete
c 复制代码
/**
 * @brief 删除定时器
 * @param timerId 定时器ID
 * @return KAL_OK成功,KAL_ERR_PARA参数错误,KAL_ERR_INNER内部错误
 */
KalErrCode KalTimerDelete(KalTimerId timerId);
KalTimerIsRunning
c 复制代码
/**
 * @brief 查询定时器是否运行
 * @param timerId 定时器ID
 * @return 1运行中,0停止或无效
 */
unsigned int KalTimerIsRunning(KalTimerId timerId);
5.1.4 内存池接口
OhosMalloc
c 复制代码
/**
 * @brief 从指定类型内存池申请内存
 * @param type 内存池类型(MemType枚举)
 * @param size 申请大小
 * @attention 不建议申请小于8字节的内存
 * @return 成功返回内存地址,失败返回NULL
 */
void *OhosMalloc(MemType type, uint32 size);
OhosFree
c 复制代码
/**
 * @brief 释放内存
 * @param ptr 内存地址
 * @attention 禁止释放空指针或非OhosMalloc申请的内存
 */
void OhosFree(void *ptr);

5.2 数据交换接口

5.2.1 JS API数据交换格式
文件操作参数
javascript 复制代码
// 读取文本文件
{
    uri: 'internal://app/path/to/file.txt',  // 文件URI
    position: 0,                              // 起始位置(可选)
    length: 1024,                             // 读取长度(可选)
    success: function(data) {},               // 成功回调
    fail: function(data, code) {},            // 失败回调
    complete: function() {}                   // 完成回调
}

// 写入文本文件
{
    uri: 'internal://app/path/to/file.txt',
    text: 'content to write',                 // 写入内容
    append: false,                            // 是否追加
    success: function() {},
    fail: function(data, code) {},
    complete: function() {}
}
KV存储参数
javascript 复制代码
// 获取值
{
    key: 'my_key',                           // 键名
    default: 'default_value',                // 默认值(可选)
    success: function(data) {},              // data为获取的值
    fail: function(data, code) {},
    complete: function() {}
}

// 设置值
{
    key: 'my_key',
    value: 'my_value',                       // 要设置的值
    success: function() {},
    fail: function(data, code) {},
    complete: function() {}
}
设备信息返回格式
javascript 复制代码
{
    brand: 'HUAWEI',                         // 品牌
    manufacturer: 'HUAWEI',                  // 制造商
    model: 'Hi3861',                         // 型号
    product: 'Hi3861',                       // 产品名
    deviceType: 'liteWearable',              // 设备类型
    language: 'zh',                          // 语言
    region: 'CN',                            // 地区
    apiVersion: '6',                         // API版本
    windowWidth: 454,                        // 窗口宽度
    windowHeight: 454,                       // 窗口高度
    screenDensity: 195,                      // 屏幕密度
    screenShape: 'rect'                      // 屏幕形状
}
5.2.2 错误码定义
错误码 常量名 说明
0 NATIVE_SUCCESS 成功
-2 ERROR_FR_NO_FILE 文件不存在
-39 ERROR_DIR_NOT_EMPTY 目录非空
-200 ERROR_CODE_GENERAL 通用错误
-202 ERROR_CODE_PARAM 参数错误
-300 ERROR_CODE_IO I/O错误
-301 ERROR_CODE_NO_FILE 文件不存在
-302 ERROR_CODE_READ_TOO_LONG 读取内容超过4KB

5.3 接口调用时序图

5.3.1 文件读取时序图

JS Engine NativeapiFs fs_impl.c file.c hal_file readText(args) DispatchAsyncWork return undefined [异步线程] GetFullPath() StatImpl() HalFileStat() 返回结果 返回结果 ReadFileImpl() HalFileOpen() 返回fd HalFileRead() 返回数据 HalFileClose() 返回结果 返回数据 SuccessCallBack success({text}) complete() JS Engine NativeapiFs fs_impl.c file.c hal_file

5.3.2 定时器操作时序图

Caller nativeapi_timer kal.c POSIX Timer StartTimerTask() KalTimerCreate() timer_create() 返回结果 返回timerId KalTimerStart() timer_settime() 返回结果 返回结果 返回结果 [定时器超时] SIGEV_THREAD KalFunction() 触发回调 userCallback() StopTimerTask() KalTimerDelete() timer_delete() 返回结果 返回结果 返回结果 Caller nativeapi_timer kal.c POSIX Timer

5.3.3 KV存储操作时序图

JS Engine NativeapiKv kv_impl.c File System set(key, value) DispatchAsyncWork return undefined [异步线程] InitKv() access() 返回结果 mkdir() 返回结果 opt [目录不存在] SetValue() open() 返回fd write() 返回结果 close() 返回结果 SuccessCallBack success() complete() JS Engine NativeapiKv kv_impl.c File System


附录

A. 配置参数说明

参数 默认值 说明
FEATURE_KV_CACHE 启用 KV存储缓存功能开关
MAX_CACHE_SIZE 10 KV缓存最大条目数
MAX_KV_SUM 50 每个应用最大KV存储条目数
KEY_MAX_LEN 32 键名最大长度
VALUE_MAX_LEN 128 值最大长度
FILE_NAME_MAX_LEN 300 文件名最大长度
URI_NAME_MAX_LEN 128 URI最大长度
TEXT_MAX_READ_LEN 4096 单次文本读取最大长度

B. 编译选项

gn 复制代码
# bundle.json中的feature配置
"features": [
    "utils_lite_feature_file",        # 文件操作功能
    "utils_lite_feature_kal_timer",   # KAL定时器功能
    "utils_lite_feature_timer_task",  # 定时任务功能
    "utils_lite_feature_js_builtin"   # JS API功能
]
相关推荐
鸿蒙小白龙1 天前
OpenHarmony LiteOS-A/M 版本迭代与演进对照
分布式·openharmony
狮恒1 天前
OpenHarmony Flutter 分布式数据持久化:跨设备数据一致性与同步方案
分布式·flutter·wpf·openharmony
狮恒2 天前
OpenHarmony Flutter 分布式数据管理:跨设备数据同步与一致性保障方案
分布式·flutter·wpf·openharmony
狮恒2 天前
OpenHarmony Flutter 分布式设备发现与连接:无感组网与设备协同管理方案
分布式·flutter·wpf·openharmony
●VON2 天前
小V健身助手开发手记(四):打造专属健康空间——以 PersonContent构建统一风格的个人中心
人工智能·学习·openharmony·开源鸿蒙·von
●VON2 天前
小V健身助手开发手记(三):用成就点燃坚持——构建可视化激励系统
学习·openharmony·总结·开源鸿蒙·von
狮恒2 天前
OpenHarmony Flutter 分布式音视频:跨设备流传输与实时协同交互方案
分布式·flutter·wpf·openharmony
狮恒2 天前
OpenHarmony Flutter 分布式安全与隐私保护:跨设备可信交互与数据防泄漏方案
分布式·flutter·wpf·openharmony
狮恒2 天前
OpenHarmony Flutter 分布式任务调度:跨设备资源协同与负载均衡方案
分布式·flutter·wpf·openharmony