SerialBLEInterface.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #pragma once
  2. #include "../BaseSerialInterface.h"
  3. #include <bluefruit.h>
  4. #ifndef BLE_TX_POWER
  5. #define BLE_TX_POWER 4
  6. #endif
  7. class SerialBLEInterface : public BaseSerialInterface {
  8. BLEUart bleuart;
  9. bool _isEnabled;
  10. bool _isDeviceConnected;
  11. uint16_t _conn_handle;
  12. unsigned long _last_health_check;
  13. unsigned long _last_retry_attempt;
  14. struct Frame {
  15. uint8_t len;
  16. uint8_t buf[MAX_FRAME_SIZE];
  17. };
  18. #define FRAME_QUEUE_SIZE 12
  19. uint8_t send_queue_len;
  20. Frame send_queue[FRAME_QUEUE_SIZE];
  21. uint8_t recv_queue_len;
  22. Frame recv_queue[FRAME_QUEUE_SIZE];
  23. void clearBuffers();
  24. void shiftSendQueueLeft();
  25. void shiftRecvQueueLeft();
  26. bool isValidConnection(uint16_t handle, bool requireWaitingForSecurity = false) const;
  27. bool isAdvertising() const;
  28. static void onConnect(uint16_t connection_handle);
  29. static void onDisconnect(uint16_t connection_handle, uint8_t reason);
  30. static void onSecured(uint16_t connection_handle);
  31. static bool onPairingPasskey(uint16_t connection_handle, uint8_t const passkey[6], bool match_request);
  32. static void onPairingComplete(uint16_t connection_handle, uint8_t auth_status);
  33. static void onBLEEvent(ble_evt_t* evt);
  34. static void onBleUartRX(uint16_t conn_handle);
  35. public:
  36. SerialBLEInterface() {
  37. _isEnabled = false;
  38. _isDeviceConnected = false;
  39. _conn_handle = BLE_CONN_HANDLE_INVALID;
  40. _last_health_check = 0;
  41. _last_retry_attempt = 0;
  42. send_queue_len = 0;
  43. recv_queue_len = 0;
  44. }
  45. /**
  46. * init the BLE interface.
  47. * @param prefix a prefix for the device name
  48. * @param name IN/OUT - a name for the device (combined with prefix). If "@@MAC", is modified and returned
  49. * @param pin_code the BLE security pin
  50. */
  51. void begin(const char* prefix, char* name, uint32_t pin_code);
  52. void disconnect();
  53. void enable() override;
  54. void disable() override;
  55. bool isEnabled() const override { return _isEnabled; }
  56. bool isConnected() const override;
  57. bool isWriteBusy() const override;
  58. size_t writeFrame(const uint8_t src[], size_t len) override;
  59. size_t checkRecvFrame(uint8_t dest[]) override;
  60. };
  61. #if BLE_DEBUG_LOGGING && ARDUINO
  62. #include <Arduino.h>
  63. #define BLE_DEBUG_PRINT(F, ...) Serial.printf("BLE: " F, ##__VA_ARGS__)
  64. #define BLE_DEBUG_PRINTLN(F, ...) Serial.printf("BLE: " F "\n", ##__VA_ARGS__)
  65. #else
  66. #define BLE_DEBUG_PRINT(...) {}
  67. #define BLE_DEBUG_PRINTLN(...) {}
  68. #endif