AWTK-HMI 內置了不少模型,利用這些模型開發應用程序,不需要編寫代碼即可實現常見的應用。但是,有時候我們需要自定義一些命令,以實現一些特殊的功能。
本文檔介紹如何使用 C 語言自定義命令。
1. 實現 hmi_model_cmd_t 接口
1.1 exec 函數
本函數用于執行命令。函數原型如下:
typedef ret_t (*hmi_model_cmd_exec_t)(hmi_model_cmd_t* cmd, tk_object_t* obj, const char* args);
參數:
- cmd: 命令對象
- obj: 默認模型對象
- args: 參數
返回:
- RET_OBJECT_CHANGED 表示模型對象發生了變化,界面自動更新。
- RET_OK 表示命令執行成功,但模型對象沒有發生變化。
- 其他值表示命令執行失敗。
1.2 can_exec 函數
本函數用于判斷命令是否可以執行。函數原型如下:
typedef bool_t (*hmi_model_cmd_can_exec_t)(hmi_model_cmd_t* cmd, tk_object_t* obj, const char* args);
參數:
- cmd: 命令對象
- obj: 默認模型對象
- args: 參數
返回:
- TRUE 表示命令可以執行。
- FALSE 表示命令不能執行。
1.3 聲明命令對象
命令對象一般定義為全局變量。
示例
static const hmi_model_cmd_t s_inc_temp_cmd = { .name = "inc_temp",.exec = inc_temp_exec,.can_exec = inc_temp_can_exec,
};
2.注冊命令
調用函數 hmi_model_add_cmd 注冊命令。
ret_t custom_cmds_init(void) {tk_object_t* model = hmi_service_get_default_model();hmi_model_add_cmd(model, &s_inc_temp_cmd);return RET_OK;
}
3.完整示例
下面的代碼實現了一個命令 inc_temp,用于增加溫度屬性的值。溫度的值小于 100 時,命令可以執行。
#define PROP_TEMP "溫度"static ret_t inc_temp_exec(hmi_model_cmd_t* cmd, tk_object_t* obj, const char* args) {int temp = tk_object_get_prop_int(obj, PROP_TEMP, 0);tk_object_set_prop_int(obj, PROP_TEMP, temp + 1);return RET_OBJECT_CHANGED;
}static bool_t inc_temp_can_exec(hmi_model_cmd_t* cmd, tk_object_t* obj, const char* args) {int temp = tk_object_get_prop_int(obj, PROP_TEMP, 0);return temp < 100;
}static const hmi_model_cmd_t s_inc_temp_cmd = { .name = "inc_temp",.exec = inc_temp_exec,.can_exec = inc_temp_can_exec,
};ret_t custom_cmds_init(void) {tk_object_t* model = hmi_service_get_default_model();hmi_model_add_cmd(model, &s_inc_temp_cmd);return RET_OK;
}
完整示例請參考:demo_custom_cmd