跳转到内容

模板传感器

template 传感器平台允许您使用 lambdas 创建具有模板值的传感器。

# 示例配置条目
sensor:
- platform: template
name: "模板传感器"
lambda: |-
if (id(some_binary_sensor).state) {
return 42.0;
} else {
return 0.0;
}
update_interval: 60s

lambda 的可能返回值:

  • return <浮点数>; 传感器的新值。
  • return NAN; 如果状态应被视为无效以指示错误(高级)。
  • return {}; 如果您不想发布新状态(高级)。
  • lambda (可选, lambda): 每个更新间隔要评估的 lambda,以获取传感器的新值

  • update_interval (可选, 时间): 检查传感器的时间间隔。设置为 never 可禁用更新。默认为 60s

  • 传感器的所有其他选项。

您还可以使用 sensor.template.publish 动作从 YAML 文件的其他位置向模板传感器发布状态。

# 示例配置条目
sensor:
- platform: template
name: "模板传感器"
id: template_sens
# 在某个触发器中
on_...:
- sensor.template.publish:
id: template_sens
state: 42.0
# 模板化
- sensor.template.publish:
id: template_sens
state: !lambda 'return 42.0;'

配置选项:

  • id (必需, ID): 模板传感器的 ID。
  • state (必需, 浮点数, 可模板化): 要发布的状态。

NOTE

此动作也可以在 lambdas 中编写:

id(template_sens).publish_state(42.0);

以下是一些用于调试和跟踪蓝牙代理的有用传感器。

# 示例配置条目
sensor:
- platform: template
name: "蓝牙代理连接限制"
id: bluetooth_proxy_connections_limit
icon: "mdi:bluetooth-settings"
update_interval: 30s
entity_category: "diagnostic"
lambda: |-
int limit = bluetooth_proxy::global_bluetooth_proxy->get_bluetooth_connections_limit();
ESP_LOGD("bluetooth_proxy_sensor", "当前连接限制 => %d", limit);
return limit;
- platform: template
name: "蓝牙代理空闲连接"
id: bluetooth_proxy_connections_free
icon: "mdi:bluetooth-settings"
update_interval: 30s
entity_category: "diagnostic"
lambda: |-
int free = bluetooth_proxy::global_bluetooth_proxy->get_bluetooth_connections_free();
ESP_LOGD("bluetooth_proxy_sensor", "当前空闲连接 => %d", free);
return free;