映射组件
mapping 组件允许您创建一个映射或字典,实现从键到值的一对一转换。这使得可以将字符串映射到数字或反之,或将字符串(如天气状况)映射到图像。
# 示例配置条目mapping: - id: weather_icon from: string to: image entries: clear-night: clear_night_img cloudy: cloudy_img
# 在自动化中使用映射text_sensor: - id: forecast_text platform: homeassistant entity_id: weather.forecast_home on_value: lvgl.image.update: id: weather_image src: !lambda return id(weather_icon)[x];-
from (必需, string):映射中键的类型。可以是
string或int之一。 -
to (必需, string):映射中值的类型。可以是
string或int或下面讨论的类说明符。 -
entries (必需, dict):定义映射的键值对列表。键必须是
from字段中指定的类型,值必须是to字段中指定的类型。
您也可以映射到一个类。当您想映射到更复杂的类型(如图像或颜色)时,这很有用。有几种可用的类说明符:
image:映射到 图像 组件中定义的图像。每个值应该是一个图像 ID。color:映射到预定义的 颜色。每个值应该是一个颜色 ID。- ESPHome 定义的 C++ 类名称,例如
Component。每个值应该是该类的 ID。
在此组件中定义的映射可以在其他组件的 lambda 中使用。可以使用 id 函数访问映射,并使用 [] 运算符或 get 函数查找值,如上例所示。
映射可以在运行时通过 lambda 调用更新,例如 map.set("key", value)。
映射存储在 RAM 中,但如果可用,将使用 PSRAM。
以下是一个更复杂的示例:
mapping: - id: color_map from: int to: color entries: 0: red 1: green 2: blue - id: string_map from: int to: string entries: 0: red 1: green 2: blue
color: - id: red hex: FF0000 - id: green hex: 00FF00 - id: blue hex: 0000FF
font: - file: gfonts://Roboto id: roboto20 size: 20 bpp: 4
display: - platform: ... # 更新显示,绘制随机颜色的随机文本 lambda: |- auto color = color_map.get(random_uint32() % 3); # 使用 get() 索引 color_map it.printf(100, 100, id(roboto20), color, id(string_map)[random_uint32() % 3].c_str(), Color(0));
on_...: then: - lambda: |- id(color_map).set(2, Color::random_color());