16static constexpr const char *SERVICE_UUID =
"03B80E5A-EDE8-4B33-A751-6CE34EC4C700";
17static constexpr const char *CHARACTERISTIC_UUID =
"7772E5DB-3868-4112-A1A9-F2669D106BF3";
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;
27static constexpr size_t LOG_MAX_BYTES = 32;
33 " Maximum SysEx size: %u\n"
34 " Pair on connect: %s",
40 case ESP_GATTC_OPEN_EVT: {
41 if (param->open.status != ESP_GATT_OK)
49 ESP_LOGW(TAG,
"Pairing failed, error=%d", err);
54 case ESP_GATTC_CFG_MTU_EVT: {
55 if (param->cfg_mtu.status == ESP_GATT_OK)
56 this->
mtu_ = param->cfg_mtu.mtu;
59 case ESP_GATTC_DISCONNECT_EVT:
60 case ESP_GATTC_CLOSE_EVT: {
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);
81 espbt::ESPBTUUID::from_raw(CHARACTERISTIC_UUID));
83 if (characteristic ==
nullptr) {
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"));
97 ESP_LOGW(TAG,
"register_for_notify failed, error=%d", err);
102 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
103 if (param->reg_for_notify.handle != this->characteristic_handle_)
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);
112 case ESP_GATTC_WRITE_DESCR_EVT: {
113 if (this->
cccd_handle_ == 0 || param->write.handle != this->cccd_handle_ || this->notify_registered_)
115 if (param->write.status != ESP_GATT_OK) {
116 ESP_LOGW(TAG,
"Device refused to enable notifications, status=%d", param->write.status);
121 this->
node_state = espbt::ClientState::ESTABLISHED;
122 ESP_LOGI(TAG,
"MIDI notifications enabled");
128 case ESP_GATTC_WRITE_CHAR_EVT: {
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);
135 case ESP_GATTC_NOTIFY_EVT: {
136 if (param->notify.handle != this->characteristic_handle_ || param->notify.value_len == 0)
141 ESP_LOGV(TAG,
"Received %u bytes: %s", param->notify.value_len,
142 format_hex_to(hex, param->notify.value, param->notify.value_len));
160 LOG_STR_ARG(MessageTypeNames::get_log_str(
static_cast<uint8_t
>(
message.type), MessageTypeNames::LAST_INDEX)));
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());
168 ESP_LOGW(TAG,
"MIDI message 0x%02X dropped: cut short by another status byte",
message.status());
172 ESP_LOGW(TAG,
"Undecodable MIDI byte 0x%02X",
message.status());
206 ESP_LOGW(TAG,
"Cannot send: not connected");
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));
217 packet[0] = PACKET_HEADER;
218 packet[1] = PACKET_TIMESTAMP;
219 esp_err_t err = esp_ble_gattc_write_char(
222 ESP_GATT_AUTH_REQ_NONE);
224 ESP_LOGW(TAG,
"Write failed, error=%d", err);
228 ESP_LOGV(TAG,
"Sent %u bytes: %s",
static_cast<unsigned>(packet_length),
format_hex_to(hex, packet, packet_length));
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));
238 uint8_t packet[MAX_TX_MIDI_BYTES + 2];
239 std::memcpy(packet + 2, midi_bytes,
length);
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,
252 const uint8_t bytes[3] = {
static_cast<uint8_t
>(
status | channel),
static_cast<uint8_t
>(data1),
253 static_cast<uint8_t
>(data2)};
258 this->
send_channel_(STATUS_NOTE_ON, channel, note, velocity, 3);
262 this->
send_channel_(STATUS_NOTE_OFF, channel, note, velocity, 3);
270 this->
send_channel_(STATUS_PROGRAM_CHANGE, channel, program, 0, 2);
275 ESP_LOGW(TAG,
"Cannot send: pitch bend %" PRId32
" out of range",
value);
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);
283 uint8_t packet[MAX_TX_MIDI_BYTES + 2];
284 const size_t framed =
frame_sysex(payload,
length, packet + 2, MAX_TX_MIDI_BYTES);
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));
296 bool one_message =
length > 0 && (bytes[0] & 0x80) != 0 && bytes[0] != STATUS_SYSEX_START &&
298 for (
size_t i = 1; one_message && i <
length; i++) {
299 one_message = (bytes[i] & 0x80) == 0;
302 ESP_LOGW(TAG,
"Cannot send: raw payload must be one message, a status byte followed by data bytes");
void status_set_warning()
void status_clear_warning()
espbt::ClientState node_state
void send_control_change(int32_t control_number, int32_t value, int32_t channel)
bool write_without_response_
void send_program_change(int32_t program, int32_t channel)
LazyCallbackManager< void(uint8_t, uint8_t, uint8_t)> note_on_callback_
LazyCallbackManager< void(uint8_t, uint8_t, uint8_t)> control_change_callback_
LazyCallbackManager< void(uint8_t, uint8_t, uint8_t)> note_off_callback_
LazyCallbackManager< void()> disconnect_callback_
void send_note_off(int32_t note, int32_t velocity, int32_t channel)
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.
LazyCallbackManager< void(int16_t, uint8_t)> pitch_bend_callback_
void send_raw(const uint8_t *bytes, size_t length)
Send raw MIDI bytes (status byte followed by its data bytes).
void dump_config() override
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.
void send_note_on(int32_t note, int32_t velocity, int32_t channel)
void gattc_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param) override
void send_sysex(const uint8_t *payload, size_t length)
Send a System Exclusive message.
void send_pitch_bend(int32_t value, int32_t channel)
Pitch bend value is -8192 to 8191, centered on zero.
void fail_session_()
Set a warning and drop the link so that ble_client reconnects and the setup runs again.
LazyCallbackManager< void(ByteSpan)> message_callback_
LazyCallbackManager< void(ByteSpan)> sysex_callback_
LazyCallbackManager< void(uint8_t, uint8_t)> program_change_callback_
bool is_ready() const
True once the MIDI characteristic has been discovered and notifications are enabled.
static void dispatch_message(void *ctx, const MidiMessage &message)
uint16_t characteristic_handle_
void handle_message_(const MidiMessage &message)
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.
LazyCallbackManager< void()> connect_callback_
uint16_t sysex_capacity() const
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)
void disconnect() override
const LogString * message
std::span< const uint8_t > ByteSpan
The bytes of a received message, valid for the duration of the automation.
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,...
constexpr size_t format_hex_size(size_t byte_count)
Calculate buffer size needed for format_hex_to: "XXXXXXXX...\0" = bytes * 2 + 1.
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).
int16_t pitch_bend() const