FabGL2 2.0.0
Graphics, audio, GUI and retro-computing library for the ESP32 (ESP-IDF)
Loading...
Searching...
No Matches
blemidi.cpp
1/*
2 Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com>
3 Copyright (c) 2019-2026 Fabrizio Di Vittorio.
4 All rights reserved.
5
6
7* Please contact fdivitto2013@gmail.com if you need a commercial license.
8
9
10* This library and related software is available under GPL v3.
11
12 FabGL is free software: you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
16
17 FabGL is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with FabGL. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26
27#include <string.h>
28
29#include "sdkconfig.h"
30#include "esp_log.h"
31
32#include "blemidi.h"
33
34#if CONFIG_BT_NIMBLE_ENABLED
35 #include "nvs_flash.h"
36 #include "esp_bt.h"
37 #include "nimble/nimble_port.h"
38 #include "nimble/nimble_port_freertos.h"
39 #include "host/ble_hs.h"
40 #include "services/gap/ble_svc_gap.h"
41 #include "services/gatt/ble_svc_gatt.h"
42#endif
43
44
45
46namespace fabgl {
47
48
49static const char * TAG = "BLEMIDI";
50
51static BLEMIDI * s_instance = nullptr;
52
53
54#if CONFIG_BT_NIMBLE_ENABLED
55
56
57// BLE-MIDI service 03B80E5A-EDE8-4B33-A751-6CE34EC4C700
58static const ble_uuid128_t MIDI_SERVICE_UUID = BLE_UUID128_INIT(0x00, 0xC7, 0xC4, 0x4E, 0xE3, 0x6C, 0x51, 0xA7,
59 0x33, 0x4B, 0xE8, 0xED, 0x5A, 0x0E, 0xB8, 0x03);
60
61// BLE-MIDI I/O characteristic 7772E5DB-3868-4112-A1A9-F2669D106BF3
62static const ble_uuid128_t MIDI_CHAR_UUID = BLE_UUID128_INIT(0xF3, 0x6B, 0x10, 0x9D, 0x66, 0xF2, 0xA9, 0xA1,
63 0x12, 0x41, 0x68, 0x38, 0xDB, 0xE5, 0x72, 0x77);
64
65static uint16_t s_charHandle;
66static uint8_t s_ownAddrType;
67static ble_gatt_chr_def s_chars[2];
68static ble_gatt_svc_def s_services[2];
69
70
71static void startAdvertising();
72
73
74// MIDI characteristic: the central writes MIDI packets, a read returns an empty payload (BLE-MIDI specification)
75static int characteristicAccess(uint16_t connHandle, uint16_t attrHandle, ble_gatt_access_ctxt * ctxt, void * arg)
76{
77 if (ctxt->op == BLE_GATT_ACCESS_OP_WRITE_CHR && s_instance) {
78 uint8_t packet[256]; // a write fits in the ATT MTU (at most 251 on the ESP32)
79 uint16_t len = 0;
80 if (ble_hs_mbuf_to_flat(ctxt->om, packet, sizeof(packet), &len) == 0)
81 s_instance->packetReceived(packet, len);
82 }
83 return 0;
84}
85
86
87static int gapEvent(ble_gap_event * event, void * arg)
88{
89 switch (event->type) {
90 case BLE_GAP_EVENT_CONNECT:
91 if (event->connect.status == 0) {
92 ESP_LOGI(TAG, "connected");
93 if (s_instance)
94 s_instance->setConnected(true);
95 } else
96 startAdvertising();
97 break;
98 case BLE_GAP_EVENT_DISCONNECT:
99 ESP_LOGI(TAG, "disconnected, reason 0x%03X", event->disconnect.reason);
100 if (s_instance)
101 s_instance->setConnected(false);
102 startAdvertising();
103 break;
104 case BLE_GAP_EVENT_ADV_COMPLETE:
105 startAdvertising();
106 break;
107 default:
108 break;
109 }
110 return 0;
111}
112
113
114// advertising data: flags + MIDI service UUID (21 of 31 bytes), scan response: device name
115static void startAdvertising()
116{
117 ble_hs_adv_fields fields = { };
118 fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP;
119 fields.uuids128 = (ble_uuid128_t *) &MIDI_SERVICE_UUID;
120 fields.num_uuids128 = 1;
121 fields.uuids128_is_complete = 1;
122 ble_gap_adv_set_fields(&fields);
123
124 ble_hs_adv_fields response = { };
125 const char * name = ble_svc_gap_device_name();
126 response.name = (uint8_t *) name;
127 response.name_len = strlen(name);
128 response.name_is_complete = 1;
129 ble_gap_adv_rsp_set_fields(&response);
130
131 ble_gap_adv_params params = { };
132 params.conn_mode = BLE_GAP_CONN_MODE_UND;
133 params.disc_mode = BLE_GAP_DISC_MODE_GEN;
134 int rc = ble_gap_adv_start(s_ownAddrType, nullptr, BLE_HS_FOREVER, &params, gapEvent, nullptr);
135 if (rc != 0 && rc != BLE_HS_EALREADY)
136 ESP_LOGE(TAG, "ble_gap_adv_start failed (%d)", rc);
137}
138
139
140static void hostSynced()
141{
142 ble_hs_id_infer_auto(0, &s_ownAddrType);
143 startAdvertising();
144}
145
146
147static void hostTask(void * arg)
148{
149 nimble_port_run(); // returns when nimble_port_stop() is called
150 nimble_port_freertos_deinit();
151}
152
153
154#endif // CONFIG_BT_NIMBLE_ENABLED
155
156
157
158BLEMIDI::BLEMIDI()
159 : m_queue(nullptr),
160 m_connected(false),
161 m_dropped(0),
162 m_putCount(0),
163 m_runningStatus(0),
164 m_inSysEx(false)
165{
166}
167
168
169BLEMIDI::~BLEMIDI()
170{
171 // the Bluetooth stack keeps running: the instance must live as long as the application
172 if (s_instance == this)
173 s_instance = nullptr;
174}
175
176
178{
179 #if CONFIG_BT_NIMBLE_ENABLED
180 static bool released = false;
181 if (!released) {
182 esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT);
183 released = true;
184 }
185 #endif
186}
187
188
189bool BLEMIDI::begin(char const * deviceName, int queueSize)
190{
191 #if CONFIG_BT_NIMBLE_ENABLED
192
193 if (s_instance) {
194 ESP_LOGE(TAG, "already started");
195 return false;
196 }
197
198 m_queue = xQueueCreate(queueSize, sizeof(MIDIMessage));
199 if (!m_queue)
200 return false;
201 s_instance = this;
202
203 // NimBLE uses NVS (the application may have already initialized it)
204 nvs_flash_init();
205
206 // releases the classic Bluetooth memory if the application didn't (it can be released only before the init)
208
209 if (nimble_port_init() != ESP_OK) {
210 ESP_LOGE(TAG, "nimble_port_init failed");
211 s_instance = nullptr;
212 vQueueDelete(m_queue);
213 m_queue = nullptr;
214 return false;
215 }
216
217 ble_hs_cfg.sync_cb = hostSynced;
218
219 ble_svc_gap_init();
220 ble_svc_gatt_init();
221
222 memset(s_chars, 0, sizeof(s_chars));
223 memset(s_services, 0, sizeof(s_services));
224 s_chars[0].uuid = &MIDI_CHAR_UUID.u;
225 s_chars[0].access_cb = characteristicAccess;
226 s_chars[0].flags = BLE_GATT_CHR_F_READ | BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_NO_RSP | BLE_GATT_CHR_F_NOTIFY;
227 s_chars[0].val_handle = &s_charHandle;
228 s_services[0].type = BLE_GATT_SVC_TYPE_PRIMARY;
229 s_services[0].uuid = &MIDI_SERVICE_UUID.u;
230 s_services[0].characteristics = s_chars;
231 ble_gatts_count_cfg(s_services);
232 ble_gatts_add_svcs(s_services);
233
234 ble_svc_gap_device_name_set(deviceName);
235
236 nimble_port_freertos_init(hostTask);
237 return true;
238
239 #else
240
241 ESP_LOGE(TAG, "NimBLE is not enabled in sdkconfig (CONFIG_BT_NIMBLE_ENABLED)");
242 return false;
243
244 #endif
245}
246
247
249{
250 return m_queue && xQueueReceive(m_queue, msg, 0) == pdTRUE;
251}
252
253
254void BLEMIDI::putMessage(uint8_t status, uint8_t data1, uint8_t data2)
255{
256 MIDIMessage msg = { status, data1, data2 };
257 if (xQueueSendToBack(m_queue, &msg, 0) == pdTRUE)
258 ++m_putCount;
259 else
260 ++m_dropped;
261}
262
263
264void BLEMIDI::setConnected(bool value)
265{
266 m_connected = value;
267 m_runningStatus = 0;
268 m_inSysEx = false;
269 if (!value) {
270 // notes held on the disconnected device would never receive their Note Off
271 for (int channel = 0; channel < 16; ++channel)
272 putMessage(0xB0 | channel, 123, 0);
273 onMessages();
274 }
275}
276
277
278int BLEMIDI::dataBytes(uint8_t status)
279{
280 switch (status & 0xF0) {
281 case 0xC0: // program change
282 case 0xD0: // channel pressure
283 return 1;
284 case 0xF0: // system messages
285 return status == 0xF2 ? 2 : (status == 0xF1 || status == 0xF3 ? 1 : 0);
286 default: // note off/on, poly pressure, control change, pitch bend
287 return 2;
288 }
289}
290
291
292// BLE-MIDI packet: a header byte (bit 7 set, high bits of the timestamp), then messages. Every status byte is
293// preceded by a timestamp byte (bit 7 set). Running status: data bytes without status, with or without a timestamp.
294// System exclusive messages can span packets (continuation packets start with data bytes after the header) and end
295// with a timestamp + F7. Real-time messages (F8..FF) can appear anywhere, preceded by a timestamp.
296void BLEMIDI::packetReceived(uint8_t const * data, int len)
297{
298 if (len < 2 || !(data[0] & 0x80))
299 return;
300
301 int putCount = m_putCount;
302
303 int i = 1;
304 while (i < len) {
305 uint8_t b = data[i];
306
307 if (b & 0x80) {
308 // timestamp byte
309 if (++i >= len)
310 break;
311 b = data[i];
312 if (!(b & 0x80))
313 continue; // timestamp + data bytes (running status or system exclusive continuation)
314 // timestamp + status byte
315 ++i;
316 if (b >= 0xF8) {
317 // real-time: doesn't change the running status, can be inside a system exclusive
318 if (b != 0xFE) // Active Sensing discarded
319 putMessage(b, 0, 0);
320 continue;
321 }
322 if (b == 0xF0) {
323 m_inSysEx = true;
324 m_runningStatus = 0;
325 continue;
326 }
327 m_inSysEx = false;
328 if (b == 0xF7)
329 continue; // end of system exclusive
330 // system common messages cancel the running status
331 m_runningStatus = b < 0xF0 ? b : 0;
332 int n = dataBytes(b);
333 if (n == 0) {
334 putMessage(b, 0, 0);
335 continue;
336 }
337 if (b >= 0xF0) {
338 // system common with data bytes
339 if (i + n <= len && !(data[i] & 0x80) && (n == 1 || !(data[i + 1] & 0x80)))
340 putMessage(b, data[i], n == 2 ? data[i + 1] : 0);
341 while (i < len && !(data[i] & 0x80))
342 ++i;
343 continue;
344 }
345 }
346
347 // data bytes of the running status
348 if (m_inSysEx || !m_runningStatus) {
349 ++i;
350 continue;
351 }
352 int n = dataBytes(m_runningStatus);
353 if (i + n > len || (data[i] & 0x80) || (n == 2 && (data[i + 1] & 0x80))) {
354 // incomplete message: skip its data bytes
355 while (i < len && !(data[i] & 0x80))
356 ++i;
357 continue;
358 }
359 putMessage(m_runningStatus, data[i], n == 2 ? data[i + 1] : 0);
360 i += n;
361 }
362
363 if (m_putCount != putCount)
364 onMessages();
365}
366
367
368} // end of namespace
This file contains the fabgl::BLEMIDI definition.
bool getMessage(MIDIMessage *msg)
Gets the next received message (non blocking).
Definition blemidi.cpp:248
static void releaseClassicBTMemory()
Releases the internal RAM reserved for classic Bluetooth (BR/EDR), about 15 KB.
Definition blemidi.cpp:177
bool begin(char const *deviceName, int queueSize=64)
Starts the Bluetooth stack and advertises the BLE-MIDI service.
Definition blemidi.cpp:189
MIDI input over Bluetooth Low Energy (BLE-MIDI peripheral).
Definition blemidi.h:104
A MIDI message: status byte and up to two data bytes.
Definition blemidi.h:54