ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
ble_midi.cpp
Go to the documentation of this file.
1#include "ble_midi.h"
2
3#ifdef USE_ESP32
4
5#include "esphome/core/log.h"
6
7#include <algorithm>
8#include <cstring>
9
11
12ESPHOME_LOG_TAG(TAG, "ble_midi");
13
14// Standard BLE-MIDI service and characteristic, as defined by the BLE-MIDI
15// specification.
16static constexpr const char *SERVICE_UUID = "03B80E5A-EDE8-4B33-A751-6CE34EC4C700";
17static constexpr const char *CHARACTERISTIC_UUID = "7772E5DB-3868-4112-A1A9-F2669D106BF3";
18
19// MIDI status bytes for the messages this component can transmit.
20static constexpr uint8_t STATUS_NOTE_OFF = 0x80;
21static constexpr uint8_t STATUS_NOTE_ON = 0x90;
22static constexpr uint8_t STATUS_CONTROL_CHANGE = 0xB0;
23static constexpr uint8_t STATUS_PROGRAM_CHANGE = 0xC0;
24static constexpr uint8_t STATUS_PITCH_BEND = 0xE0;
25
26// Number of received bytes included in verbose packet logs.
27static constexpr size_t LOG_MAX_BYTES = 32;
28
30 ESP_LOGCONFIG(TAG,
31 "BLE MIDI:\n"
32 " MAC address: %s\n"
33 " Maximum SysEx size: %u\n"
34 " Pair on connect: %s",
35 this->parent()->address_str(), this->parser_.sysex_capacity(), YESNO(this->pair_));
36}
37
38void BLEMidi::gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) {
39 switch (event) {
40 case ESP_GATTC_OPEN_EVT: {
41 if (param->open.status != ESP_GATT_OK)
42 break;
43 // A warning left by an earlier session no longer applies
45 this->parser_.reset();
46 if (this->pair_) {
47 esp_err_t err = this->parent()->pair();
48 if (err != ESP_OK) {
49 ESP_LOGW(TAG, "Pairing failed, error=%d", err);
50 }
51 }
52 break;
53 }
54 case ESP_GATTC_CFG_MTU_EVT: {
55 if (param->cfg_mtu.status == ESP_GATT_OK)
56 this->mtu_ = param->cfg_mtu.mtu;
57 break;
58 }
59 case ESP_GATTC_DISCONNECT_EVT:
60 case ESP_GATTC_CLOSE_EVT: {
61 this->parser_.reset();
62 this->characteristic_handle_ = 0;
63 this->cccd_handle_ = 0;
64 this->mtu_ = 23;
65 // Both events can arrive for the same disconnect, so the automation runs
66 // only for the one that follows an established MIDI connection.
67 const bool was_ready = this->notify_registered_;
68 this->notify_registered_ = false;
69 this->node_state = espbt::ClientState::IDLE;
70 if (was_ready)
71 this->disconnect_callback_.call();
72 break;
73 }
74 case ESP_GATTC_SEARCH_CMPL_EVT: {
75 if (param->search_cmpl.status != ESP_GATT_OK) {
76 ESP_LOGW(TAG, "Service discovery failed, status=%d", param->search_cmpl.status);
77 this->fail_session_();
78 break;
79 }
80 auto *characteristic = this->parent()->get_characteristic(espbt::ESPBTUUID::from_raw(SERVICE_UUID),
81 espbt::ESPBTUUID::from_raw(CHARACTERISTIC_UUID));
82 // Reconnecting would not help a device without them, so the link is left as it is
83 if (characteristic == nullptr) {
84 this->status_set_warning(LOG_STR("No BLE MIDI characteristic found on this device"));
85 break;
86 }
87 auto *cccd = characteristic->get_descriptor(ESP_GATT_UUID_CHAR_CLIENT_CONFIG);
88 if (cccd == nullptr) {
89 this->status_set_warning(LOG_STR("BLE MIDI characteristic has no notification descriptor"));
90 break;
91 }
92 this->characteristic_handle_ = characteristic->handle;
93 this->cccd_handle_ = cccd->handle;
94 this->write_without_response_ = (characteristic->properties & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) != 0;
95 esp_err_t err = this->parent()->register_for_notify(characteristic->handle);
96 if (err != ESP_OK) {
97 ESP_LOGW(TAG, "register_for_notify failed, error=%d", err);
98 this->fail_session_();
99 }
100 break;
101 }
102 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
103 if (param->reg_for_notify.handle != this->characteristic_handle_)
104 break;
105 if (param->reg_for_notify.status != ESP_GATT_OK) {
106 ESP_LOGW(TAG, "Registering for notifications failed, status=%d", param->reg_for_notify.status);
107 this->fail_session_();
108 }
109 // On success the parent writes the descriptor; the device has accepted it once WRITE_DESCR_EVT reports OK
110 break;
111 }
112 case ESP_GATTC_WRITE_DESCR_EVT: {
113 if (this->cccd_handle_ == 0 || param->write.handle != this->cccd_handle_ || this->notify_registered_)
114 break;
115 if (param->write.status != ESP_GATT_OK) {
116 ESP_LOGW(TAG, "Device refused to enable notifications, status=%d", param->write.status);
117 this->fail_session_();
118 break;
119 }
120 this->notify_registered_ = true;
121 this->node_state = espbt::ClientState::ESTABLISHED;
122 ESP_LOGI(TAG, "MIDI notifications enabled");
123 // The device can only be sent to once notifications are enabled, so this
124 // is the point where on_connect is useful.
125 this->connect_callback_.call();
126 break;
127 }
128 case ESP_GATTC_WRITE_CHAR_EVT: {
129 // A write with response reports its outcome here; one without response reports nothing
130 if (param->write.handle == this->characteristic_handle_ && param->write.status != ESP_GATT_OK) {
131 ESP_LOGW(TAG, "Write rejected, status=%d", param->write.status);
132 }
133 break;
134 }
135 case ESP_GATTC_NOTIFY_EVT: {
136 if (param->notify.handle != this->characteristic_handle_ || param->notify.value_len == 0)
137 break;
138 // format_hex_to() truncates to the buffer size, so long packets are logged
139 // only in part.
140 char hex[format_hex_size(LOG_MAX_BYTES)];
141 ESP_LOGV(TAG, "Received %u bytes: %s", param->notify.value_len,
142 format_hex_to(hex, param->notify.value, param->notify.value_len));
143 this->parser_.feed(param->notify.value, param->notify.value_len, BLEMidi::dispatch_message, this);
144 break;
145 }
146 default:
147 break;
148 }
149}
150
152 this->status_set_warning();
153 // ble_client reconnects, which runs the setup again
154 this->parent()->disconnect();
155}
156
158 ESP_LOGV(
159 TAG, "Decoded %s",
160 LOG_STR_ARG(MessageTypeNames::get_log_str(static_cast<uint8_t>(message.type), MessageTypeNames::LAST_INDEX)));
161 // Only decoded messages reach on_message
163 ESP_LOGW(TAG, "SysEx of %u bytes dropped: cut short, or longer than max_sysex_size (%u)", message.length,
164 this->parser_.sysex_capacity());
165 return;
166 }
167 if (message.type == MessageType::INCOMPLETE) {
168 ESP_LOGW(TAG, "MIDI message 0x%02X dropped: cut short by another status byte", message.status());
169 return;
170 }
171 if (message.type == MessageType::UNKNOWN) {
172 ESP_LOGW(TAG, "Undecodable MIDI byte 0x%02X", message.status());
173 return;
174 }
175 this->message_callback_.call(ByteSpan(message.data, message.length));
176
177 switch (message.type) {
179 this->note_on_callback_.call(message.data1(), message.data2(), message.channel());
180 break;
182 this->note_off_callback_.call(message.data1(), message.data2(), message.channel());
183 break;
185 this->control_change_callback_.call(message.data1(), message.data2(), message.channel());
186 break;
188 this->program_change_callback_.call(message.data1(), message.channel());
189 break;
191 this->pitch_bend_callback_.call(message.pitch_bend(), message.channel());
192 break;
194 // The payload without the 0xF0/0xF7 wrappers; a complete SysEx always has both
195 this->sysex_callback_.call(ByteSpan(message.data + 1, message.length - 2));
196 break;
197 default:
198 // Polyphonic and channel aftertouch, system common and real-time messages
199 // are only reported through on_message.
200 break;
201 }
202}
203
204bool BLEMidi::write_packet_(uint8_t *packet, size_t midi_length) {
205 if (!this->is_ready()) {
206 ESP_LOGW(TAG, "Cannot send: not connected");
207 return false;
208 }
209 // Every BLE-MIDI packet has to fit one ATT packet
210 const size_t packet_length = midi_length + 2;
211 const size_t limit = std::min<size_t>(MAX_TX_MIDI_BYTES + 2, this->mtu_ - 3);
212 if (packet_length > limit) {
213 ESP_LOGW(TAG, "Cannot send: message of %u bytes exceeds the %u byte limit", static_cast<unsigned>(midi_length),
214 static_cast<unsigned>(limit - 2));
215 return false;
216 }
217 packet[0] = PACKET_HEADER;
218 packet[1] = PACKET_TIMESTAMP;
219 esp_err_t err = esp_ble_gattc_write_char(
220 this->parent()->get_gattc_if(), this->parent()->get_conn_id(), this->characteristic_handle_, packet_length,
221 packet, this->write_without_response_ ? ESP_GATT_WRITE_TYPE_NO_RSP : ESP_GATT_WRITE_TYPE_RSP,
222 ESP_GATT_AUTH_REQ_NONE);
223 if (err != ESP_OK) {
224 ESP_LOGW(TAG, "Write failed, error=%d", err);
225 return false;
226 }
227 char hex[format_hex_size(LOG_MAX_BYTES)];
228 ESP_LOGV(TAG, "Sent %u bytes: %s", static_cast<unsigned>(packet_length), format_hex_to(hex, packet, packet_length));
229 return true;
230}
231
232bool BLEMidi::write_midi_(const uint8_t *midi_bytes, size_t length) {
233 if (length == 0 || length > MAX_TX_MIDI_BYTES) {
234 ESP_LOGW(TAG, "Cannot send: message of %u bytes, the limit is %u", static_cast<unsigned>(length),
235 static_cast<unsigned>(MAX_TX_MIDI_BYTES));
236 return false;
237 }
238 uint8_t packet[MAX_TX_MIDI_BYTES + 2];
239 std::memcpy(packet + 2, midi_bytes, length);
240 return this->write_packet_(packet, length);
241}
242
243void BLEMidi::send_channel_(uint8_t status, int32_t channel, int32_t data1, int32_t data2, size_t length) {
244 // Validation covers constants only; a lambda can return any value, and masking it would send a different message.
245 // The values arrive unnarrowed so a negative or wrapped one is caught here (the unsigned compare covers negatives).
246 if (static_cast<uint32_t>(channel) > 0x0F || static_cast<uint32_t>(data1) > 0x7F ||
247 static_cast<uint32_t>(data2) > 0x7F) {
248 ESP_LOGW(TAG, "Cannot send: channel %" PRId32 " or value %" PRId32 "/%" PRId32 " out of range", channel, data1,
249 data2);
250 return;
251 }
252 const uint8_t bytes[3] = {static_cast<uint8_t>(status | channel), static_cast<uint8_t>(data1),
253 static_cast<uint8_t>(data2)};
254 this->write_midi_(bytes, length);
255}
256
257void BLEMidi::send_note_on(int32_t note, int32_t velocity, int32_t channel) {
258 this->send_channel_(STATUS_NOTE_ON, channel, note, velocity, 3);
259}
260
261void BLEMidi::send_note_off(int32_t note, int32_t velocity, int32_t channel) {
262 this->send_channel_(STATUS_NOTE_OFF, channel, note, velocity, 3);
263}
264
265void BLEMidi::send_control_change(int32_t control_number, int32_t value, int32_t channel) {
266 this->send_channel_(STATUS_CONTROL_CHANGE, channel, control_number, value, 3);
267}
268
269void BLEMidi::send_program_change(int32_t program, int32_t channel) {
270 this->send_channel_(STATUS_PROGRAM_CHANGE, channel, program, 0, 2);
271}
272
273void BLEMidi::send_pitch_bend(int32_t value, int32_t channel) {
274 if (value < -8192 || value > 8191) {
275 ESP_LOGW(TAG, "Cannot send: pitch bend %" PRId32 " out of range", value);
276 return;
277 }
278 const uint16_t unsigned_value = static_cast<uint16_t>(value + 8192);
279 this->send_channel_(STATUS_PITCH_BEND, channel, unsigned_value & 0x7F, unsigned_value >> 7, 3);
280}
281
282void BLEMidi::send_sysex(const uint8_t *payload, size_t length) {
283 uint8_t packet[MAX_TX_MIDI_BYTES + 2];
284 const size_t framed = frame_sysex(payload, length, packet + 2, MAX_TX_MIDI_BYTES);
285 if (framed == 0) {
286 ESP_LOGW(TAG, "Cannot send: SysEx of %u bytes is empty or exceeds the %u byte limit", static_cast<unsigned>(length),
287 static_cast<unsigned>(MAX_TX_MIDI_BYTES));
288 return;
289 }
290 this->write_packet_(packet, framed);
291}
292
293void BLEMidi::send_raw(const uint8_t *bytes, size_t length) {
294 // The packet carries one timestamp, in front of the first byte, so the payload has to be a single complete
295 // message with its status byte first; a SysEx goes through send_sysex
296 bool one_message = length > 0 && (bytes[0] & 0x80) != 0 && bytes[0] != STATUS_SYSEX_START &&
297 bytes[0] != STATUS_SYSEX_END && length == 1u + MidiParser::expected_data_bytes(bytes[0]);
298 for (size_t i = 1; one_message && i < length; i++) {
299 one_message = (bytes[i] & 0x80) == 0;
300 }
301 if (!one_message) {
302 ESP_LOGW(TAG, "Cannot send: raw payload must be one message, a status byte followed by data bytes");
303 return;
304 }
305 this->write_midi_(bytes, length);
306}
307
308} // namespace esphome::ble_midi
309
310#endif // USE_ESP32
uint8_t status
Definition bl0942.h:8
void status_clear_warning()
Definition component.h:309
void send_control_change(int32_t control_number, int32_t value, int32_t channel)
Definition ble_midi.cpp:265
void send_program_change(int32_t program, int32_t channel)
Definition ble_midi.cpp:269
LazyCallbackManager< void(uint8_t, uint8_t, uint8_t)> note_on_callback_
Definition ble_midi.h:117
LazyCallbackManager< void(uint8_t, uint8_t, uint8_t)> control_change_callback_
Definition ble_midi.h:119
LazyCallbackManager< void(uint8_t, uint8_t, uint8_t)> note_off_callback_
Definition ble_midi.h:118
LazyCallbackManager< void()> disconnect_callback_
Definition ble_midi.h:116
void send_note_off(int32_t note, int32_t velocity, int32_t channel)
Definition ble_midi.cpp:261
void send_channel_(uint8_t status, int32_t channel, int32_t data1, int32_t data2, size_t length)
Channel-voice message: the status byte takes the channel; out-of-range values are refused.
Definition ble_midi.cpp:243
LazyCallbackManager< void(int16_t, uint8_t)> pitch_bend_callback_
Definition ble_midi.h:121
void send_raw(const uint8_t *bytes, size_t length)
Send raw MIDI bytes (status byte followed by its data bytes).
Definition ble_midi.cpp:293
void dump_config() override
Definition ble_midi.cpp:29
bool write_packet_(uint8_t *packet, size_t midi_length)
Write a packet whose MIDI bytes already sit at packet + 2; the header and timestamp are filled in.
Definition ble_midi.cpp:204
void send_note_on(int32_t note, int32_t velocity, int32_t channel)
Definition ble_midi.cpp:257
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
Definition ble_midi.cpp:38
void send_sysex(const uint8_t *payload, size_t length)
Send a System Exclusive message.
Definition ble_midi.cpp:282
void send_pitch_bend(int32_t value, int32_t channel)
Pitch bend value is -8192 to 8191, centered on zero.
Definition ble_midi.cpp:273
void fail_session_()
Set a warning and drop the link so that ble_client reconnects and the setup runs again.
Definition ble_midi.cpp:151
LazyCallbackManager< void(ByteSpan)> message_callback_
Definition ble_midi.h:123
LazyCallbackManager< void(ByteSpan)> sysex_callback_
Definition ble_midi.h:122
LazyCallbackManager< void(uint8_t, uint8_t)> program_change_callback_
Definition ble_midi.h:120
bool is_ready() const
True once the MIDI characteristic has been discovered and notifications are enabled.
Definition ble_midi.h:50
static void dispatch_message(void *ctx, const MidiMessage &message)
Definition ble_midi.h:101
void handle_message_(const MidiMessage &message)
Definition ble_midi.cpp:157
bool write_midi_(const uint8_t *midi_bytes, size_t length)
Wrap MIDI bytes in a BLE-MIDI packet and write them to the MIDI characteristic.
Definition ble_midi.cpp:232
LazyCallbackManager< void()> connect_callback_
Definition ble_midi.h:115
uint16_t sysex_capacity() const
Definition midi_parser.h:80
void feed(const uint8_t *data, size_t length, MidiMessageHandler handler, void *ctx)
Feed one BLE notification payload.
static uint8_t expected_data_bytes(uint8_t status)
Number of data bytes that follow a status byte other than SysEx.
void reset()
Drop all parser state.
BLEDescriptor * get_descriptor(espbt::ESPBTUUID uuid)
esp_err_t register_for_notify(uint16_t char_handle)
Register for notifications, holding the service release until the registration completes.
BLECharacteristic * get_characteristic(espbt::ESPBTUUID service, espbt::ESPBTUUID chr)
const LogString * message
Definition component.cpp:35
std::span< const uint8_t > ByteSpan
The bytes of a received message, valid for the duration of the automation.
Definition ble_midi.h:24
ESPHOME_LOG_TAG(TAG, "ble_midi")
size_t frame_sysex(const uint8_t *payload, size_t length, uint8_t *out, size_t out_size)
Frame a SysEx payload for one BLE-MIDI packet: 0xF0 and 0xF7 are added when the payload lacks them,...
uint32_t value
Definition hal.cpp:41
constexpr size_t format_hex_size(size_t byte_count)
Calculate buffer size needed for format_hex_to: "XXXXXXXX...\0" = bytes * 2 + 1.
Definition helpers.h:1661
char * format_hex_to(char *buffer, size_t buffer_size, const uint8_t *data, size_t length)
Format byte array as lowercase hex to buffer (base implementation).
Definition helpers.cpp:428
static void uint32_t
A decoded MIDI message.
Definition midi_parser.h:34
uint16_t length
Definition tt21100.cpp:0