记忆系统在核心 1.1.0 支持了二进制多媒体节点,但那条链路只对**内核自己**开放: 插件把 Triple / Doc 交进来,媒体一律无处安放,且**不报错**。本版补上公开接口 侧缺失的表达能力。 ## 一、类型与接口(全部新增,无签名变更) - `Triple` += `SentenceText`、`MediaDigests` - `Doc` += `MediaDigests`、`Attachments`;新增 `MediaAttachment` - `TextEvent` += `Attachments` - `DocMemoryAPI` += `InsertWithMedia` - `IOInjector` += `InjectInputMedia` / `InjectInputMediaSync` / `InjectInterruptMedia` - `PluginSDK` 补上一直缺失的 `SetToolBlocks` 包装(接口里有、便捷方法里没有, 插件只能自己去拿 injector) `MediaAttachment` 一个类型服务两个方向:给 `Data`+`MIME` 是新内容(内核按字节 去重),只给 `Digest` 是引用已有内容。读路径**只回元数据不回字节**——一次检索 可能命中几十份媒体,把字节全塞回来会撑爆跨进程消息。 媒体注入为什么不能搭 `SetToolBlocks` 的车:那个方法只在工具处理函数内部可用, 且媒体要等**下一条** tool message 才到模型手上。插件主动发起一轮带媒体的对话、 以及中断注入,需要各自的签名,且媒体在**本轮**就随消息发出。 `Triple.MediaDigests` 非空而 `SentenceText` 为空时,内核会用媒体标记本身充当句子 ——媒体引用挂在句子上,没有句子就无处挂起。插件只需填 digest,标记由内核拼: 要求调用方知道格式,等于让一个拼写错误静默切断引用绑定而全链路无人报错。 ## 二、修掉两处并发竞态 `sdk/stress_test.go` 的 `-race` 实测报 11 处 DATA RACE,收敛到两个字段: 1. **`PluginSDK` 的 API 字段无锁**。写方是内核(加载/重载插件时依次注入 injector、memory、doc、llm…),读方是插件在 `Start()` 里起的后台 goroutine ——轮询、监听、定时器都要拿 injector 往管道注消息。生产表现是插件重载瞬间 偶发崩溃:读到半个接口值就 nil 解引用。 2. **`autoRestart` 标志无锁**。`SetAutoRestart` 的文档用法本身就是「外部连接建好 后再决定能否自动重启」,而连接建立通常在后台 goroutine;内核 registry 在另一个 goroutine 读 `AutoRestart()` 决定崩溃后重启策略。这对读写天然跨 goroutine。 加 `apiMu sync.RWMutex`。关键约定写进注释:**只在持锁期间取字段值,取完立刻 释放再调用**。持锁调用会把 `InjectInputSync`(阻塞到 agent 回复,可达数分钟) 与 `SetIOInjector` 串到一起,让插件重载卡死。 ## 三、压测(sdk/stress_test.go,13 例) SDK 是被多个 goroutine 同时使用的共享对象,单线程单测全绿不代表并发路径成立。 断言的是不变量而非吞吐: - 媒体注入高并发不丢不串——每次调用带唯一 tag,逐条校验文本与图片 URL 配对。 「不串」是重点:若实现里出现任何共享中间状态(把 blocks 暂存到字段再读出), 高并发下会出现 A 的文本配 B 的图,而两者单独看都「成功」了; - injector 热替换(含替换成 nil,即内核卸载 API 的真实状态); - stop / onRemove handler 恰好一次——契约是「执行后清空,幂等」,执行两次的后果 从重复写文件到 close 已关闭 channel 直接 panic; - `StageContext` 并发读改写无 lost update(媒体链路让 Extra 成为新热点, 而 map 并发写在 Go 里是直接 fatal,recover 接不住); - `OwnTools` scope 不跨插件泄漏; - 媒体类型 JSON 往返字节级一致(9 种长度,含 0/1/2/3 与 base64 分组边界) ——`[]byte` 在 JSON 里是 base64,往返不一致意味着图片静默损坏, 要到 CAS 校验 digest 时才发现,那时已无从追查; - `omitempty` 真的生效(读路径不能出现 `"data"` 键); - nil 依赖全部静默降级不 panic。 ## 四、工具链同步 - `proc_main.go.tmpl`:`procIO` 三个媒体方法、`procDocMemory.InsertWithMedia`。 模板不跟上的后果是**每个外部插件都编不过**(接口未实现),是硬失败; - `proc_runtime_test.go`:方法清单补 `io.injectMedia*` 与 `doc.insertWithMedia`。 漏接线时插件调 `InjectInputMedia` 会静默无效果——模板不发这个 RPC,内核也就 收不到,两边都不报错; - `yaegi/mocksdk`:与公开 SDK 对齐。它此前漂移严重且**没有任何代码对着它编译**, 所以漂移不会被编译器抓到:`Triple` 用的是 `Predicate`,而公开 SDK 一直叫 `Relation` —— 插件在 yaegi 调试期写 `Relation:` 报未知字段,写 `Predicate:` 则 编成 plugin.bin 时报错,两边都不对。 - README 中英双语补媒体接口文档与用法示例。 ## 兼容性 存量插件不需要改一行也不需要重编:新增方法由**插件调用、内核实现**,不调就不 受影响。17 个 example 插件源码零改动通过类型检查;用 SDK 0.9.2 编的旧 plugin.bin 在新内核上直接建链通过(握手校验的是 ProtocolVersion=1,不是 SDK 版本)。 媒体接口需要核心 1.1.1+(更早的核心没有对应 RPC,调用返回 unknown method)。 `CoreVersion` 保持 1.0.0:它是「SDK 能在其上运行」的下限,媒体是可选能力。
26 KiB
HomeAgent SDK
Plugin development SDK for building intelligent plugins that interact with the HomeAgent platform.
SDK API Surface
Plugin Interface
Plugins implement the Plugin interface:
type Plugin interface {
Name() string
Start(sdk *PluginSDK) error
Stop() error
}
PluginSDK Methods
The SDK instance injected via Start(sdk *PluginSDK) provides:
| Category | Method | Description |
|---|---|---|
| Stage Hooks | RegisterStage(stage, handler, scope...) |
Register stage callback; scope: StageScopeGlobal (all, default) or StageScopeOwnTools (own tools only) |
| Input Channel | RegisterInputChannel(name, def) |
Register input channel with ChannelDef (NoMemory/Cleaner) |
| Output Channel | RegisterOutputChannel(name, caps, desc, def, handler) |
Register output channel with ChannelDef and capability bitmask |
| Tool Registration | RegisterTool(name, def, handler) |
Register a tool for LLM invocation |
| Plugin API | RegisterPluginAPI(name) |
Register plugin API for inter-plugin access |
| Graph Memory | Memory() |
Access graph memory API (entity-relation store) |
| Text Memory | TextMemory() |
Access text memory API (chronological events) |
| Doc Memory | DocMemory() |
Access document memory API (vector store) |
| Social Graph | Social() |
Access social graph API (read-only for external plugins) |
| Knowledge | Knowledge() |
Access knowledge base API |
| LLM | LLM() |
Access LLM provider manager API |
| Settings | Settings() |
Access settings API |
| Events | Events() |
Access event subscriber (subscribe-only for external plugins) |
| Inject | InjectText(source, channel, text) / InjectInterruptText(source, channel, text) / InjectTextNoMemory(source, channel, text) |
Inject text into the agent pipeline |
| Media inject | InjectInputMedia(source, channel, text, blocks) / InjectInputMediaSync(...) / InjectInterruptMedia(...) |
Inject input carrying images/audio (added in 1.1.0) |
| Auto-Restart | SetAutoRestart(enabled) / AutoRestart() |
Control automatic restart on crash |
Stage Hooks
// Listen to all stage events globally
sdk.RegisterStage(StagePreAction, func(ctx *StageContext) error { return nil })
// Listen only to this plugin's own tool calls (before_toolcall / after_toolcall only)
sdk.RegisterStage(StageBeforeToolcall, myHandler, StageScopeOwnTools)
ChannelDef
type ChannelDef struct {
NoMemory bool // Channel input/output skips memory computation (vector/keyword/distill), original text preserved
Cleaner func(string) string // Optional: computation layer filter (does not modify original text)
}
ChannelDef controls channel behavior in the memory computation layer, with the same semantics as ToolDef.NoMemory/Cleaner.
Input Channels
sdk.RegisterInputChannel("qq", ChannelDef{
NoMemory: true,
Cleaner: func(text string) string { return strings.TrimSpace(text) },
})
Output Channels
sdk.RegisterOutputChannel("my-channel", CapText|CapFile, "channel description", ChannelDef{}, handler)
The handler receives three arguments:
payload(string) — message content. Fortype=textit's plain text, fortype=file/imageit's a URLmeta(string) — optional JSON routing metadata (e.g.{"group_id":123,"user_id":456})type(string) — content type enum (see below)
Capability flags:
| Flag | Value | Description |
|---|---|---|
CapText |
1 | Plain text output |
CapFile |
2 | File output |
CapImage |
4 | Image output |
CapAudio |
8 | Audio output |
CapStructured |
16 | Structured data output |
Type enum values:
| Value | Description |
|---|---|
text |
plain text |
voice / audio |
audio/voice |
image |
image |
file |
file |
IOInjector Channel Routing
| Method | Description |
|---|---|
InjectText(source, channel, text) |
Inject text, record to memory, route to specified channel |
InjectInterruptText(source, channel, text) |
Inject interrupt text, interrupt current processing, route to specified channel |
InjectTextNoMemory(source, channel, text) |
Inject text without memory recording, route to specified channel |
Multimodal Injection (added in 1.1.0)
| Method | Description |
|---|---|
InjectInputMedia(source, channel, text, blocks) |
Inject media-bearing input, asynchronous |
InjectInputMediaSync(source, channel, text, blocks) |
Inject media-bearing input and wait for the reply text |
InjectInterruptMedia(source, channel, text, blocks) |
Inject a media-bearing interrupt that can preempt current processing |
blocks is []sdk.ContentBlock, the same type SetToolBlocks takes:
s.InjectInputMedia("myplugin", "webui", "take a look at this", []sdk.ContentBlock{{
Type: "image_url",
ImageURL: &sdk.ImageURL{URL: "data:image/png;base64," + b64, Detail: "auto"},
}})
How this differs from SetToolBlocks: that one is only callable inside a tool handler and
its media reaches the model with the next tool message. These three let a plugin
initiate a turn that carries media — the media goes out with this turn's message and is
automatically stored in the media store with a memory reference attached.
data: URLs in the blocks are stored and deduplicated by the kernel; http(s) URLs are
passed to the model only and never stored (storing them would require the kernel to make
network requests, bringing timeouts, auth and SSRF into scope).
source identifies the origin, channel specifies the target output channel.
Triple Extended Fields
The Triple data structure includes additional fields:
Confidence— confidence score (0.0–1.0)SubjectType— subject typeObjectType— object typeSentenceText— the original sentence (added in 1.1.0), written to thesentencestable; media references hang off the sentenceMediaDigests— associated media digests (added in 1.1.0)
Media in Memory (added in 1.1.0)
Inside plain-text memory, media is represented as a marker of the form
[<mime> <short digest>] <description>:
[image/png a1b2c3d4e5f6] a purple-blue-red three-band chart
The description is the durable semantic memory (retrieval uses it); the digest is the key back to the bytes (reverse lookup uses it). Markers are generated by the kernel — a plugin never has to assemble one, it just supplies the digest.
Graph memory
s.Memory().Commit([]sdk.Triple{{
Subject: "palette", Relation: "contains", Object: "three-band",
MediaDigests: []string{"a1b2c3d4e5f6"}, // short digest is fine, the kernel resolves it
}})
With no SentenceText, the kernel uses the marker itself as the sentence — media must have
a sentence to hang off, otherwise the reference has nowhere to attach.
Knowledge base
s.DocMemory().InsertWithMedia(&sdk.Doc{
Title: "illustrated note",
Content: "body",
}, []sdk.MediaAttachment{
{MIME: "image/png", Data: pngBytes, Name: "chart.png"}, // new content, stored and deduped
{Digest: "a1b2c3d4e5f6"}, // reference existing content
})
Insert keeps its original signature; markers already present in the body are bound as
document-level references too. Query fills MediaDigests and Attachments (mime plus
description, no bytes — one query can match dozens of media items). Removing a document
releases its references.
Text memory
s.TextMemory().Append(sdk.TextEvent{
Role: "user", Content: "look at this",
Attachments: []sdk.MediaAttachment{{MIME: "image/png", Data: pngBytes}},
})
RecentEvents decodes markers in the body back into Attachments.
The media store can be disabled kernel-side (core.memory.media.enabled=false); all of the
above then degrades to plain-text behaviour — no errors, no panics, identical to how it
behaved before this feature shipped.
ToolDef Field Reference
The def parameter of RegisterTool is of type sdk.ToolDef, with the following fields:
| Field | Type | Description |
|---|---|---|
Name |
string |
Tool name, use plugin name prefix to avoid conflicts |
Description |
string |
Tool description, LLM uses this for tool selection |
Parameters |
map[string]interface{} |
JSON Schema parameter definition |
NoMemory |
bool |
Default false; when true, output skips vector/jieba/distill computation (original text preserved) |
Cleaner |
func(string) string |
Optional, filters output before computation layer (e.g., extract .content from JSON) |
For detailed design rationale of NoMemory and Cleaner, see docs/en/PLUGIN_DEV.md in the core repository.
New Constructor
New() is called by the kernel when loading a plugin. Plugin developers do not need to construct PluginSDK manually:
func New(name string, sett SettingsAPI, regTool ToolRegistrar, regStage StageRegistrar, regAPI APIRegistrar, regOutput OutputChannelRegistrar) *PluginSDK
Plugin developers only need to implement the Plugin interface and export a NewPlugin() entry function.
plugindev Toolchain
plugindev provides full development workflow support. Prebuilt binaries ship as release assets
(linux/darwin/windows × amd64/arm64); download from
Releases and put it on your PATH:
# From release assets (v1.0.0 / linux amd64 shown)
curl -Lo plugindev https://gitcode.com/JianFeeeee/homeagent-sdk/releases/download/v1.0.0/plugindev_linux_amd64
chmod +x plugindev
# Or build from source
cd tools/plugindev && go build -o plugindev .
Binaries no longer ship inside the repository (the old
bin/directory is retired): five platforms at 26-28MB each piled another copy into git history on every rebuild, and they are reproducible from source anyway.
| Command | Description |
|---|---|
plugindev init <name> [--lua] |
Initialize plugin project (generates plg.json, plugin.go or main.lua, go.mod, README.md) |
plugindev build [flags] |
Build and package into a .hmap (supports cross-compilation and bundle mode) |
plugindev clean |
Clean build/ and dist/ plus generated files |
plugindev debug [dir] |
Load plugin source through the Yaegi Go interpreter and start an interactive REPL |
plugindev sdk <command> |
SDK version management (list/install/use/path/current/latest) |
Supports both Go and Lua plugin languages.
plg.json Manifest Format
{
"name": "weather",
"name_zh": "天气查询",
"name_en": "Weather",
"version": "1.0.0",
"description": "Weather plugin",
"author": "HomeAgent",
"entry": "plugin.bin",
"tags": ["weather", "forecast"],
"targets": "linux/amd64,windows/amd64",
"outdir": "dist",
"bundle": true,
"replaces": {
"github.com/example/pkg": "../local/pkg"
},
"source_dirs": [
"../shared-lib"
]
}
| Field | Type | Description |
|---|---|---|
name |
string | Plugin identifier |
name_zh |
string | Chinese name |
name_en |
string | English name |
version |
string | Version |
description |
string | Plugin description |
author |
string | Author |
entry |
string | Entry file (plugin.bin / main.lua). Since v1.0.0 Go plugins uniformly build to plugin.bin—no per-platform suffix |
tags |
string[] | Tags |
targets |
string | Build targets, comma-separated (e.g. linux/amd64,windows/amd64) |
outdir |
string | Output directory (default dist) |
bundle |
bool | Bundle mode (build all platforms at once) |
replaces |
object | Go module replacements, key=module path, value=local path |
source_dirs |
string[] | Additional source search paths (auto-imported at build time) |
.hmap Package Format
.hmap is a ZIP archive containing:
plugin.json— plugin metadataplugin.bin— Go compiled artifact (single-platform build)plugin.bin.<goos>.<goarch>— one per platform in bundle mode; on install pluginmgr picks the one matching the current platform and renames it toplugin.binmain.lua— Lua plugin entry (for Lua plugins)
Since v1.0.0
plugin.so/plugin.dll/plugin.dylibare no longer used—the process boundary is the ABI boundary, so there is no platform-specific shared-library distinction. The new kernel will not load old artifacts; it emits an explicit rebuild hint instead.
Plugin Lifecycle
Start & Stop
Start(sdk *PluginSDK) error— Plugin startup, receives SDK instanceStop() error— Plugin shutdown, release resourcessdk.RegisterStopHandler(fn func())— Register a shutdown cleanup callback. The kernel (for built-in plugins) or z_bridge (for external plugins) runs all registered handlers before calling the plugin'sStop()(LIFO order, cleared after running — idempotent). Use it for persistence and cancelling background work: plugin memory is still fresh at that point, avoiding stale-state write-backs that resurrect deleted data.
Remove Cleanup (onRemove)
Stop / RegisterStopHandler run whenever the plugin stops (including reload and disable); RegisterOnRemoveHandler runs only once when the plugin is uninstalled (removed) — never on reload or disable:
sdk.RegisterOnRemoveHandler(fn func())— Register a remove cleanup callback. The kernel runs it after the plugin'sStop()in theRemovePluginflow (LIFO order, cleared after running — idempotent). Use it to delete persistent files the plugin created itself (data/cache/state files).- The kernel also cleans up on uninstall: tool registrations, the
disabled_pluginsrecord, the plugin's config definitions (plugin.<name>.*) and its config table (config_<name>) — the plugin's config section disappears completely after removal. - Examples:
example/calendar(removes events.json),example/memo(removes memos.json),example/rss(removes the subscription data dir),example/weather(removes the cache dir); theplugindevtemplate includes an onRemove demo.
sdk.RegisterOnRemoveHandler(func() {
os.Remove(filepath.Join(dataDir, "events.json"))
})
Auto-Restart
sdk.SetAutoRestart(true)
// Query state
enabled := sdk.AutoRestart()
The platform automatically restarts the plugin on crash, ensuring service availability.
Restricted SDK vs Full SDK
External plugins (third-party distribution) use a restricted SDK that only exposes a safe subset:
| Restricted API | Allowed Operations |
|---|---|
SocialAPI |
Read-only: GetPerson, GetTrait, GetRelations, GetNetwork, ListPersons |
EventSubscriber |
Subscribe-only: Subscribe (no Publish) |
Internal plugins (platform built-in) have full SDK access including SocialAPI write operations and EventPublisher.
Example Plugins
| Plugin | Type | Description |
|---|---|---|
| weather | Go | Weather queries (wttr.in); demonstrates NoMemory/Cleaner/stage hooks/channels/text memory |
| luademo | Lua | Full-featured Lua example covering the whole v0.8.0 Lua SDK surface |
| Go | QQ messaging integration (NapCat), 17 tools, full input/output channel wiring | |
| a2a | Go | Agent-to-Agent protocol communication |
| ai_image | Go | AI image generation |
| bili | Go | Bilibili video downloading |
| browser | Go | Web search, page fetching, browser rendering |
| calendar | Go | Calendar management |
| editdoc | Go | Document editing |
| files | Go | File management |
| memo | Go | Memos (PreAction injection + scheduled reminders) |
| music | Go | Music playback |
| ocr | Go | Optical character recognition |
| rss | Go | RSS subscriptions |
| sanitizer | Go | Content sanitization / safety filtering |
Remote Device SDK
A C language SDK for developing remote device access adapters with zero external dependencies, compatible with embedded platforms.
Architecture
┌─────────────────────────────────────────────────┐
│ ha_remotedevice (C SDK) │
│ Protocol Engine │ WS Frames │ JSON │ State │
│ Machine │ Transport Abstraction │
└──────────┬──────────────────────────────────────┘
│ Same C code, shared by device & app
┌──────┴──────────────────┐
▼ ▼
┌──────────────┐ ┌──────────────────────────┐
│ ESP32 Bare │ │ Linux App │
│ Pure C │ │ (Python ctypes / Go CGo /│
│ Simple Cmd │ │ Node addon / C# P/Invoke)│
└──────────────┘ └──────────────────────────┘
Declarative API Design
The device declares what it is and what it can do in code. The SDK handles all protocol details automatically:
#include "ha_remotedevice.h"
/* Declare capabilities */
const char *caps[] = {"camera", "status", NULL};
ha_config_t config = {
.transport = my_transport, // User implements 4 functions
.server = "192.168.1.100:9890",
.token = "my-token",
.device = {
.device_id = "esp32-cam-1",
.name = "Front Door Camera",
.kind = "camera",
.caps = caps,
},
.on_cmd = my_cmd_handler, // Called when receiving commands
.on_binary = my_data_handler, // Called on binary data (TTS audio, etc.)
.on_state = my_state_handler, // Connection state changes
};
ha_client_t *client = ha_client_new(&config);
ha_client_start(client);
while (1) {
ha_client_process(client); // Main loop processing
}
Transport Layer Abstraction
Users only need to implement 4 functions to adapt to different platforms:
ha_transport_t my_transport = {
.connect = my_tcp_connect, // Establish TCP connection
.send = my_tcp_send, // Send data
.recv = my_tcp_recv, // Receive data (blocking)
.close = my_tcp_close, // Close connection
.ctx = &my_platform_ctx,
};
Protocol Support
| Feature | API |
|---|---|
| WS connection + handshake | Automatic via ha_client_start |
| Device registration (hello/bind) | Automatic on startup |
| Command receive (shell/homeagent) | on_cmd callback |
| Command result | ha_client_send_result |
| Binary chunked transfer (video) | ha_client_send_data_chunked |
| TTS audio receive | on_binary callback |
| Event reporting | ha_client_send_event |
| Status reporting | ha_client_send_status |
| Heartbeat keepalive | Automatic ping/pong |
Usage
Initialize a project via the plugindev toolchain:
plugindev init my-adapter --type remotedevice
Generates main.c + CMakeLists.txt, can be built directly or used as a third-party library:
add_subdirectory(path/to/ha_remotedevice)
target_link_libraries(my_app ha_remotedevice)
target_include_directories(my_app PRIVATE ${HA_REMOTEDEVICE_INCLUDE_DIR})
Quick Start Guide
A complete step-by-step guide from zero to a device successfully connected to HomeAgent.
Step 1: Preparation
Create an access token on the HomeAgent platform:
# Create a device access token on the HomeAgent server
curl -X POST http://<homeagent-server>:8080/api/v1/device/token \
-H "Content-Type: application/json" \
-d '{"device_id":"esp32-cam-1","name":"Front Door Camera","kind":"camera"}'
# Returns: {"token":"ha-dev-token-xxxxx"}
Save the returned token — you'll need it in the device configuration.
Step 2: Implement the Transport Layer (4 functions)
Implement the 4 function pointers of ha_transport_t for your platform. Here are common scenarios:
Scenario A: Embedded device with TCP/IP stack (e.g., ESP32 + lwIP)
#include "ha_remotedevice.h"
#include "lwip/sockets.h"
static int esp_connect(void *ctx, const char *host, uint16_t port) {
struct sockaddr_in addr;
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) return -1;
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
inet_pton(AF_INET, host, &addr.sin_addr);
int ret = connect(sock, (struct sockaddr *)&addr, sizeof(addr));
if (ret < 0) { closesocket(sock); return -1; }
*(int *)ctx = sock;
return 0;
}
static int esp_send(void *ctx, const uint8_t *data, int len) {
int sock = *(int *)ctx;
return send(sock, (const char *)data, len, 0);
}
static int esp_recv(void *ctx, uint8_t *buf, int len) {
int sock = *(int *)ctx;
return recv(sock, (char *)buf, len, 0);
}
static void esp_close(void *ctx) {
int sock = *(int *)ctx;
closesocket(sock);
}
int esp_ctx = -1;
ha_transport_t transport = {
.connect = esp_connect,
.send = esp_send,
.recv = esp_recv,
.close = esp_close,
.ctx = &esp_ctx,
};
Scenario B: Serial (UART) passthrough module
static int uart_connect(void *ctx, const char *host, uint16_t port) {
(void)host; (void)port;
return uart_init((uart_ctx_t *)ctx, 115200);
}
static int uart_send(void *ctx, const uint8_t *data, int len) {
return uart_write((uart_ctx_t *)ctx, data, len);
}
static int uart_recv(void *ctx, uint8_t *buf, int len) {
return uart_read((uart_ctx_t *)ctx, buf, len);
}
static void uart_close(void *ctx) {
uart_deinit((uart_ctx_t *)ctx);
}
Note: For UART passthrough, a TCP bridge program must run on the other end to forward serial data to the HomeAgent WebSocket port.
Step 3: Declare Device Capabilities and Command Handlers
#include "ha_remotedevice.h"
/* Declare device capabilities */
const char *caps[] = {"camera", "speaker", "status", NULL};
/* Handle camerasue command (take photo) */
static ha_status_t handle_camera(const char *req_id, const char *args,
ha_cmd_result_t *result, void *userdata) {
(void)req_id; (void)userdata;
int duration = args[0] ? atoi(args) : 0;
// Capture image, fill the result
result->status = 0;
result->output = "data:image/jpeg;base64,/9j/4AAQ..."; // base64 image data
return HA_OK;
}
/* Handle shell command */
static ha_status_t handle_shell(const char *req_id, const char *args,
ha_cmd_result_t *result, void *userdata) {
(void)req_id; (void)userdata;
result->status = 0;
result->output = "command executed";
return HA_OK;
}
/* Declarative command handler table */
ha_cmd_handler_def_t handlers[] = {
{.command = "shell", .handler = handle_shell},
{.command = "camerasue", .handler = handle_camera},
{.command = "screensee", .handler = handle_camera},
{.command = "speakeruse", .handler = handle_speaker},
{.command = NULL}, /* terminator */
};
Step 4: Configure and Start the Client
ha_config_t config = {
.transport = transport, // Transport layer implementation
.server = "192.168.1.100:9890", // HomeAgent server address
.token = "ha-dev-token-xxxxx", // Token from Step 1
.device = {
.device_id = "esp32-cam-1",
.name = "Front Door Camera",
.kind = "camera",
.caps = caps,
.info_json = "{\"chip\":\"ESP32-S3\",\"firmware\":\"v1.0\"}",
},
.handlers = handlers, // Command handler table
.on_binary = on_binary_data, // Receive TTS audio etc.
.on_state = on_state_change, // Connection state callback
.ping_interval = 30,
};
ha_client_t *client = ha_client_new(&config);
ha_status_t ret = ha_client_start(client);
if (ret != HA_OK) {
printf("Device connection failed: %d\n", ret);
return;
}
/* Main loop */
while (1) {
ha_client_process(client); // Process protocol frames, heartbeats, commands
/* Optional: device-initiated event reporting */
ha_client_send_event(client, "motion_detected",
"{\"zone\":\"front_door\",\"confidence\":0.95}");
/* Optional: report device status */
ha_client_send_status(client, "online");
vTaskDelay(100 / portTICK_PERIOD_MS); // RTOS-style delay
}
Step 5: Verify the Connection
Check if the device is online on the HomeAgent server:
# List registered devices
curl http://<homeagent-server>:8080/api/v1/device/list
# Expected output includes: {"device_id":"esp32-cam-1","status":"online",...}
# Send a command to the device (test camerasue)
curl -X POST http://<homeagent-server>:8080/api/v1/device/esp32-cam-1/cmd \
-H "Content-Type: application/json" \
-d '{"cmd":"camerasue","args":"3"}'
# Expected: {"status":"ok","result":"data:image/jpeg;base64,..."}
Step 6: Debugging Tips
| Issue | Check |
|---|---|
| Connection failed | Verify server address and port are reachable; check token |
| WS handshake failed | Verify HomeAgent server WebSocket support is enabled |
| Command not responding | Confirm the command name is registered in handlers table; check on_binary |
| Reconnection issues | max_reconnect controls retry count; -1 = infinite |
| Low memory (embedded) | Define HA_NO_ALLOC to disable dynamic memory allocation |
Location
- SDK Source:
remotedevice/ - plugindev template:
plugindev init --type remotedevice
Building & Installing
Build
plugindev build
Outputs a .hmap package to the dist/ directory (default is the multi-platform bundle; use plugindev build --no-bundle for a single-target build).
Install
Via the pluginmgr HTTP API (default port 9876, listening on 127.0.0.1 only, no auth):
# Local path
curl -X POST http://127.0.0.1:9876/plugins \
-H "Content-Type: application/json" \
-d '{"path": "/path/to/my-plugin.hmap"}'
# Upload binary directly
curl -X POST http://127.0.0.1:9876/plugins \
--data-binary @dist/my-plugin.hmap
Or upload via the WebUI plugin management page, or manually place the .hmap in the plugin directory and restart the platform.