Service Runtime Layer

[中文]

API Reference

Service Base

Public header: #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::expression::Emote, esp_brookesia::service::Audio, esp_brookesia::service::CustomService, esp_brookesia::service::NVS, esp_brookesia::service::SNTP, esp_brookesia::service::VideoDecoder, esp_brookesia::service::VideoEncoder, esp_brookesia::service::wifi::Wifi

Public Types

using FunctionHandlerMap = std::map<std::string, FunctionHandler>

Map from function names to service-side handlers.

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

Callback invoked with the result of an asynchronous function call.

Public Functions

inline ServiceBase(const Attributes &attributes)

Construct a service with immutable attributes.

Parameters

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}
            }
        }
    };
}

Returns

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}
            }
        }
    };
}

Returns

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)

Parameters
  • 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

Returns

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)

Parameters
  • 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

Returns

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)

Parameters
  • 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

Returns

true if called successfully, false otherwise

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

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

Parameters
  • name[in] Function name to call

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

  • timeout_ms[in] Timeout in milliseconds (default: 100ms)

Returns

FunctionResult Result of the function call

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

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

Parameters
  • name[in] Function name to call

  • parameters_values[in] FunctionParameterMap values (ordered array)

  • timeout_ms[in] Timeout in milliseconds (default: 100ms)

Returns

FunctionResult Result of the function call

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

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

Parameters
  • name[in] Function name to call

  • parameters_json[in] FunctionParameterMap in JSON object format

  • timeout_ms[in] Timeout in milliseconds (default: 100ms)

Returns

FunctionResult Result of the function call

EventRegistry::SignalConnection subscribe_event(const std::string &event_name, const EventRegistry::SignalSlot &slot)

Subscribe to an event.

Parameters
  • event_name[in] Event name to subscribe

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

Returns

EventRegistry::SignalConnection RAII scoped connection object for managing the subscription, automatically disconnects the subscription when the connection object is destroyed.

inline bool is_initialized() const

Check if the service is initialized.

Returns

true if initialized, false otherwise

inline bool is_running() const

Check if the service is running.

Returns

true if running, false otherwise

inline bool is_server_connected() const

Check if the service is connected to server.

Returns

true if connected, false otherwise

inline const Attributes &get_attributes() const

Get the service attributes.

Returns

const Attributes& Reference to service attributes

inline virtual std::string get_call_task_group() const

Get the call task group name.

Returns

std::string Call task group name

inline virtual std::string get_event_task_group() const

Get the event task group name.

Returns

std::string Event task group name

inline virtual std::string get_request_task_group() const

Get the request task group name.

Returns

std::string Request task group name

Public Static Functions

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

Helper function to convert std::expected to FunctionResult.

Template Parameters

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

Parameters

result[in] std::expected object

Returns

FunctionResult Converted result

struct Attributes

Service attributes configuration.

Public Functions

inline bool has_scheduler() const

Check whether a dedicated task scheduler configuration is present.

Returns

true if the service should create its own scheduler.

inline const lib_utils::TaskScheduler::StartConfig &get_scheduler_config() const

Get the dedicated task scheduler configuration.

Note

Call this only when has_scheduler() returns true.

Returns

const lib_utils::TaskScheduler::StartConfig& Config stored in task_scheduler_config.

Public Members

std::string name

Service name.

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

Optional: List of dependent service names, will be started in order.

std::optional<lib_utils::TaskScheduler::StartConfig> 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

bool bindable = true

Optional: Whether the service can be bound.

Macros

BROOKESIA_SERVICE_FUNC_HANDLER_0(func_name, func_call)
BROOKESIA_SERVICE_FUNC_HANDLER_1(func_name, param_name, param_type, func_call)
BROOKESIA_SERVICE_FUNC_HANDLER_2(func_name, param1_name, param1_type, param2_name, param2_type, func_call)
BROOKESIA_SERVICE_FUNC_HANDLER_3(func_name, p1_name, p1_type, p2_name, p2_type, p3_name, p3_type, func_call)

Service Manager

Public header: #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.

Returns

true if valid and service is running, false otherwise

inline explicit operator bool() const

Explicit conversion to bool.

Returns

true if valid, false otherwise

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

Get the service object.

Returns

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.

Parameters

name[in] Dependency service name

Returns

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, and RPC communication.

Public Functions

bool init()

Initialize the service manager.

Returns

true if initialized successfully, false otherwise

void deinit()

Deinitialize the service manager.

bool start(const lib_utils::TaskScheduler::StartConfig &config = DEFAULT_TASK_SCHEDULER_START_CONFIG)

Start the service manager.

Parameters

config[in] Task scheduler start configuration

Returns

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.

Parameters

service[in] Service to add

Returns

true if added successfully, false otherwise

bool remove_service(const std::string &name)

Remove a service by name.

Parameters

name[in] Service name

Returns

true if removed successfully, false otherwise

ServiceBinding bind(const std::string &name)

Bind a service by name.

Parameters

name[in] Service name

Returns

ServiceBinding Service binding handle

bool start_rpc_server(const rpc::Server::Config &config = rpc::Server::Config(), uint32_t timeout_ms = 100)

Start the RPC server.

Parameters
  • config[in] RPC server configuration

  • timeout_ms[in] Timeout in milliseconds (default: 100ms)

Returns

true if started successfully, false otherwise

void stop_rpc_server()

Stop the RPC server.

bool connect_rpc_server_to_services(std::vector<std::string> names = {})

Connect RPC server to services.

Parameters

names[in] Service names to connect (empty means all services)

Returns

true if connected successfully, false otherwise

bool disconnect_rpc_server_from_services(std::vector<std::string> names = {})

Disconnect RPC server from services.

Parameters

names[in] Service names to disconnect (empty means all services)

Returns

true if disconnected successfully, false otherwise

std::shared_ptr<rpc::Client> new_rpc_client(const RPC_ClientConfig &config = RPC_ClientConfig())

Create a new RPC client.

Parameters

config[in] RPC client configuration

Returns

std::shared_ptr<rpc::Client> Shared pointer to the RPC client

FunctionResult call_rpc_function_sync(std::string host, const std::string &service_name, const std::string &function_name, boost::json::object params, uint32_t timeout_ms = BROOKESIA_SERVICE_MANAGER_RPC_CLIENT_CALL_FUNCTION_TIMEOUT_MS, uint16_t port = BROOKESIA_SERVICE_MANAGER_RPC_SERVER_LISTEN_PORT)

Call an RPC function synchronously.

Parameters
  • host[in] Host address

  • service_name[in] Service name

  • function_name[in] Function name

  • params[in] Function parameters in JSON format

  • timeout_ms[in] Timeout in milliseconds (default: configured timeout)

  • port[in] Server port (default: configured port)

Returns

FunctionResult Result of the function call

inline bool is_initialized() const

Check if the service manager is initialized.

Returns

true if initialized, false otherwise

inline bool is_running() const

Check if the service manager is running.

Returns

true if running, false otherwise

inline bool is_rpc_server_running() const

Check if the RPC server is running.

Returns

true if running, false otherwise

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

Get a service by name.

Parameters

name[in] Service name

Returns

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

Public Static Functions

static inline lib_utils::TaskScheduler::StartConfig 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 ServiceManager &get_instance()

Get the singleton instance.

Returns

ServiceManager& Reference to the singleton instance

struct RPC_ClientConfig

Optional callbacks applied to RPC clients created by the manager.

Public Members

rpc::Client::DisconnectCallback on_disconnect_callback

Called after the RPC transport disconnects.

rpc::Client::DeinitCallback on_deinit_callback

Called when the client is deinitialized.

Local Test Runner

Public header: #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.

Parameters
  • config[in] Run tests configuration

  • test_items[in] List of test items

Returns

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.

Parameters
  • service_name[in] Service name to test

  • test_items[in] List of test items

Returns

true if all tests passed, false otherwise

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

Get test results.

Returns

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

struct RunTestsConfig