Control Surface main
MIDI Control Surface library for Arduino
Loading...
Searching...
No Matches
gatt_midi.cpp
Go to the documentation of this file.
1#if defined(ARDUINO_RASPBERRY_PI_PICO_W) && ENABLE_BLE
2
3#define BTSTACK_FILE__ "gatt_midi.cpp"
4
5#include <atomic>
6#include <cassert>
7#include <csignal>
8#include <cstdint>
9#include <cstdlib>
10#include <cstring>
11
12#include <btstack.h>
13
14#include "../BLEAPI.hpp"
15#include "advertising.hpp"
16#include "gatt_midi.h"
17#include "hci_event_names.hpp"
18
19#include <AH/Arduino-Wrapper.h>
20#include <AH/Debug/Debug.hpp>
21
22namespace cs::midi_ble_btstack {
23
24namespace {
25
26constexpr uint16_t midi_char_value_handle =
28constexpr uint16_t midi_cccd_handle =
30
31MIDIBLEInstance *instance = nullptr;
32btstack_packet_callback_registration_t hci_event_callback_registration;
33
34// callback/event functions
35
36// HCI_SUBEVENT_LE_CONNECTION_COMPLETE
37void connection_handler(uint8_t *packet, [[maybe_unused]] uint16_t size) {
38 if (!instance)
39 return;
40 if (hci_subevent_le_connection_complete_get_status(packet) != 0)
41 return;
42 uint16_t conn_handle =
43 hci_subevent_le_connection_complete_get_connection_handle(packet);
44 instance->handleConnect(BLEConnectionHandle {conn_handle});
45}
46// HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE
47void connection_update_handler([[maybe_unused]] uint8_t *packet,
48 [[maybe_unused]] uint16_t size) {
49 DEBUGREF( // clang-format off
50 "Connection update: status="
51 << hci_subevent_le_connection_update_complete_get_status(packet)
52 << ", connection interval="
53 << hci_subevent_le_connection_update_complete_get_conn_interval(packet)
54 << ", connection latency="
55 << hci_subevent_le_connection_update_complete_get_conn_latency(packet)
56 << ", supervision timeout="
57 << hci_subevent_le_connection_update_complete_get_supervision_timeout(packet));
58 // clang-format on
59}
60// HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST
61void connection_param_req_handler([[maybe_unused]] uint8_t *packet,
62 [[maybe_unused]] uint16_t size) {
63 DEBUGREF( // clang-format off
64 "Connection parameter request: interval min="
65 << hci_subevent_le_remote_connection_parameter_request_get_interval_min(packet)
66 << ", interval max="
67 << hci_subevent_le_remote_connection_parameter_request_get_interval_max(packet)
68 << ", latency="
69 << hci_subevent_le_remote_connection_parameter_request_get_latency(packet)
70 << ", timeout="
71 << hci_subevent_le_remote_connection_parameter_request_get_timeout(packet));
72 // clang-format on
73}
74// HCI_EVENT_LE_META
75void le_packet_handler(uint8_t *packet, uint16_t size) {
76 uint8_t type = hci_event_le_meta_get_subevent_code(packet);
77 DEBUGREF("LE event: " << le_event_names[type] << " (0x" << hex << type
78 << dec << ")");
79 switch (type) {
80 case HCI_SUBEVENT_LE_CONNECTION_COMPLETE:
81 connection_handler(packet, size);
82 break;
83 case HCI_SUBEVENT_LE_CONNECTION_UPDATE_COMPLETE:
84 connection_update_handler(packet, size);
85 break;
86 case HCI_SUBEVENT_LE_REMOTE_CONNECTION_PARAMETER_REQUEST:
87 connection_param_req_handler(packet, size);
88 break;
89 default: break;
90 }
91}
92// HCI_EVENT_LE_META
93void gattservice_handler(uint8_t *packet, [[maybe_unused]] uint16_t size) {
94 [[maybe_unused]] uint8_t type =
95 hci_event_gattservice_meta_get_subevent_code(packet);
96 DEBUGREF("GATT service event: " << gattservice_event_names[type] << " (0x"
97 << hex << type << dec << ")");
98}
99// HCI_EVENT_DISCONNECTION_COMPLETE
100void disconnect_handler(uint8_t *packet, [[maybe_unused]] uint16_t size) {
101 assert(instance);
102 uint16_t conn_handle =
103 hci_event_disconnection_complete_get_connection_handle(packet);
104 instance->handleDisconnect(BLEConnectionHandle {conn_handle});
105}
106// ATT_EVENT_MTU_EXCHANGE_COMPLETE
107void mtu_exchange_complete_handler(uint8_t *packet,
108 [[maybe_unused]] uint16_t size) {
109 assert(instance);
110 uint16_t conn_handle = att_event_mtu_exchange_complete_get_handle(packet);
111 uint16_t mtu = att_event_mtu_exchange_complete_get_MTU(packet);
112 DEBUGREF("mtu=" << mtu);
113 instance->handleMTU(BLEConnectionHandle {conn_handle}, mtu);
114}
115// GATT_EVENT_MTU
116void gatt_event_mtu_handler(uint8_t *packet, [[maybe_unused]] uint16_t size) {
117 assert(instance);
118 uint16_t conn_handle = gatt_event_mtu_get_handle(packet);
119 uint16_t mtu = gatt_event_mtu_get_MTU(packet);
120 instance->handleMTU(BLEConnectionHandle {conn_handle}, mtu);
121}
122// BTSTACK_EVENT_STATE
123void btstack_event_state_handler(uint8_t *packet,
124 [[maybe_unused]] uint16_t size) {
125 if (btstack_event_state_get_state(packet) != HCI_STATE_WORKING)
126 return;
127 bd_addr_t local_addr;
128 gap_local_bd_addr(local_addr);
129 DEBUGREF("BTstack up and running on " << bd_addr_to_str(local_addr));
130}
131
132// Handles all HCI event packets.
133void packet_handler(uint8_t packet_type, [[maybe_unused]] uint16_t channel,
134 uint8_t *packet, uint16_t size) {
135 if (packet_type != HCI_EVENT_PACKET)
136 return;
137 auto type = hci_event_packet_get_type(packet);
138 DEBUGREF("HCI event: " << hci_event_names[type] << " (0x" << hex << type
139 << dec << ")");
140 switch (type) {
141 case HCI_EVENT_LE_META: le_packet_handler(packet, size); break;
142 case HCI_EVENT_GATTSERVICE_META:
143 gattservice_handler(packet, size);
144 break;
145 case HCI_EVENT_DISCONNECTION_COMPLETE:
146 disconnect_handler(packet, size);
147 break;
148 default: break;
149 case ATT_EVENT_MTU_EXCHANGE_COMPLETE:
150 mtu_exchange_complete_handler(packet, size);
151 break;
152 // TODO: what's the difference with the previous one?
153 case GATT_EVENT_MTU: gatt_event_mtu_handler(packet, size); break;
154 case BTSTACK_EVENT_STATE:
155 btstack_event_state_handler(packet, size);
156 break;
157 }
158}
159
160// ATT Client Read Callback for Dynamic Data
161// - if buffer == NULL, don't copy data, just return size of value
162// - if buffer != NULL, copy data and return number bytes copied
163uint16_t att_read_callback([[maybe_unused]] hci_con_handle_t connection_handle,
164 uint16_t att_handle,
165 [[maybe_unused]] uint16_t offset,
166 [[maybe_unused]] uint8_t *buffer,
167 [[maybe_unused]] uint16_t buffer_size) {
168 if (att_handle == midi_char_value_handle)
169 return 0; // MIDI always responds with no data
170 return 0;
171}
172
173int midi_cccd_write(hci_con_handle_t conn_handle, uint8_t *buffer,
174 [[maybe_unused]] uint16_t buffer_size) {
175 assert(instance);
176 bool notify = (little_endian_read_16(buffer, 0) &
177 GATT_CLIENT_CHARACTERISTICS_CONFIGURATION_NOTIFICATION) != 0;
178 instance->handleSubscribe(BLEConnectionHandle {conn_handle},
179 BLECharacteristicHandle {midi_char_value_handle},
180 notify);
181 return 0;
182}
183
184int midi_value_write(hci_con_handle_t conn_handle, uint8_t *buffer,
185 uint16_t buffer_size) {
186 assert(instance);
187 BLEDataView data {buffer, buffer_size};
188 auto data_gen = [data {data}]() mutable { return std::exchange(data, {}); };
189 instance->handleData(
190 BLEConnectionHandle {conn_handle},
191 BLEDataGenerator {compat::in_place, std::move(data_gen)},
193 return 0;
194}
195
196int att_write_callback(hci_con_handle_t conn_handle, uint16_t att_handle,
197 [[maybe_unused]] uint16_t transaction_mode,
198 uint16_t offset, uint8_t *buffer, uint16_t buffer_size) {
199 DEBUGREF("ATT write: handle=" << att_handle << ", offset=" << offset
200 << ", size=" << buffer_size);
201 // Only support regular writes (no prepared/long writes)
202 if (transaction_mode != ATT_TRANSACTION_MODE_NONE)
203 return ATT_ERROR_REQUEST_NOT_SUPPORTED;
204 // Only support writes without offset
205 if (offset != 0)
206 return ATT_ERROR_INVALID_OFFSET;
207 // Client configuration update
208 if (att_handle == midi_cccd_handle)
209 return midi_cccd_write(conn_handle, buffer, buffer_size);
210 // MIDI data received
211 else if (att_handle == midi_char_value_handle)
212 return midi_value_write(conn_handle, buffer, buffer_size);
213 return 0;
214}
215
216void le_midi_setup(const BLESettings &ble_settings) {
217 l2cap_init();
218 // setup SM: no input, no output
219 sm_init();
220 // setup ATT server
221 att_server_init(profile_data, att_read_callback, att_write_callback);
222 // setup advertisements
223 le_midi_setup_adv(ble_settings);
224 // register for HCI events
225 hci_event_callback_registration.callback = &packet_handler;
226 hci_add_event_handler(&hci_event_callback_registration);
227 // register for ATT event
228 att_server_register_packet_handler(packet_handler);
229}
230
231template <class F>
232btstack_context_callback_registration_t create_context_callback(F &f) {
233 btstack_context_callback_registration_t ret {};
234 ret.callback = +[](void *context) { (*static_cast<F *>(context))(); };
235 ret.context = &f;
236 return ret;
237}
238
239} // namespace
240
241bool init(MIDIBLEInstance &instance, BLESettings settings) {
242 cs::midi_ble_btstack::instance = &instance;
243 le_midi_setup(settings);
244 hci_power_control(HCI_POWER_ON);
245 // btstack_run_loop_execute(); // not necessary in background mode
246 return true;
247}
248
249void notify(BLEConnectionHandle conn_handle,
250 BLECharacteristicHandle char_handle, BLEDataView data) {
251 // DEBUGREF("[" << data.length << "] "
252 // << (AH::HexDump {data.data, data.length}));
253 [[maybe_unused]] const auto t0 = micros();
254 // Don't bother sending empty packets
255 if (!data)
256 return;
257 // Flag to know when the can-send-now callback is done
258 volatile std::atomic_bool notify_done {false};
259 // The following is executed in the BTstack can-send-now callback, so it is
260 // synchronized with the BTstack code
261 auto send = [&] {
262 DEBUGREF("notify " << micros() - t0);
263 att_server_notify(conn_handle.conn, char_handle.characteristic,
264 data.data, data.length);
265 DEBUGREF("notify done " << micros() - t0);
266 notify_done.store(true, std::memory_order_release);
267 };
268 auto send_ctx = create_context_callback(send);
269 // The following is executed in the async_context, so it is synchronized
270 // with the BTstack code
271 auto run = [&] {
272 // Request can-send-now callback to be fired later
273 DEBUGREF("req send " << micros() - t0);
274 auto ret = att_server_request_to_send_notification(&send_ctx,
275 conn_handle.conn);
276 assert(ret == ERROR_CODE_SUCCESS);
277 };
278 auto run_ctx = create_context_callback(run);
279 // Schedule the run callback on the BTstack thread, which will then schedule
280 // the send callback as soon as sending data is possible.
281 DEBUGREF("req main thread " << micros() - t0);
282 btstack_run_loop_execute_on_main_thread(&run_ctx);
283 // Wait for the can-send-now callback to clear the flag
284 while (!notify_done.load(std::memory_order_acquire)) tight_loop_contents();
285 DEBUGREF("all done " << micros() - t0);
286}
287
288} // namespace cs::midi_ble_btstack
289
290#endif
Type definitions and callback interfaces for communication between the low-level BLE stacks and highe...
@ ConsumeImmediately
Buffer is valid only during the callback. Do not keep any pointers to it.
Callable that returns the next chunk of data from a BLE packet when called.
Definition BLEAPI.hpp:66
Defines the interface for callback functions registered by the low-level BLE code.
Definition BLEAPI.hpp:127
virtual void handleData(BLEConnectionHandle conn_handle, BLEDataGenerator &&data, BLEDataLifetime lifetime)=0
Called by the BLE stack when the central writes data to the MIDI GATT characteristic.
virtual void handleConnect(BLEConnectionHandle conn_handle)=0
Called by the BLE stack when a connection is established.
virtual void handleSubscribe(BLEConnectionHandle conn_handle, BLECharacteristicHandle char_handle, bool notify)=0
Called by the BLE stack when the central subscribes to receive notifications for the MIDI GATT charac...
virtual void handleDisconnect(BLEConnectionHandle conn_handle)=0
Called by the BLE stack when a connection is terminated.
virtual void handleMTU(BLEConnectionHandle conn_handle, uint16_t mtu)=0
Called by the BLE stack when the maximum transmission unit for the connection changes.
const uint8_t profile_data[]
Definition gatt_midi.h:19
#define ATT_CHARACTERISTIC_7772E5DB_3868_4112_A1A9_F2669D106BF3_01_CLIENT_CONFIGURATION_HANDLE
Definition gatt_midi.h:65
#define ATT_CHARACTERISTIC_7772E5DB_3868_4112_A1A9_F2669D106BF3_01_VALUE_HANDLE
Definition gatt_midi.h:64
#define DEBUGREF(x)
Print an expression and its location (file and line number) to the debug output if debugging is enabl...
Definition Debug.hpp:105
constexpr Note F
F (Fa)
Definition Notes.hpp:61
static in_place_t in_place
Definition compat.hpp:27
bool init(MIDIBLEInstance &instance, BLESettings settings)
constexpr const char * gattservice_event_names[114]
void notify(BLEConnectionHandle conn_handle, BLECharacteristicHandle char_handle, BLEDataView data)
void le_midi_setup_adv(const BLESettings &ble_settings)
constexpr const char * hci_event_names[256]
constexpr const char * le_event_names[42]
Represents a handle to a local GATT characteristic.
Definition BLEAPI.hpp:30
Represents a handle to the connection to another device.
Definition BLEAPI.hpp:19
Non-owning, std::span-style read-only view of BLE data.
Definition BLEAPI.hpp:42
uint16_t length
Definition BLEAPI.hpp:44
const uint8_t * data
Definition BLEAPI.hpp:43
Configuration options for the low-level BLE code.
Definition BLEAPI.hpp:150