display.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. """ESPHome display platform that dispatches to GxEPD2's panel driver classes.
  2. model: is validated against components/gxepd2/catalog.json, generated by
  3. tools/gxepd2_catalog/generate_catalog.py.
  4. """
  5. import json
  6. from pathlib import Path
  7. import esphome.codegen as cg
  8. import esphome.config_validation as cv
  9. from esphome import pins
  10. from esphome.components import display, spi
  11. from esphome.components.esp32 import add_idf_component
  12. from esphome.const import (
  13. CONF_BUSY_PIN,
  14. CONF_CS_PIN,
  15. CONF_DC_PIN,
  16. CONF_ID,
  17. CONF_MODEL,
  18. CONF_RESET_PIN,
  19. CONF_SPI_ID,
  20. Framework,
  21. )
  22. from esphome.core import CORE
  23. from esphome.types import ConfigType
  24. CODEOWNERS = ["@zib"]
  25. DEPENDENCIES = ["spi"]
  26. # Not in esphome/const.py: only the dual-CS "master+slave" panels need it.
  27. CONF_CS2_PIN = "cs2_pin"
  28. VENDOR_ROOT = Path(__file__).parent / "vendor"
  29. ARDUINO_COMPAT_DIR = Path(__file__).parent / "arduino_compat"
  30. CATALOG_PATH = Path(__file__).parent / "catalog.json"
  31. CATALOG = json.loads(CATALOG_PATH.read_text())
  32. # gxepd2::GxEPD2ColorMode enumerator name for each catalog wrapper class.
  33. COLOR_MODES = {
  34. "GxEPD2_BW": "BW",
  35. "GxEPD2_3C": "THREE_COLOR",
  36. "GxEPD2_4C": "FOUR_COLOR",
  37. "GxEPD2_7C": "SEVEN_COLOR",
  38. }
  39. # USE_GXEPD2_* define gating which wrapper header gxepd2_display.h includes.
  40. WRAPPER_DEFINES = {
  41. "GxEPD2_BW": "USE_GXEPD2_BW",
  42. "GxEPD2_3C": "USE_GXEPD2_3C",
  43. "GxEPD2_4C": "USE_GXEPD2_4C",
  44. "GxEPD2_7C": "USE_GXEPD2_7C",
  45. }
  46. MODELS = {model_id: entry for model_id, entry in CATALOG.items() if entry["wrapper"] in COLOR_MODES}
  47. gxepd2_ns = cg.esphome_ns.namespace("gxepd2")
  48. GxEPD2Display = gxepd2_ns.class_("GxEPD2Display", display.DisplayBuffer)
  49. # GxEPD2's plain int16_t pin ids (PinRegistry keys), assigned at codegen time.
  50. _PIN_ID_KEY = "gxepd2_next_pin_id"
  51. def _allocate_pin_id() -> int:
  52. pin_id = CORE.data.get(_PIN_ID_KEY, 0)
  53. CORE.data[_PIN_ID_KEY] = pin_id + 1
  54. return pin_id
  55. # .cpp files this config needs, accumulated across every gxepd2 instance.
  56. _SOURCES_KEY = "gxepd2_needed_sources"
  57. _SHARED_SOURCE = "GxEPD2_EPD.cpp"
  58. def _write_sources_manifest(source: str) -> None:
  59. needed: set[str] = CORE.data.setdefault(_SOURCES_KEY, {_SHARED_SOURCE})
  60. needed.add(source)
  61. manifest = CORE.relative_src_path("gxepd2_sources.cmake")
  62. manifest.parent.mkdir(parents=True, exist_ok=True)
  63. lines = ["set(GXEPD2_SOURCES"]
  64. lines += [f' "${{CMAKE_CURRENT_SOURCE_DIR}}/src/{path}"' for path in sorted(needed)]
  65. lines.append(")")
  66. manifest.write_text("\n".join(lines) + "\n")
  67. def validate_cs2_pin_required(config: ConfigType) -> ConfigType:
  68. needs_cs2 = MODELS[config[CONF_MODEL]]["ctor_args"] == 5
  69. has_cs2 = CONF_CS2_PIN in config
  70. if needs_cs2 and not has_cs2:
  71. raise cv.Invalid(f"'{CONF_CS2_PIN}' is required for model {config[CONF_MODEL]} (a dual-CS panel)")
  72. if has_cs2 and not needs_cs2:
  73. raise cv.Invalid(f"'{CONF_CS2_PIN}' is not used by model {config[CONF_MODEL]}")
  74. return config
  75. CONFIG_SCHEMA = cv.All(
  76. display.FULL_DISPLAY_SCHEMA.extend(
  77. {
  78. cv.GenerateID(): cv.declare_id(GxEPD2Display),
  79. cv.GenerateID(CONF_SPI_ID): cv.use_id(spi.SPIComponent),
  80. cv.Required(CONF_MODEL): cv.one_of(*MODELS, upper=False),
  81. cv.Required(CONF_CS_PIN): pins.gpio_output_pin_schema,
  82. cv.Required(CONF_DC_PIN): pins.gpio_output_pin_schema,
  83. cv.Optional(CONF_RESET_PIN): pins.gpio_output_pin_schema,
  84. cv.Optional(CONF_BUSY_PIN): pins.gpio_input_pin_schema,
  85. cv.Optional(CONF_CS2_PIN): pins.gpio_output_pin_schema,
  86. }
  87. ),
  88. cv.only_with_framework(Framework.ESP_IDF),
  89. validate_cs2_pin_required,
  90. )
  91. async def to_code(config: ConfigType) -> None:
  92. entry = MODELS[config[CONF_MODEL]]
  93. driver_t = cg.global_ns.class_(entry["driver"])
  94. page_height = f"{entry['driver']}::HEIGHT / {entry['height_divisor']}"
  95. display_t = cg.RawExpression(f"{entry['wrapper']}<{entry['driver']}, {page_height}>")
  96. color_mode = cg.RawExpression(f"gxepd2::GxEPD2ColorMode::{COLOR_MODES[entry['wrapper']]}")
  97. dual_cs = entry["ctor_args"] == 5
  98. specific_type = GxEPD2Display.template(driver_t, display_t, color_mode, dual_cs)
  99. cg.add_define(WRAPPER_DEFINES[entry["wrapper"]])
  100. add_idf_component(name=VENDOR_ROOT.name, path=str(VENDOR_ROOT))
  101. _write_sources_manifest(entry["source"])
  102. cg.add_build_flag(f"-I{ARDUINO_COMPAT_DIR}")
  103. cg.add_build_flag(f"-I{CORE.relative_src_path()}")
  104. cs_id, dc_id = _allocate_pin_id(), _allocate_pin_id()
  105. reset_id = _allocate_pin_id() if CONF_RESET_PIN in config else -1
  106. busy_id = _allocate_pin_id() if CONF_BUSY_PIN in config else -1
  107. ctor_args = [cs_id, dc_id, reset_id, busy_id]
  108. if entry["ctor_args"] == 5:
  109. cs2_id = _allocate_pin_id()
  110. ctor_args.append(cs2_id)
  111. rhs = specific_type.new(*ctor_args)
  112. var = cg.Pvariable(config[CONF_ID], rhs, specific_type)
  113. cg.add(var.set_pin(cs_id, await cg.gpio_pin_expression(config[CONF_CS_PIN])))
  114. cg.add(var.set_pin(dc_id, await cg.gpio_pin_expression(config[CONF_DC_PIN])))
  115. if reset_pin := config.get(CONF_RESET_PIN):
  116. cg.add(var.set_pin(reset_id, await cg.gpio_pin_expression(reset_pin)))
  117. if busy_pin := config.get(CONF_BUSY_PIN):
  118. cg.add(var.set_pin(busy_id, await cg.gpio_pin_expression(busy_pin)))
  119. if entry["ctor_args"] == 5:
  120. cg.add(var.set_pin(cs2_id, await cg.gpio_pin_expression(config[CONF_CS2_PIN])))
  121. spi_parent = await cg.get_variable(config[CONF_SPI_ID])
  122. cg.add(var.set_spi_parent(spi_parent))
  123. await display.register_display(var, config)