跳转到内容

映射组件

mapping 组件允许你创建一个映射表或字典,实现键到值的一对一转换。 例如,可以将字符串映射为数字或反之亦然,或者将诸如天气状况之类的字符串映射为图像。

# 示例配置条目
mapping:
- id: weather_icon
from: string
to: image
default_value: unknown_weather_img
entries:
clear-night: clear_night_img
cloudy: cloudy_img
- id: day_map
from: int
to: string
entries:
1: DIM
2: LUN
3: MAR
4: MER
5: JEU
6: VEN
7: SAM
default_value: "---"
# 在自动化中使用映射
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];
  • id (必选, ID): 为映射指定一个 ID,以便你以后在 lambdas 中引用它。

  • from (必选, string): 映射中键的类型。可以是 string 或 int 之一。

  • to (必选, string): 映射中值的类型。可以是 string 或 int 之一,或者是下面讨论的类说明符。

  • entries (必选, dict): 定义映射的一组键值对。键必须是 from 字段中指定的类型,值必须是 to 字段中指定的类型。

  • default_value (可选, value): 当在映射中找不到键时返回的默认值。此值的类型必须与 to 类型匹配。

你还可以映射到类。当你想映射到更复杂的类型(如图像或颜色)时,这很有用。你可以使用以下几种类型的类说明符:

  • image :映射到 Image 组件中定义的图像。每个值都应是一个图像 ID。
  • color :映射到预定义的 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());