开发与设备接入

Keragi 不限于现有客户端:服务端可以加载自定义 WASM 资源,设备也可以通过网关或客户端身份接入消息系统。本页给出接口模型、简单示例与设备接入方式。

1. 两种扩展方式

2. 自定义 WASM 资源

2.1 运行模型

2.2 简单案例:hello + echo

下面是一个最小资源,提供 GET /demo/hello 与 POST /demo/echo。

Cargo.toml:

[package]
name = "hello-resource"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[features]
default = ["wasm"]
wasm = ["wasm-core/wasm"]

[dependencies]
wasm-core = { version = "0.1", default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

src/lib.rs:

use serde::{Deserialize, Serialize};
use wasm_core::{get, post, wasm_handler, wasm_main, Json, Router};

#[wasm_main]
fn router() -> Router {
    Router::new()
        .route("/hello", get(hello))
        .route("/echo", post(echo))
}

#[wasm_handler]
async fn hello() -> String {
    "hello from hello-resource".to_string()
}

#[derive(Deserialize)]
struct EchoRequest {
    message: String,
}

#[derive(Serialize)]
struct EchoResponse {
    message: String,
}

#[wasm_handler]
async fn echo(Json(req): Json<EchoRequest>) -> EchoResponse {
    EchoResponse { message: req.message }
}

构建:

cargo build --release --target wasm32-unknown-unknown \
  --no-default-features --features wasm

产物为 target/wasm32-unknown-unknown/release/hello_resource.wasm。

2.3 打包与安装

资源目录:

hello-resource/
├── package.json
├── wasmx.resource.json
└── wasm/hello.wasm

package.json:

{
  "name": "@example/hello-resource",
  "version": "0.1.0",
  "files": ["wasm", "wasmx.resource.json"]
}

wasmx.resource.json:

{
  "resources": [
    {
      "name": "hello",
      "file": "hello.wasm",
      "config": { "prefix": "/demo", "allow_http": true }
    }
  ]
}

安装并启动:

cp target/wasm32-unknown-unknown/release/hello_resource.wasm \
  hello-resource/wasm/hello.wasm

wasmx add ./hello-resource
wasmx stop
wasmx start

curl http://127.0.0.1:3001/demo/hello
curl -X POST http://127.0.0.1:3001/demo/echo \
  -H 'content-type: application/json' \
  -d '{"message":"hi"}'

示例使用当前 Rust SDK 的接口形态。官方 SDK、宏、模板与示例的对外获取方式将在开发者版本中公布;接口如有调整,以对应版本的 SDK 文档为准。

2.4 数据与鉴权

3. 设备接入

3.1 三种接入模式

模式数据路径能否读取端到端加密消息适用场景
设备作为客户端参与者设备持有独立身份与密钥,加入指定会话/频道能,但仅限其作为成员可解密的会话有安全存储与一定算力的设备
WASM 网关资源设备 ↔ 网关资源 ↔ 消息系统不能解密端到端加密消息;只能处理明文/机器人通道或由客户端桥接传感器、执行器、HTTP/MQTT 设备
本地边缘桥接设备 ↔ 本地桥接程序(客户端)↔ 会话能,桥接机成为可信端点家庭、工业现场、串口/GPIO 设备

加密边界:服务端只持有密文,运行在服务端的 WASM 网关无法解密端到端加密消息。需要读取加密消息的设备,必须以客户端参与者身份加入,或通过本地桥接在客户端侧解密后再控制设备。

3.2 典型数据流

3.3 示例接口

以下是网关资源可以实现的一组接口,具体协议由设备侧决定:

方法路径用途
POST/device/{id}/telemetry上报传感器数据,例如 {"temperature":23.5,"ts":...}
GET/device/{id}/commandsSSE/WebSocket 长连接,接收命令
POST/device/{id}/ack确认命令执行结果
POST/device/{id}/relay控制继电器/执行器,例如 {"channel":1,"on":true}
GET/device/{id}/state查询设备状态

3.4 认证与安全

3.5 执行器与物理安全

重要:继电器、电机、阀门等执行器涉及人身与财产安全。必须设计失效安全(fail-safe)、急停、超时复位、权限校验与人工接管,并在真实负载前完成测试。本文示例仅用于说明软件接入方式,不构成工业安全认证或安全保证。

3.6 ESP32 等设备

4. 相关页面