服务运行层

[English]

API 参考

服务基类

公共头文件: #include "brookesia/service_manager/service/base.hpp"

Header File

Classes

class ServiceBase

Base class for bindable services managed by ServiceManager.

Subclasses expose callable functions and publishable events through the function and event registries owned by the service.

Subclassed by esp_brookesia::agent::Base, esp_brookesia::agent::Manager, esp_brookesia::emulation::Nes, esp_brookesia::expression::Emote, esp_brookesia::service::AudioDecoder, esp_brookesia::service::AudioEncoder, esp_brookesia::service::AudioPlayback, esp_brookesia::service::CustomService, esp_brookesia::service::Device, esp_brookesia::service::Display, esp_brookesia::service::ManagerService, esp_brookesia::service::PicoDet, esp_brookesia::service::SNTP, esp_brookesia::service::Storage, esp_brookesia::service::Usb, esp_brookesia::service::UtilsService, esp_brookesia::service::VideoDecoder, esp_brookesia::service::VideoEncoder, esp_brookesia::service::http::Http, esp_brookesia::service::wifi::Wifi

Public Types

enum class SchedulerType

Shared scheduler selected by a service when it does not own a private scheduler.

Values:

enumerator Main
enumerator Secondary
using FunctionHandlerList = std::vector<FunctionHandlerEntry>

Contiguous function handlers used during service registration.

The list is short-lived and ordered exactly like get_function_schemas(). A contiguous handler-only container avoids a temporary tree, duplicate function-name strings, and schema-name lookups for every service.

using FunctionResultHandler = std::function<void(FunctionResult&&)>

Callback invoked with the result of an asynchronous function call.

using FunctionBatchResultHandler = std::function<void(FunctionBatchResult&&)>

Callback invoked with the result of an asynchronous batched function call.

Public Functions

ServiceBase(const Attributes &attributes)

Construct a service with immutable attributes.

参数

attributes -- [in] Public metadata and scheduler preferences for the service.

virtual ~ServiceBase()

Virtual destructor.

inline virtual std::vector<FunctionSchema> get_function_schemas()

Get the function schemas list.

Subclasses should override this method to return an array of function schemas

std::vector<FunctionSchema> get_function_schemas() override {
    return {
        {
            "add", "Add numbers", {
                {"a", "First", FunctionValueType::Number},
                {"b", "Second", FunctionValueType::Number}
            }
        },
        {
            "sub", "Subtract", {
                {"a", "First", FunctionValueType::Number},
                {"b", "Second", FunctionValueType::Number}
            }
        }
    };
}

返回

std::vector<FunctionSchema> List of function schemas

inline virtual std::vector<EventSchema> get_event_schemas()

Get the event schemas list.

Subclasses should override this method to return an array of event schemas

std::vector<EventSchema> get_event_schemas() override {
    return {
        {
            "value_change", "Value changed", {
                {"value", "New value", EventItemType::Number}
            }
        }
    };
}

返回

std::vector<EventSchema> List of event schemas

bool call_function_async(const std::string &name, FunctionParameterMap parameters_map, FunctionResultHandler handler = nullptr)

Call a function asynchronously with parameters map (non-blocking)

参数
  • name -- [in] Function name to call

  • parameters_map -- [in] FunctionParameterMap map (key-value pairs)

  • handler -- [in] FunctionResultHandler to handle the result, if not provided, the result will be ignored

返回

true if called successfully, false otherwise

bool call_function_async(const std::string &name, std::vector<FunctionValue> parameters_values, FunctionResultHandler handler = nullptr)

Call a function asynchronously with parameters values (non-blocking)

参数
  • name -- [in] Function name to call

  • parameters_values -- [in] FunctionParameterMap values (ordered array)

  • handler -- [in] FunctionResultHandler to handle the result, if not provided, the result will be ignored

返回

true if called successfully, false otherwise

bool call_function_async(const std::string &name, const boost::json::object &parameters_json, FunctionResultHandler handler = nullptr)

Call a function asynchronously with JSON parameters (non-blocking)

参数
  • name -- [in] Function name to call

  • parameters_json -- [in] FunctionParameterMap in JSON object format

  • handler -- [in] FunctionResultHandler to handle the result, if not provided, the result will be ignored

返回

true if called successfully, false otherwise

bool call_functions_async(std::vector<FunctionCall> calls, FunctionBatchResultHandler handler = nullptr)

Call multiple functions asynchronously on this service in order.

The batch is fail-fast: once one function fails, later functions are skipped.

参数
  • calls -- [in] Function calls to execute.

  • handler -- [in] FunctionBatchResultHandler to handle the batch result.

返回

true if the batch was accepted, false otherwise

FunctionResult call_function_sync(const std::string &name, FunctionParameterMap parameters_map, uint32_t timeout_ms = 0)

Call a function synchronously with parameters map (blocking with timeout)

参数
  • name -- [in] Function name to call

  • parameters_map -- [in] FunctionParameterMap map (key-value pairs)

  • timeout_ms -- [in] Timeout in milliseconds. 0 uses the function schema default or manager default.

返回

FunctionResult Result of the function call

FunctionResult call_function_sync(const std::string &name, std::vector<FunctionValue> parameters_values, uint32_t timeout_ms = 0)

Call a function synchronously with parameters values (blocking with timeout)

参数
  • name -- [in] Function name to call

  • parameters_values -- [in] FunctionParameterMap values (ordered array)

  • timeout_ms -- [in] Timeout in milliseconds. 0 uses the function schema default or manager default.

返回

FunctionResult Result of the function call

FunctionResult call_function_sync(const std::string &name, const boost::json::object &parameters_json, uint32_t timeout_ms = 0)

Call a function synchronously with JSON parameters (blocking with timeout)

参数
  • name -- [in] Function name to call

  • parameters_json -- [in] FunctionParameterMap in JSON object format

  • timeout_ms -- [in] Timeout in milliseconds. 0 uses the function schema default or manager default.

返回

FunctionResult Result of the function call

FunctionBatchResult call_functions_sync(std::vector<FunctionCall> calls, uint32_t timeout_ms = BROOKESIA_SERVICE_MANAGER_DEFAULT_CALL_FUNCTION_TIMEOUT_MS)

Call multiple functions synchronously on this service in order.

参数
  • calls -- [in] Function calls to execute.

  • timeout_ms -- [in] Timeout in milliseconds.

返回

FunctionBatchResult Result of the batch call

EventSignalConnection subscribe_event(const std::string &event_name, const EventSignalSlot &slot)

Subscribe to an event.

参数
  • event_name -- [in] Event name to subscribe

  • slot -- [in] Callback slot to be invoked when event is published

返回

EventSignalConnection RAII scoped connection object for managing the subscription, automatically disconnects the subscription when the connection object is destroyed.

bool is_initialized() const

Check if the service is initialized.

返回

true if initialized, false otherwise

bool is_running() const

Check if the service is running.

返回

true if running, false otherwise

const Attributes &get_attributes() const

Get the service attributes.

返回

const Attributes& Reference to service attributes

virtual std::string get_call_task_group() const

Get the call task group name.

返回

std::string Call task group name

virtual std::string get_event_task_group() const

Get the event task group name.

返回

std::string Event task group name

virtual std::string get_request_task_group() const

Get the request task group name.

返回

std::string Request task group name

Public Static Functions

static inline std::string make_version(uint32_t major, uint32_t minor, uint32_t patch)

Build a dotted version string from numeric components.

参数
  • major -- [in] Major version number.

  • minor -- [in] Minor version number.

  • patch -- [in] Patch version number.

返回

std::string Version formatted as major.minor.patch.

template<typename T>
static inline FunctionResult to_function_result(std::expected<T, std::string> result)

Helper function to convert std::expected to FunctionResult.

模板参数

T -- Return value type, can be void or any type convertible to FunctionValue

参数

result -- [in] std::expected object

返回

FunctionResult Converted result

struct Attributes

Service attributes configuration.

Public Functions

bool has_scheduler() const

Check whether a dedicated task scheduler configuration is present.

返回

true if the service should create its own scheduler.

const lib_utils::TaskSchedulerStartConfig &get_scheduler_config() const

Get the dedicated task scheduler configuration.

备注

Call this only when has_scheduler() returns true.

返回

const lib_utils::TaskSchedulerStartConfig& Config stored in task_scheduler_config.

Public Members

std::string name

Service name.

std::string description

Human-readable service description.

std::string version

Service version.

std::vector<std::string> dependencies = {}

Optional list of dependent service names, started in order.

std::optional<lib_utils::TaskSchedulerStartConfig> task_scheduler_config = std::nullopt

Optional task scheduler configuration.

If configured, service request tasks will be scheduled to this scheduler; otherwise, ServiceManager's scheduler will be used.

SchedulerType scheduler_type = SchedulerType::Main

Shared scheduler selected when task_scheduler_config is not configured.

bool bindable = true

Optional: Whether the service can be bound.

struct FunctionHandlerEntry

Function handler entry used during service registration.

Macros

BROOKESIA_SERVICE_FUNC_HANDLER_0(func_name, func_call)

Create a zero-parameter function handler.

Example: BROOKESIA_SERVICE_FUNC_HANDLER_0("get_volume", function_get_volume())

参数
  • func_name -- Function name string (e.g., "get_volume")

  • func_call -- Actual function call (e.g., function_get_volume())

BROOKESIA_SERVICE_FUNC_HANDLER_1(func_name, param_name, param_type, func_call)

Create a single-parameter function handler.

Example: BROOKESIA_SERVICE_FUNC_HANDLER_1("play", "url", std::string, function_play(PARAM)) BROOKESIA_SERVICE_FUNC_HANDLER_1("set_volume", "volume", uint8_t, function_set_volume(static_cast<uint8_t>(PARAM)))

参数
  • func_name -- Function name string

  • param_name -- Parameter name string

  • param_type -- Parameter C++ type (e.g., std::string, double)

  • func_call -- Function call, use PARAM as parameter placeholder

BROOKESIA_SERVICE_FUNC_HANDLER_2(func_name, param1_name, param1_type, param2_name, param2_type, func_call)

Create a two-parameter function handler.

Example: BROOKESIA_SERVICE_FUNC_HANDLER_2("add", "a", double, "b", double, function_add(PARAM1, PARAM2))

参数
  • func_name -- Function name string

  • param1_name -- First parameter name

  • param1_type -- First parameter type

  • param2_name -- Second parameter name

  • param2_type -- Second parameter type

  • func_call -- Function call, use PARAM1, PARAM2 as parameter placeholders

BROOKESIA_SERVICE_FUNC_HANDLER_3(func_name, p1_name, p1_type, p2_name, p2_type, p3_name, p3_type, func_call)

Create a three-parameter function handler.

Usage is similar to BROOKESIA_SERVICE_FUNC_HANDLER_2, supports PARAM1, PARAM2, PARAM3

服务管理器

公共头文件: #include "brookesia/service_manager/service/manager.hpp"

Header File

Classes

class ServiceBinding

Service binding handle.

RAII wrapper for service binding that automatically releases the service and its dependencies when the binding goes out of scope.

Public Functions

inline bool is_valid() const

Check if the binding is valid.

返回

true if valid and service is running, false otherwise

inline explicit operator bool() const

Explicit conversion to bool.

返回

true if valid, false otherwise

inline std::shared_ptr<ServiceBase> get_service() const

Get the service object.

返回

std::shared_ptr<ServiceBase> Pointer to the service

inline std::shared_ptr<ServiceBase> get_dependency_service(const std::string &name) const

Get a dependency service by name.

参数

name -- [in] Dependency service name

返回

std::shared_ptr<ServiceBase> Pointer to the dependency service, or nullptr if not found

void release()

Release the service binding.

class ServiceManager

Service manager singleton.

Manages service lifecycle, dependencies, local function calls, and event dispatch.

Public Functions

bool init()

Initialize the service manager.

返回

true if initialized successfully, false otherwise

void deinit()

Deinitialize the service manager.

bool start(const lib_utils::TaskSchedulerStartConfig &config = DEFAULT_TASK_SCHEDULER_START_CONFIG)

Start the service manager.

参数

config -- [in] Task scheduler start configuration

返回

true if started successfully, false otherwise

void stop()

Stop the service manager.

bool add_service(std::shared_ptr<ServiceBase> service)

Add a service to the service manager.

参数

service -- [in] Service to add

返回

true if added successfully, false otherwise

bool remove_service(const std::string &name)

Remove a service by name.

参数

name -- [in] Service name

返回

true if removed successfully, false otherwise

ServiceBinding bind(const std::string &name)

Bind a service by name.

参数

name -- [in] Service name

返回

ServiceBinding Service binding handle

std::vector<std::string> get_service_names() const

Get all registered service names in lexical order.

返回

std::vector<std::string> Registered service names.

std::optional<ServiceInfo> get_service_info(const std::string &name) const

Get a snapshot for one registered service.

参数

name -- [in] Registered service name.

返回

std::optional<ServiceInfo> Snapshot, or empty when the service is not registered.

std::optional<ManagerService::ServiceSchemaOverview> get_service_schema(const std::string &name) const

Get the metadata and member names exposed by one service.

std::optional<FunctionSchema> get_service_function_schema(const std::string &service_name, const std::string &function_name) const

Copy one registered function schema.

std::optional<EventSchema> get_service_event_schema(const std::string &service_name, const std::string &event_name) const

Copy one registered event schema.

dataflow::DataFlowRegistry &get_dataflow_registry()

Get the manager-owned data-flow provider and operation registry.

The registry exists after init() and remains valid until deinit() completes. Provider services use it to register adapters; consumers use it to open typed native operations without linking provider headers.

inline bool is_initialized() const

Check if the service manager is initialized.

返回

true if initialized, false otherwise

inline bool is_running() const

Check if the service manager is running.

返回

true if running, false otherwise

inline std::shared_ptr<ServiceBase> get_service(const std::string &name)

Get a service by name.

参数

name -- [in] Service name

返回

std::shared_ptr<ServiceBase> Pointer to the service, or nullptr if not found

Public Static Functions

static inline lib_utils::TaskSchedulerStartConfig make_default_task_scheduler_start_config()

Default worker configuration used by start().

The configuration creates two worker threads for service dispatching and uses the module-level scheduling defaults defined in macro_configs.h.

static inline lib_utils::TaskSchedulerStartConfig make_default_secondary_task_scheduler_start_config()

Default worker configuration used by the secondary scheduler.

The secondary scheduler is intended for services that need manager-owned workers with internal SRAM stacks.

static inline ServiceManager &get_instance()

Get the singleton instance.

返回

ServiceManager& Reference to the singleton instance

内置 Manager 服务

公共头文件: #include "brookesia/service_manager/service/manager_service.hpp"

Header File

Classes

class ManagerService : public esp_brookesia::service::ServiceBase
struct ServiceInfo
struct ServiceSchemaOverview

内置 Utils 服务

公共头文件: #include "brookesia/service_manager/service/utils_service.hpp"

Header File

Classes

class UtilsService : public esp_brookesia::service::ServiceBase
struct DebugCapabilities
struct DebugConfig
struct DebugRuntimeState
struct DebugSnapshot
struct HeapDebugInfo
struct MemoryDebugSnapshot
struct ThreadDebugSnapshot
struct ThreadTaskDebugInfo

服务本地运行器

公共头文件: #include "brookesia/service_manager/service/local_runner.hpp"

Header File

Classes

class LocalTestRunner

Local service test runner.

A test framework based on TaskScheduler that supports executing test sequences in order, where each test item can specify a start delay and run duration.

Public Functions

bool run_tests(const RunTestsConfig &config, const std::vector<LocalTestItem> &test_items)

Run test sequence.

参数
  • config -- [in] Run tests configuration

  • test_items -- [in] List of test items

返回

true if all tests passed, false otherwise

inline bool run_tests(const std::string &service_name, const std::vector<LocalTestItem> &test_items)

Run test sequence with default configuration.

参数
  • service_name -- [in] Service name to test

  • test_items -- [in] List of test items

返回

true if all tests passed, false otherwise

const std::vector<bool> &get_results() const

Get test results.

返回

const std::vector<bool>& Result of each test item

struct RunTestsConfig