local_mqtt_broker.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Start an anonymous MQTT broker for local bridge testing.
  2. This is intentionally a development-only helper. It binds to loopback and
  3. does not configure authentication or TLS.
  4. """
  5. import argparse
  6. import asyncio
  7. import logging
  8. from amqtt.broker import Broker
  9. def build_config(host: str, port: int) -> dict:
  10. return {
  11. "listeners": {
  12. "default": {
  13. "type": "tcp",
  14. "bind": f"{host}:{port}",
  15. }
  16. },
  17. "auth": {
  18. "allow-anonymous": True,
  19. },
  20. "topic-check": {
  21. "enabled": False,
  22. },
  23. }
  24. async def run(host: str, port: int) -> None:
  25. broker = Broker(build_config(host, port))
  26. await broker.start()
  27. logging.info("local MQTT broker listening on mqtt://%s:%s", host, port)
  28. try:
  29. await asyncio.Event().wait()
  30. finally:
  31. await broker.shutdown()
  32. def main() -> None:
  33. parser = argparse.ArgumentParser(description="Local development MQTT broker")
  34. parser.add_argument("--host", default="127.0.0.1")
  35. parser.add_argument("--port", default=1883, type=int)
  36. args = parser.parse_args()
  37. logging.basicConfig(
  38. level=logging.INFO,
  39. format="%(asctime)s %(levelname)s %(name)s: %(message)s",
  40. )
  41. try:
  42. asyncio.run(run(args.host, args.port))
  43. except KeyboardInterrupt:
  44. pass
  45. if __name__ == "__main__":
  46. main()