core.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # MicroPython aioble module
  2. # MIT license; Copyright (c) 2021 Jim Mussared
  3. import bluetooth
  4. log_level = 1
  5. def log_error(*args):
  6. if log_level > 0:
  7. print("[aioble] E:", *args)
  8. def log_warn(*args):
  9. if log_level > 1:
  10. print("[aioble] W:", *args)
  11. def log_info(*args):
  12. if log_level > 2:
  13. print("[aioble] I:", *args)
  14. class GattError(Exception):
  15. def __init__(self, status):
  16. self._status = status
  17. def ensure_active():
  18. if not ble.active():
  19. try:
  20. from .security import load_secrets
  21. load_secrets()
  22. except:
  23. pass
  24. ble.active(True)
  25. def config(*args, **kwargs):
  26. ensure_active()
  27. return ble.config(*args, **kwargs)
  28. # Because different functionality is enabled by which files are available the
  29. # different modules can register their IRQ handlers and shutdown handlers
  30. # dynamically.
  31. _irq_handlers = []
  32. _shutdown_handlers = []
  33. def register_irq_handler(irq, shutdown):
  34. if irq:
  35. _irq_handlers.append(irq)
  36. if shutdown:
  37. _shutdown_handlers.append(shutdown)
  38. def stop():
  39. ble.active(False)
  40. for handler in _shutdown_handlers:
  41. handler()
  42. # Dispatch IRQs to the registered sub-modules.
  43. def ble_irq(event, data):
  44. log_info(event, data)
  45. for handler in _irq_handlers:
  46. result = handler(event, data)
  47. if result is not None:
  48. return result
  49. # TODO: Allow this to be injected.
  50. ble = bluetooth.BLE()
  51. ble.irq(ble_irq)
  52. __version__ = '0.4.0'