Matter Linux 恒温器示例实战:在 Raspberry Pi 上构建、运行并管理 Thermostat Presets

原创2026-09-17 10:15:491,689 阅读
文章标签:物联网智能家居嵌入式IoT协议通信网络蓝牙密码学认证鉴权

Matter Linux 恒温器示例实战:在 Raspberry Pi 上构建、运行并管理 Thermostat Presets

本文以 Matter(connectedhomeip)仓库中的 Linux 恒温器示例为核心,讲解如何在一块 Raspberry Pi 4 上完成工具链安装、应用构建、BLE/WiFi/Thread 命令行参数配置与完整上机运行,并深入剖析 Thermostat 集群 Presets(预设温度场景)功能的实测命令与底层委托实现,帮助读者从零打通一台可被控制器入网、可读写预设场景的 Matter 恒温器设备。

1. 示例定位与运行环境

examples/thermostat/linux 是 Matter SDK 面向 Linux 平台的恒温器(Thermostat)参考实现。官方文档明确标注该示例已在 Ubuntu for Raspberry Pi Server 20.04 LTS (aarch64) 和 Ubuntu for Raspberry Pi Desktop 20.10 (aarch64) 上验证通过,因此文章中的构建与运行步骤均以 Ubuntu 20.04 及以上 ARM64 镜像为前提(原文档见 examples/thermostat/linux/README.md)。

除了树内构建,文档还指出:如果需要以 x64 主机交叉编译该示例、并烧录到 NXP i.MX 8M Mini EVK 运行,应参考专门的交叉编译文档 nxp_imx8m_linux_examples.md,本文不展开该流程。

从构建文件 examples/thermostat/linux/BUILD.gn 可以看出,最终产物是名为 thermostat-app 的可执行文件,其源码仅为本地的 main.cpp 与低功耗管理模块 LowPowerManager.cpp/h,真正的集群业务来自公共依赖:

executable("thermostat-app") {
  sources = [
    "include/low-power/LowPowerManager.cpp",
    "include/low-power/LowPowerManager.h",
    "main.cpp",
  ]

  deps = [
    "${chip_root}/examples/platform/linux:app-main",
    "${chip_root}/examples/thermostat/thermostat-common",
    "${chip_root}/src/lib",
  ]
  ...
}

即:Linux 平台主循环(app-main)+ 跨平台恒温器公共逻辑(thermostat-common,包含各集群委托实现与 thermostat.zap 数据模型定义)+ SDK 核心库(src/lib)。构建参数文件 基于 standalone 平台默认参数,并额外开启了 matter_enable_tracing_support = true。

2. 构建示例

2.1 安装工具链

首先安装 GN/Ninja 构建体系所需依赖:

$ sudo apt-get install git gcc g++ python pkg-config libssl-dev libdbus-1-dev libglib2.0-dev ninja-build python3-venv python3-dev unzip

其中 libssl-dev 用于 SDK 的加密栈,libdbus-1-dev 与 libglib2.0-dev 是 BLE(BlueZ)与系统服务的运行依赖,ninja-build、python3-venv 则是 gn gen 与 Python 激活脚本(activate.sh)的基础。

2.2 编译

$ cd ~/connectedhomeip/examples/thermostat/linux
$ git submodule update --init
$ source third_party/connectedhomeip/scripts/activate.sh
$ gn gen out/debug
$ ninja -C out/debug

说明:

  • third_party/connectedhomeip 是指向仓库根的链接,source 脚本会创建并激活项目所需的 Python 虚拟环境(venv);
  • gn gen out/debug 生成 debug 配置,产物输出到 out/debug/;
  • 构建完成后,可执行文件位于 out/debug/thermostat-app。

2.3 清理产物

$ cd ~/connectedhomeip/examples/thermostat/linux
$ rm -rf out/

删除 out/ 目录即可移除全部可执行文件、库与目标文件。

3. 命令行参数详解

thermostat-app 与其他 Linux 示例共用同一套命令行解析框架,参数在 Options.cpp 的 sDeviceOptionDefs 表中注册,解析结果存入单例 LinuxDeviceOptions 结构体。恒温器文档重点介绍了三个与入网方式直接相关的参数:

参数 参数类型 作用
--wifi 可选 启用 WiFi 管理特性,WiFi 入网(commissioning)时必需。从源码看,Linux 目标下该参数可携带接口名(--wifi=<interface>),用于选择由 wpa_supplicant 管理的网卡
--thread 无参 启用 Thread 管理特性,要求 ot-br-posix 的 dbus 守护进程(ot-agent)在运行,Thread 入网时必需
--ble-device <interface id> 必填整型 指定用于 BLE 广播与连接的蓝牙接口,取值为 hciconfig 列表中 hci 后面的数字,例如 --ble-device 1 表示使用 hci1,默认 0

源码级细节(以当前仓库为准):

  • --ble-device 对应的枚举是 kDeviceOption_BleDevice,其解析处理将参数转为 LinuxDeviceOptions::mBleDevice(Options.h 第 57 行 中默认为 0),与文档描述的“默认 0”一致。需要注意,当前源码注册的选项名是 --ble-controller <selector>(见 Options.cpp 第 170-172 行 的 OptionDef 表),README 中的 --ble-device 与它指向同一标识符、同一处理分支,属于同一参数的不同命名,实际执行时以 --help 输出为准;
  • --wifi 在 Linux 目标下注册为 kArgumentOptional,即 --wifi= wlan0 这种带接口名的形式同样合法(Options.cpp 第 174-179 行);
  • 除上述三项外,框架还支持 --discriminator、--passcode、--spake2p-* 等 PASE 配对码相关参数,以及 --KVS、--interface-id 等通用参数,本文聚焦恒温器文档涉及的部分。

4. 在 Raspberry Pi 4 上运行完整示例

4.1(可选)启用 Echo 协议

如果需要测试 Echo 协议,需要在生成构建配置时打开 chip_app_use_echo:

$ gn gen out/debug --args='chip_app_use_echo=true'
$ ninja -C out/debug

4.2 前置条件

  1. 一块 Raspberry Pi 4 开发板;
  2. 一个 USB 蓝牙适配器。Ubuntu 桌面版会自行发送蓝牙广播,从而阻塞 Matter 通过 BLE 连接;使用 Ubuntu Server 时则需通过 APT 安装 pi-bluetooth 包;
  3. 用于 ARM64 平台的 Ubuntu 20.04 或更新版本的镜像。

4.3 识别蓝牙适配器

插入 USB 蓝牙适配器后,用 hciconfig 查看设备号(hci 后面的数字即设备号,下例中为 1):

$ hciconfig
hci1:  Type: Primary  Bus: USB
    BD Address: 00:1A:7D:AA:BB:CC  ACL MTU: 310:10  SCO MTU: 64:8
    UP RUNNING PSCAN ISCAN
    RX bytes:20942 acl:1023 sco:0 events:1140 errors:0
    TX bytes:16559 acl:1011 sco:0 commands:121 errors:0

hci0:  Type: Primary  Bus: UART
    BD Address: B8:27:EB:AA:BB:CC  ACL MTU: 1021:8  SCO MTU: 64:1
    UP RUNNING PSCAN ISCAN
    RX bytes:8609495 acl:14 sco:0 events:217484 errors:0
    TX bytes:92185 acl:20 sco:0 commands:5259 errors:0

hci0 是板载 UART 蓝牙,hci1 是新插入的 USB 适配器——应使用后者避免与系统默认广播冲突。

4.4 启动应用并用控制器验证

$ cd ~/connectedhomeip/examples/thermostat/linux
$ sudo out/debug/thermostat-app --ble-device [bluetooth device number]
# 本例中要使用的设备是 hci1
$ sudo out/debug/thermostat-app --ble-device 1

启动后,在笔记本/工作站上用 Matter 控制器(ChipDeviceController)对设备执行配对、入网与属性读写测试。

设备端逻辑非常简洁:main.cpp 在 ApplicationInit() 中把六个恒温器相关委托一次性注册到端点 1(gThermostatEndpoint(1)):

constexpr EndpointId gThermostatEndpoint(1);
static Clusters::Thermostat::ThermostatDelegate gThermostatDelegate(gThermostatEndpoint);
static Clusters::Thermostat::ThermostatSetpointsDelegate gSetpointsDelegate(gThermostatEndpoint);
static Clusters::Thermostat::ThermostatHoldDelegate gHoldDelegate(gThermostatEndpoint);
static Clusters::Thermostat::ThermostatPresetsDelegate gPresetsDelegate(gThermostatEndpoint);
static Clusters::Thermostat::ThermostatSuggestionsDelegate gSuggestionsDelegate(gThermostatEndpoint, gPresetsDelegate);
static Clusters::Thermostat::ThermostatSensorsDelegate gSensorsDelegate(gThermostatEndpoint);

随后 main() 只做两件事:ChipLinuxAppInit(argc, argv)(内部完成上面第 3 节所述命令行解析)与 ChipLinuxAppMainLoop()。控制器侧的所有 Presets 操作最终都由 ThermostatPresetsDelegate 承接,这正是下一节的主角。

5. Presets 功能实测与源码剖析

Thermostat 集群(Cluster ID 0x0201)的 Presets 属性(Attribute 0x0050)以结构体数组形式保存“场景-制冷/制热设定值”组合,例如文档中读出的 PresetScenario: 1 / CoolingSetpoint: 2500 / HeatingSetpoint: 2100 表示一个占用场景下制冷 25.0℃、制热 21.0℃ 的预设。以下是 README 给出的完整实测操作序列。

5.1 读取预设(read presets)

chip-tool-x86-64 thermostat read presets <nodeID> 1 | grep TOO
[1758985235.117] [4022:4024] [TOO] Sending command to node 0x1e
[1758985235.347] [4022:4024] [TOO] Sending ReadAttribute to:
[1758985235.347] [4022:4024] [TOO]      cluster 0x0000_0201, attribute: 0x0000_0050, endpoint 1
[1758985235.350] [4022:4024] [TOO] Endpoint: 1 Cluster: 0x0000_0201 Attribute 0x0000_0050 DataVersion: 1113257472
[1758985235.351] [4022:4024] [TOO]   Presets: 2 entries
[1758985235.351] [4022:4024] [TOO]     [1]: {
[1758985235.351] [4022:4024] [TOO]       PresetHandle: 01
[1758985235.351] [4022:4024] [TOO]       PresetScenario: 1
[1758985235.351] [4022:4024] [TOO]       CoolingSetpoint: 2500
[1758985235.351] [4022:4024] [TOO]       HeatingSetpoint: 2100
[1758985235.351] [4022:4024] [TOO]       BuiltIn: TRUE
[1758985235.351] [4022:4024] [TOO]      }
[1758985235.351] [4022:4024] [TOO]     [2]: {
[1758985235.351] [4022:4024] [TOO]       PresetHandle: 02
[1758985235.351] [4022:4024] [TOO]       PresetScenario: 2
[1758985235.351] [4022:4024] [TOO]       CoolingSetpoint: 2600
[1758985235.351] [4022:4024] [TOO]       HeatingSetpoint: 2000
[1758985235.351] [4022:4024] [TOO]       BuiltIn: TRUE
[1758985235.351] [4022:4024] [TOO]      }

两条默认预设(PresetHandle 01/02,BuiltIn 为 TRUE)正是设备初始化时内置的样本数据——这一点与源码完全吻合,见 thermostat-presets-delegate-impl.cpp 的 InitializePresets():

PresetScenarioEnum presetScenarioEnumArray[2] = { PresetScenarioEnum::kOccupied, PresetScenarioEnum::kUnoccupied };
...
int16_t coolingSetpointValue = static_cast<int16_t>(2500 + (index * 100));   // 2500, 2600
int16_t heatingSetpointValue = static_cast<int16_t>(2100 - (index * 100));   // 2100, 2000
mPresets[index].SetBuiltIn(DataModel::MakeNullable(true));

即场景 1(Occupied,占 2500/2100)与场景 2(Unoccupied,占 2600/2000),PresetHandle 取场景枚举值的单字节表示(01、02),与实测输出逐字段对应。

5.2 批量写入三条预设(atomic-request)

先构造三条预设的 JSON 载荷(注意第三条的 presetHandle 为 null,由设备自动分配句柄):

[
    {
        "presetHandle": "01",
        "presetScenario": 1,
        "coolingSetpoint": 2500,
        "heatingSetpoint": 2100,
        "builtIn": true
    },
    {
        "presetHandle": "02",
        "presetScenario": 2,
        "coolingSetpoint": 2600,
        "heatingSetpoint": 2000,
        "builtIn": true
    },
    {
        "presetHandle": null,
        "presetScenario": 3,
        "coolingSetpoint": 2700,
        "heatingSetpoint": 2000,
        "builtIn": false
    }
]

使用 atomic-request 原子写机制(对应 Matter 的 AttributePathIBArray 原子写流程),以下三条命令必须在 3 秒超时内依次执行完:

chip-tool-x86-64 thermostat atomic-request 0 '[80]' <nodeID> 1 --Timeout 3000
chip-tool-x86-64 thermostat write presets '[ { "presetHandle": "01", "presetScenario": 1, "coolingSetpoint": 2500, "heatingSetpoint": 2100, "builtIn": true }, {"presetHandle": "02", "presetScenario": 2, "coolingSetpoint": 2600, "heatingSetpoint": 2000, "builtIn": true }, {"presetHandle": null, "presetScenario": 3, "coolingSetpoint": 2700, "heatingSetpoint": 2000, "builtIn": false } ]' <nodeID> 1
chip-tool-x86-64 thermostat atomic-request 1 '[80]' <nodeID> 1

参数含义:atomic-request 0 发起原子写并指定属性路径 [80](即属性 0x0050 = Presets),--Timeout 3000 为超时(毫秒);中间夹一次 write 完成实际载荷写入;atomic-request 1 提交结束。

3000ms 这个“魔法数字”在设备端有明确出处——GetMaxAtomicWriteTimeout():

std::optional<System::Clock::Milliseconds16> ThermostatPresetsDelegate::GetMaxAtomicWriteTimeout(chip::AttributeId attributeId)
{
    switch (attributeId)
    {
    case Attributes::Presets::Id:
        return std::chrono::milliseconds(3000);
    case Attributes::Schedules::Id:
        return std::chrono::milliseconds(9000);
    case Attributes::SensorSchedule::Id:
        return std::chrono::milliseconds(5000);
    default:
        return std::nullopt;
    }
}

设备侧为 Presets 原子写配置的最大超时正是 3000ms(Schedules 为 9000ms,SensorSchedule 为 5000ms),因此控制器命令中的 --Timeout 3000 与之对齐。

写入过程中设备端按“待提交列表”语义处理:原子写开始副本化现有列表(InitializePendingPresets),每条新增记录追加进 mPendingPresets(AppendToPendingPresetList),全部成功提交时才通过 CommitPendingPresets() 覆盖正式数组(源码第 181-236 行)。这也解释了第三条预设传 presetHandle: null 时为何能正常入库——AppendToPendingPresetList 中检测到空句柄会自动用场景枚举值补一个单字节句柄(源码中附有 TODO:当前每种类型仅支持一个预设,句柄以场景值代替,见 thermostat-presets-delegate-impl.h 第 31-39 行 中的容量常量说明):

static constexpr uint8_t kMaxNumberOfPresetTypes = 6;                      // Occupied/Unoccupied/Sleep/Wake/Vacation/UserDefined
static constexpr uint8_t kMaxNumberOfPresetsOfEachType = 1;
static constexpr uint8_t kMaxNumberOfPresetsSupported = kMaxNumberOfPresetTypes * kMaxNumberOfPresetsOfEachType - 1;  // = 5

从源码结构看,当前实现每种场景类型各支持 1 个预设,且刻意把总容量设为 5(6-1),以测试“写入数量超过支持上限”的异常路径。

5.3 设置当前生效预设(set-active-preset-request)

选择 PresetHandle 02 生效:

chip-tool-x86-64 thermostat set-active-preset-request PresetHandle destination-id endpoint-id-ignored-for-group-commands
chip-tool-x86-64 thermostat set-active-preset-request hex:02 <nodeID> 1 | grep TOO
[1758995147.916] [4607:4609] [TOO] Sending command to node 0x1e
[1758995148.195] [4607:4609] [TOO] Sending cluster (0x00000201) command (0x00000006) on endpoint 1

日志中的 command (0x00000006) 即 Thermostat 集群的 SetActivePreset 命令。设备端 SetActivePresetHandle() 完成校验与落盘:句柄超过 kPresetHandleSize 返回 CHIP_ERROR_NO_MEMORY;成功写入后调用 MatterReportingAttributeChangeCallback(mEndpointId, Thermostat::Id, Attributes::ActivePresetHandle::Id) 触发 ActivePresetHandle 属性变更上报,因此订阅了该属性的控制器能立即感知到 ActivePresetHandle: 02。

5.4 读取当前生效句柄(read active-preset-handle)

chip-tool-x86-64 thermostat read active-preset-handle <nodeID> 1 | grep TOO
[1758995260.093] [4613:4615] [TOO] Sending command to node 0x1e
[1758995260.387] [4613:4615] [TOO] Sending ReadAttribute to:
[1758995260.387] [4613:4615] [TOO]      cluster 0x0000_0201, attribute: 0x0000_004E, endpoint 1
[1758995260.396] [4613:4615] [TOO] Endpoint: 1 Cluster: 0x0000_0201 Attribute 0x0000_004E DataVersion: 1113257472
[1758995260.396] [4613:4615] [TOO]   ActivePresetHandle: 02

读取的 ActivePresetHandle 属性 ID 为 0x004E,与上一步设置的结果 02 一致,闭环验证了“设置-上报-回读”的完整链路。

6. 小结与延伸资源

本文覆盖了 Linux 恒温器示例的完整生命周期:工具链安装与 GN/Ninja 构建、--wifi/--thread/BLE 接口三类入网参数的含义与源码解析、Raspberry Pi 4 上通过 USB 蓝牙适配器运行并配对、以及 Presets 属性“读-原子写-设置当前生效-回读”的全套控制器操作;并对照 thermostat-presets-delegate-impl.cpp 验证了默认预设数值、3000ms 原子写超时、容量上限等文档行为与源码的一致性。

想继续深入可参考:

登录后查看全文
connectedhomeip