__init__.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright (C) 2021-2023 Oxan van Leeuwen
  2. #
  3. # This program is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  15. import esphome.codegen as cg
  16. import esphome.config_validation as cv
  17. from esphome.components import uart
  18. from esphome.const import CONF_ID, CONF_PORT, CONF_BUFFER_SIZE
  19. # ESPHome doesn't know the Stream abstraction yet, so hardcode to use a UART for now.
  20. AUTO_LOAD = ["socket"]
  21. DEPENDENCIES = ["uart", "network"]
  22. MULTI_CONF = True
  23. StreamServerComponent = cg.global_ns.class_("StreamServerComponent", cg.Component)
  24. def validate_buffer_size(buffer_size):
  25. if buffer_size & (buffer_size - 1) != 0:
  26. raise cv.Invalid("Buffer size must be a power of two.")
  27. return buffer_size
  28. CONFIG_SCHEMA = (
  29. cv.Schema(
  30. {
  31. cv.GenerateID(): cv.declare_id(StreamServerComponent),
  32. cv.Optional(CONF_PORT): cv.port,
  33. cv.Optional(CONF_BUFFER_SIZE, default=128): cv.All(
  34. cv.positive_int, validate_buffer_size
  35. ),
  36. }
  37. )
  38. .extend(cv.COMPONENT_SCHEMA)
  39. .extend(uart.UART_DEVICE_SCHEMA)
  40. )
  41. async def to_code(config):
  42. var = cg.new_Pvariable(config[CONF_ID])
  43. if CONF_PORT in config:
  44. cg.add(var.set_port(config[CONF_PORT]))
  45. cg.add(var.set_buffer_size(config[CONF_BUFFER_SIZE]))
  46. await cg.register_component(var, config)
  47. await uart.register_uart_device(var, config)