服务自定义
公共头文件:
#include "brookesia/service_custom.hpp"
概述
brookesia_service_custom 为 ESP-Brookesia 生态系统提供即用的 CustomService,支持用户自定义 function 和 event 的注册与调用,无需创建独立的服务组件。
典型使用场景
轻量级功能:对于无需封装为完整 Brookesia 组件的功能(如 LED 控制、PWM、GPIO 翻转、简单传感器等),可通过 CustomService 的接口进行封装和调用。
快速原型:将应用逻辑快速暴露为可调用的 function 或 event,支持本地调用或远程 RPC 访问。
可扩展性:在不修改服务框架的前提下,为应用添加自定义能力。
功能特性
动态注册:运行时通过
register_function()和register_event()注册 function 和 event。固定 Handler 签名:Handler 接收
FunctionParameterMap,返回FunctionResult;支持 lambda、std::function、自由函数、仿函数、std::bind。事件发布/订阅:完整的事件生命周期:注册、发布、订阅、注销。
ServiceManager 集成:与 ServiceManager 配合,支持本地调用和远程 RPC。
可选 Worker:可配置任务调度器,实现线程安全执行。
API 参考
Header File
Classes
-
class CustomService : public esp_brookesia::service::ServiceBase
Dynamic service that lets callers register functions and events at runtime.
Public Functions
-
bool register_function(FunctionSchema schema, FunctionHandler handler)
Register a function for custom service.
- 参数
schema – [in] Function schema
handler – [in] Function handler
- 返回
true if registered successfully, false otherwise
-
bool unregister_function(const std::string &function_name)
Unregister a function.
- 参数
function_name – [in] Function name
- 返回
true if unregistered successfully, false otherwise
-
virtual std::vector<FunctionSchema> get_function_schemas() override
Get currently registered function schemas for custom service.
- 返回
std::vector<FunctionSchema> Function schemas
-
bool register_event(EventSchema event_schema)
Register an event for custom service.
- 参数
event_schema – [in] Event schema to register.
- 返回
true if registered successfully, false otherwise
-
bool unregister_event(const std::string &event_name)
Unregister an event.
- 参数
event_name – [in] Event name
- 返回
true if unregistered successfully, false otherwise
-
bool publish_event(const std::string &event_name, EventItemMap event_items)
Publish an event for custom service.
- 参数
event_name – [in] Event name
event_items – [in] Event items
- 返回
true if published successfully, false otherwise
-
virtual std::vector<EventSchema> get_event_schemas() override
Get currently registered event schemas for custom service.
- 返回
std::vector<EventSchema> Event schemas
Public Static Functions
-
static inline CustomService &get_instance()
Get the process-wide singleton instance.
- 返回
Reference to the singleton custom service.
-
bool register_function(FunctionSchema schema, FunctionHandler handler)