esp-nimble-cpp 2.6.0
Loading...
Searching...
No Matches
NimBLEStream.h
1/*
2 * Copyright 2020-2025 Ryan Powell <ryan@nable-embedded.io> and
3 * esp-nimble-cpp, NimBLE-Arduino contributors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#ifndef NIMBLE_CPP_STREAM_H
19#define NIMBLE_CPP_STREAM_H
20
21#include "syscfg/syscfg.h"
22#if CONFIG_BT_NIMBLE_ENABLED && (MYNEWT_VAL(BLE_ROLE_PERIPHERAL) || MYNEWT_VAL(BLE_ROLE_CENTRAL))
23
24# ifdef USING_NIMBLE_ARDUINO_HEADERS
25# include "nimble/nimble/include/nimble/nimble_npl.h"
26# else
27# include "nimble/nimble_npl.h"
28# endif
29
30# include <functional>
31# include <type_traits>
32# include <cstdarg>
33
34# ifndef NIMBLE_CPP_ARDUINO_STRING_AVAILABLE
35# define NIMBLE_CPP_ARDUINO_STRING_AVAILABLE (__has_include(<Arduino.h>))
36# endif
37
38# if NIMBLE_CPP_ARDUINO_STRING_AVAILABLE
39# include <Stream.h>
40# else
41
42// Minimal Stream/Print stubs when Arduino not available
43class Print {
44 public:
45 virtual ~Print() {}
46 virtual size_t write(uint8_t) = 0;
47 virtual size_t write(const uint8_t* buffer, size_t size) = 0;
48 size_t print(const char* s);
49 size_t println(const char* s);
50 size_t printf(const char* format, ...) __attribute__((format(printf, 2, 3)));
51};
52
53class Stream : public Print {
54 public:
55 virtual int available() = 0;
56 virtual int read() = 0;
57 virtual int peek() = 0;
58 virtual int availableForWrite() { return 0; }
59 virtual void flush() {}
60 void setTimeout(unsigned long timeout) { m_timeout = timeout; }
61 unsigned long getTimeout() const { return m_timeout; }
62
63 protected:
64 unsigned long m_timeout{0};
65};
66# endif
67
68class NimBLEStream : public Stream {
69 public:
70 enum RxOverflowAction {
71 DROP_OLDER_DATA, // Drop older buffered data to make room for new data
72 DROP_NEW_DATA // Drop new incoming data when buffer is full
73 };
74
75 using RxOverflowCallback = std::function<RxOverflowAction(const uint8_t* data, size_t len, void* userArg)>;
76
77 NimBLEStream() = default;
78 virtual ~NimBLEStream() { end(); }
79
80 // Print/Stream TX methods
81 virtual size_t write(const uint8_t* data, size_t len) override;
82 virtual size_t write(uint8_t data) override { return write(&data, 1); }
83
84 // Template for other integral types (char, int, long, etc.)
85 template <typename T>
86 typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, uint8_t>::value, size_t>::type write(T data) {
87 return write(static_cast<uint8_t>(data));
88 }
89
90 int availableForWrite() override;
91
92 // Read up to len bytes into buffer (non-blocking)
93 size_t read(uint8_t* buffer, size_t len);
94
95 // Stream RX methods
96 virtual int available() override;
97 virtual int read() override;
98 virtual int peek() override;
99 virtual bool ready() const = 0;
100
106 void setRxOverflowCallback(RxOverflowCallback cb, void* userArg = nullptr) {
107 m_rxOverflowCallback = cb;
108 m_rxOverflowUserArg = userArg;
109 }
110
111 operator bool() const { return ready(); }
112
113 using Print::write;
114
115 struct ByteRingBuffer;
116
117 protected:
118 bool begin();
119 void drainTx();
120 size_t pushRx(const uint8_t* data, size_t len);
121 virtual void end();
122 virtual bool send() = 0;
123 static void txDrainEventCb(struct ble_npl_event* ev);
124 static void txDrainCalloutCb(struct ble_npl_event* ev);
125
126 ByteRingBuffer* m_txBuf{nullptr};
127 ByteRingBuffer* m_rxBuf{nullptr};
128 uint8_t m_txChunkBuf[MYNEWT_VAL(BLE_ATT_PREFERRED_MTU)];
129 uint32_t m_txBufSize{1024};
130 uint32_t m_rxBufSize{1024};
131 ble_npl_event m_txDrainEvent{};
132 ble_npl_callout m_txDrainCallout{};
133 RxOverflowCallback m_rxOverflowCallback{nullptr};
134 void* m_rxOverflowUserArg{nullptr};
135 bool m_coInitialized{false};
136 bool m_eventInitialized{false};
137};
138
139# if MYNEWT_VAL(BLE_ROLE_PERIPHERAL)
140# include "NimBLECharacteristic.h"
141
142class NimBLEStreamServer : public NimBLEStream {
143 public:
144 NimBLEStreamServer() : m_charCallbacks(this) {}
145 ~NimBLEStreamServer() override { end(); }
146
147 // non-copyable
148 NimBLEStreamServer(const NimBLEStreamServer&) = delete;
149 NimBLEStreamServer& operator=(const NimBLEStreamServer&) = delete;
150
151 bool begin(NimBLECharacteristic* chr, uint32_t txBufSize = 1024, uint32_t rxBufSize = 1024);
152
153 // Convenience overload to create service/characteristic internally; service will be deleted on end()
154 bool begin(const NimBLEUUID& svcUuid,
155 const NimBLEUUID& chrUuid,
156 uint32_t txBufSize = 1024,
157 uint32_t rxBufSize = 1024,
158 bool secure = false);
159
160 void end() override;
161 size_t write(const uint8_t* data, size_t len) override;
162 uint16_t getPeerHandle() const { return m_charCallbacks.m_peerHandle; }
163 void setCallbacks(NimBLECharacteristicCallbacks* pCallbacks) { m_charCallbacks.m_userCallbacks = pCallbacks; }
164 bool ready() const override;
165 virtual void flush() override;
166
167 using NimBLEStream::write; // Inherit template write overloads
168
169 protected:
170 bool send() override;
171
172 struct ChrCallbacks : public NimBLECharacteristicCallbacks {
173 ChrCallbacks(NimBLEStreamServer* parent)
174 : m_parent(parent), m_userCallbacks(nullptr), m_peerHandle(BLE_HS_CONN_HANDLE_NONE) {}
175 void onWrite(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo) override;
176 void onSubscribe(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo, uint16_t subValue) override;
177 void onStatus(NimBLECharacteristic* pCharacteristic, NimBLEConnInfo& connInfo, int code) override;
178 // override this to avoid recursion when debug logs are enabled
179 void onStatus(NimBLECharacteristic* pCharacteristic, int code) override {
180 if (m_userCallbacks != nullptr) {
181 m_userCallbacks->onStatus(pCharacteristic, code);
182 }
183 }
184
185 NimBLEStreamServer* m_parent;
186 NimBLECharacteristicCallbacks* m_userCallbacks;
187 uint16_t m_peerHandle;
188 } m_charCallbacks;
189
190 NimBLECharacteristic* m_pChr{nullptr};
191 int m_rc{0};
192 // Whether to delete the BLE service when end() is called; set to false if service is managed externally
193 bool m_deleteSvcOnEnd{false};
194};
195# endif // BLE_ROLE_PERIPHERAL
196
197# if MYNEWT_VAL(BLE_ROLE_CENTRAL)
198# include "NimBLERemoteCharacteristic.h"
199
200class NimBLEStreamClient : public NimBLEStream {
201 public:
202 NimBLEStreamClient() = default;
203 ~NimBLEStreamClient() override { end(); }
204
205 // non-copyable
206 NimBLEStreamClient(const NimBLEStreamClient&) = delete;
207 NimBLEStreamClient& operator=(const NimBLEStreamClient&) = delete;
208
209 // Attach a discovered remote characteristic; app owns discovery/connection.
210 // Set subscribeNotify=true to receive notifications into RX buffer.
211 bool begin(NimBLERemoteCharacteristic* pChr,
212 bool subscribeNotify = false,
213 uint32_t txBufSize = 1024,
214 uint32_t rxBufSize = 1024);
215 void end() override;
216 void setNotifyCallback(NimBLERemoteCharacteristic::notify_callback cb) { m_userNotifyCallback = cb; }
217 bool ready() const override;
218 virtual void flush() override;
219
220 using NimBLEStream::write; // Inherit template write overloads
221
222 protected:
223 bool send() override;
224 void notifyCallback(NimBLERemoteCharacteristic* pChar, uint8_t* pData, size_t len, bool isNotify);
225
226 NimBLERemoteCharacteristic* m_pChr{nullptr};
227 NimBLERemoteCharacteristic::notify_callback m_userNotifyCallback{nullptr};
228};
229# endif // BLE_ROLE_CENTRAL
230
231#endif // CONFIG_BT_NIMBLE_ENABLED && (MYNEWT_VAL(BLE_ROLE_PERIPHERAL) || MYNEWT_VAL(BLE_ROLE_CENTRAL))
232#endif // NIMBLE_CPP_STREAM_H
Connection information.
Definition NimBLEConnInfo.h:33
A model of a BLE UUID.
Definition NimBLEUUID.h:41