Debian Codegraph @

architecture/esp32/gramo-bt-midi/components/blemidi/blemidi.c

raw
1 /*
2 BLE MIDI driver based on a heavy-lifted version of https://github.com/midibox/esp32-idf-blemidi by Thorsten Klose ([email protected]). The driver can act both as a server and as a client.
3 */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <string.h>
8 #include <sys/time.h>
9
10 #include "esp_system.h"
11 #include "esp_log.h"
12 #include "nvs_flash.h"
13 #include "esp_bt.h"
14
15 #include "blemidi.h"
16
17 #include "esp_gap_ble_api.h"
18 #include "esp_gatts_api.h"
19 #include "esp_gattc_api.h"
20 #include "esp_bt_main.h"
21 #include "esp_gatt_common_api.h"
22
23 ////////////////////////////////////////////////////////////////////////////////
24 // GLOBAL ELEMENTS SECTION
25 ////////////////////////////////////////////////////////////////////////////////
26
27 #define BLEMIDI_NUM_PORTS 1
28 #define BLEMIDI_OUTBUFFER_FLUSH_MS 15
29
30 #define BLEMIDI_TAG "BLEMIDI"
31 #define PROFILE_NUM 1
32 #define PROFILE_APP_IDX 0
33 #define PROFILE_A_APP_ID 0
34 #define INVALID_HANDLE 0
35 #define REMOTE_SERVICE_UUID 0x00, 0xC7, 0xC4, 0x4E, 0xE3, 0x6C, 0x51, 0xA7, 0x33, 0x4B, 0xE8, 0xED, 0x5A, 0x0E, 0xB8, 0x03
36 #define REMOTE_CHAR_UUID 0xF3, 0x6B, 0x10, 0x9D, 0x66, 0xF2, 0xA9, 0xA1, 0x12, 0x41, 0x68, 0x38, 0xDB, 0xE5, 0x72, 0x77
37 #define ESP_APP_ID 0x55
38 #define SVC_INST_ID 0
39
40 /* The max length of characteristic value. When the GATT client performs a write or prepare write operation,
41 * the data length must be less than GATTS_MIDI_CHAR_VAL_LEN_MAX.
42 */
43 #define GATTS_MIDI_CHAR_VAL_LEN_MAX 100
44 #define PREPARE_BUF_MAX_SIZE 2048
45 #define CHAR_DECLARATION_SIZE (sizeof(uint8_t))
46
47 #define ADV_CONFIG_FLAG (1 << 0)
48 #define SCAN_RSP_CONFIG_FLAG (1 << 1)
49
50 const char* current_device_name = "Gramophone";
51 const char* remote_device_name = "BBC micro:bit [zegut]";
52 static bool connect = false;
53 static bool get_server = false;
54 static esp_gattc_char_elem_t *char_elem_result = NULL;
55 static esp_gattc_descr_elem_t *descr_elem_result = NULL;
56
57 static uint8_t adv_config_done = 0;
58
59 /* Attributes State Machine */
60 enum
61 {
62 IDX_SVC,
63 IDX_CHAR_A,
64 IDX_CHAR_VAL_A,
65 IDX_CHAR_CFG_A,
66 HRS_IDX_NB,
67 };
68 uint16_t midi_handle_table[HRS_IDX_NB];
69
70 static uint8_t midi_service_uuid[16] = {
71 REMOTE_SERVICE_UUID
72 };
73
74 static const uint8_t midi_characteristics_uuid[16] = {
75 REMOTE_CHAR_UUID
76 };
77
78 /* The length of adv data must be less than 31 bytes */
79 static esp_ble_adv_data_t adv_data = {
80 .set_scan_rsp = false,
81 .include_name = false, // exclude name to ensure that we don't exceed 31 bytes...
82 .include_txpower = true,
83 .min_interval = 0x0006, //slave connection min interval, Time = min_interval * 1.25 msec
84 .max_interval = 0x0010, //slave connection max interval, Time = max_interval * 1.25 msec
85 .appearance = 0x00,
86 .manufacturer_len = 0, //TEST_MANUFACTURER_DATA_LEN,
87 .p_manufacturer_data = NULL, //test_manufacturer,
88 .service_data_len = 0,
89 .p_service_data = NULL,
90 .service_uuid_len = sizeof(midi_service_uuid),
91 .p_service_uuid = midi_service_uuid,
92 .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
93 };
94
95 static esp_ble_adv_params_t adv_params = {
96 .adv_int_min = 0x20,
97 .adv_int_max = 0x40,
98 .adv_type = ADV_TYPE_IND,
99 .own_addr_type = BLE_ADDR_TYPE_PUBLIC,
100 .channel_map = ADV_CHNL_ALL,
101 .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
102 };
103
104 ////////////////////////////////////////////////////////////////////////////////
105 // GATTC GLOBAL ELEMENTS SECTION
106 ////////////////////////////////////////////////////////////////////////////////
107
108 struct gattc_profile_inst {
109 esp_gattc_cb_t gattc_cb;
110 uint16_t gattc_if;
111 uint16_t app_id;
112 uint16_t conn_id;
113 uint16_t service_start_handle;
114 uint16_t service_end_handle;
115 uint16_t char_handle;
116 esp_bd_addr_t remote_bda;
117 };
118
119 static void esp_gattc_cb(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
120 static void gattc_profile_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param);
121
122 static struct gattc_profile_inst gl_profile_tab[PROFILE_NUM] = {
123 [PROFILE_A_APP_ID] = {
124 .gattc_cb = gattc_profile_event_handler,
125 .gattc_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
126 },
127 };
128
129 ////////////////////////////////////////////////////////////////////////////////
130 // GATTS GLOBAL ELEMENTS SECTION
131 ////////////////////////////////////////////////////////////////////////////////
132
133 struct gatts_profile_inst {
134 esp_gatts_cb_t gatts_cb;
135 uint16_t gatts_if;
136 uint16_t app_id;
137 uint16_t conn_id;
138 uint16_t service_handle;
139 esp_gatt_srvc_id_t service_id;
140 uint16_t char_handle;
141 esp_bt_uuid_t char_uuid;
142 esp_gatt_perm_t perm;
143 esp_gatt_char_prop_t property;
144 uint16_t descr_handle;
145 esp_bt_uuid_t descr_uuid;
146 };
147
148 static void gatts_profile_event_handler(esp_gatts_cb_event_t event,
149 esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
150
151 /* One gatt-based profile one app_id and one gatts_if, this array will store the gatts_if returned by ESP_GATTS_REG_EVT */
152 static struct gatts_profile_inst midi_profile_tab[PROFILE_NUM] = {
153 [PROFILE_APP_IDX] = {
154 .gatts_cb = gatts_profile_event_handler,
155 .gatts_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
156 },
157 };
158
159 ////////////////////////////////////////////////////////////////////////////////
160 // MIDI SECTION
161 ////////////////////////////////////////////////////////////////////////////////
162
163 // the MTU can be changed by the client during runtime
164 static size_t blemidi_mtu = GATTS_MIDI_CHAR_VAL_LEN_MAX - 3;
165
166 // This timestamp should be increased each mS from the application via blemidi_tick_ms() call:
167 static uint16_t blemidi_timestamp = 0;
168
169 // we buffer outgoing MIDI messages for 10 mS - this should avoid that multiple BLE packets have to be queued for small messages
170 static uint8_t blemidi_outbuffer[BLEMIDI_NUM_PORTS][GATTS_MIDI_CHAR_VAL_LEN_MAX];
171 static uint16_t blemidi_outbuffer_len[BLEMIDI_NUM_PORTS];
172 static uint16_t blemidi_outbuffer_timestamp_last_flush = 0;
173
174 // to handled continued SysEx
175 static size_t blemidi_continued_sysex_pos[BLEMIDI_NUM_PORTS];
176
177 void (*blemidi_callback_midi_message_received)(uint8_t blemidi_port, uint16_t timestamp, uint8_t midi_status, uint8_t *remaining_message, size_t len, size_t continued_sysex_pos, void* arg);
178
179 void* callback_arg;
180
181 // ------ Time stamp handling --------
182 void blemidi_tick(void)
183 {
184 struct timeval tv;
185 gettimeofday(&tv, NULL);
186 blemidi_timestamp = (tv.tv_sec * 1000 + (tv.tv_usec / 1000)); // 1 mS per increment
187
188 if( (blemidi_outbuffer_timestamp_last_flush > blemidi_timestamp) ||
189 (blemidi_timestamp > (blemidi_outbuffer_timestamp_last_flush + BLEMIDI_OUTBUFFER_FLUSH_MS)) ) {
190 uint8_t blemidi_port;
191 for(blemidi_port=0; blemidi_port < BLEMIDI_NUM_PORTS; ++blemidi_port) {
192 blemidi_outbuffer_flush(blemidi_port);
193 }
194
195 blemidi_outbuffer_timestamp_last_flush = blemidi_timestamp;
196 }
197 }
198
199 uint8_t blemidi_timestamp_high(void)
200 {
201 return (0x80 | ((blemidi_timestamp >> 7) & 0x3f));
202 }
203
204 uint8_t blemidi_timestamp_low(void)
205 {
206 return (0x80 | (blemidi_timestamp & 0x7f));
207 }
208
209 // ----------------------------------
210
211 int32_t blemidi_outbuffer_flush(uint8_t blemidi_port)
212 {
213 if( blemidi_port >= BLEMIDI_NUM_PORTS )
214 return -1; // invalid port
215
216 if( blemidi_outbuffer_len[blemidi_port] > 0 ) {
217 esp_ble_gatts_send_indicate(midi_profile_tab[PROFILE_APP_IDX].gatts_if, midi_profile_tab[PROFILE_APP_IDX].conn_id, midi_handle_table[IDX_CHAR_VAL_A], blemidi_outbuffer_len[blemidi_port], blemidi_outbuffer[blemidi_port], false);
218 blemidi_outbuffer_len[blemidi_port] = 0;
219 }
220 return 0; // no error
221 }
222
223 // Push a new MIDI message to the output buffer
224 static int32_t blemidi_outbuffer_push(uint8_t blemidi_port, uint8_t *stream, size_t len)
225 {
226 const size_t max_header_size = 2;
227
228 if( blemidi_port >= BLEMIDI_NUM_PORTS )
229 return -1; // invalid port
230
231 // if len >= MTU, it makes sense to send out immediately
232 if( len >= (blemidi_mtu-max_header_size) ) {
233 // this is very unlikely, since applemidi_send_message() maintains the size
234 // but just in case of future extensions, we prepare dynamic memory allocation for "big packets"
235 blemidi_outbuffer_flush(blemidi_port);
236 {
237 size_t packet_len = max_header_size + len;
238 uint8_t *packet = malloc(packet_len);
239 if( packet == NULL ) {
240 return -1; // couldn't create temporary packet
241 } else {
242 // new packet: with timestampHigh and timestampLow, or in case of continued SysEx packet: only timestampHigh
243 packet[0] = blemidi_timestamp_high();
244 if( stream[0] >= 0x80 ) {
245 packet[1] = blemidi_timestamp_low();
246 memcpy((uint8_t *)packet + 2, stream, len);
247 } else {
248 packet_len -= 1;
249 memcpy((uint8_t *)packet + 1, stream, len);
250 }
251 esp_ble_gatts_send_indicate(midi_profile_tab[PROFILE_APP_IDX].gatts_if, midi_profile_tab[PROFILE_APP_IDX].conn_id, midi_handle_table[IDX_CHAR_VAL_A], packet_len, packet, false);
252 free(packet);
253 }
254 }
255 } else {
256 // flush buffer before adding new message
257 if( (blemidi_outbuffer_len[blemidi_port] + len) >= blemidi_mtu )
258 blemidi_outbuffer_flush(blemidi_port);
259
260 // adding new message
261 if( blemidi_outbuffer_len[blemidi_port] == 0 ) {
262 // new packet: with timestampHigh and timestampLow, or in case of continued SysEx packet: only timestampHigh
263 blemidi_outbuffer[blemidi_port][blemidi_outbuffer_len[blemidi_port]++] = blemidi_timestamp_high();
264 if( stream[0] >= 0x80 ) {
265 blemidi_outbuffer[blemidi_port][blemidi_outbuffer_len[blemidi_port]++] = blemidi_timestamp_low();
266 }
267 } else {
268 blemidi_outbuffer[blemidi_port][blemidi_outbuffer_len[blemidi_port]++] = blemidi_timestamp_low();
269 }
270
271 memcpy(&blemidi_outbuffer[blemidi_port][blemidi_outbuffer_len[blemidi_port]],
272 stream, len);
273 blemidi_outbuffer_len[blemidi_port] += len;
274 }
275
276 return 0; // no error
277 }
278
279 int32_t blemidi_send_message(uint8_t blemidi_port, uint8_t *stream, size_t len)
280 {
281 const size_t max_header_size = 2;
282
283 if( blemidi_port >= BLEMIDI_NUM_PORTS )
284 return -1; // invalid port
285
286 // we've to consider blemidi_mtu
287 // if more bytes need to be sent, split over multiple packets
288 // this will cost some extra stack space :-/ therefore handled separatly?
289
290 if( len < (blemidi_mtu-max_header_size) ) {
291 // just add to output buffer
292 blemidi_outbuffer_push(blemidi_port, stream, len);
293 } else {
294 // sending packets
295 size_t max_size = blemidi_mtu - max_header_size; // -3 since blemidi_outbuffer_push() will add the timestamps
296 int pos;
297 for(pos=0; pos<len; pos += max_size) {
298 size_t packet_len = len-pos;
299 if( packet_len >= max_size ) {
300 packet_len = max_size;
301 }
302 blemidi_outbuffer_push(blemidi_port, &stream[pos], packet_len);
303 }
304 }
305
306 return 0; // no error
307 }
308
309 static int32_t blemidi_receive_packet(uint8_t blemidi_port, uint8_t *stream, size_t len, void *_callback_midi_message_received)
310 {
311 void (*callback_midi_message_received)(uint8_t blemidi_port, uint16_t timestamp, uint8_t midi_status, uint8_t *remaining_message, size_t len, size_t continued_sysex_pos, void* arg) = _callback_midi_message_received;
312
313 if( blemidi_port >= BLEMIDI_NUM_PORTS )
314 return -1; // invalid port
315
316 ESP_LOGI(BLEMIDI_TAG, "receive_packet blemidi_port=%d, len=%d, stream:", blemidi_port, len);
317 esp_log_buffer_hex(BLEMIDI_TAG, stream, len);
318
319 // detect continued SysEx
320 uint8_t continued_sysex = 0;
321 if( len > 2 && (stream[0] & 0x80) && !(stream[1] & 0x80)) {
322 continued_sysex = 1;
323 } else {
324 blemidi_continued_sysex_pos[blemidi_port] = 0;
325 }
326
327
328 if( len < 3 ) {
329 ESP_LOGE(BLEMIDI_TAG, "stream length should be >=3");
330 return -1;
331 } else if( !(stream[0] & 0x80) ) {
332 ESP_LOGE(BLEMIDI_TAG, "missing timestampHigh");
333 return -2;
334 } else {
335 size_t pos = 0;
336
337 // getting timestamp
338 uint16_t timestamp = (stream[pos++] & 0x3f) << 7;
339
340 // parsing stream
341 {
342 //! Number if expected bytes for a common MIDI event - 1
343 const uint8_t midi_expected_bytes_common[8] = {
344 2, // Note On
345 2, // Note Off
346 2, // Poly Preasure
347 2, // Controller
348 1, // Program Change
349 1, // Channel Preasure
350 2, // Pitch Bender
351 0, // System Message - must be zero, so that mios32_midi_expected_bytes_system[] will be used
352 };
353
354 //! Number if expected bytes for a system MIDI event - 1
355 const uint8_t midi_expected_bytes_system[16] = {
356 1, // SysEx Begin (endless until SysEx End F7)
357 1, // MTC Data frame
358 2, // Song Position
359 1, // Song Select
360 0, // Reserved
361 0, // Reserved
362 0, // Request Tuning Calibration
363 0, // SysEx End
364
365 // Note: just only for documentation, Realtime Messages don't change the running status
366 0, // MIDI Clock
367 0, // MIDI Tick
368 0, // MIDI Start
369 0, // MIDI Continue
370 0, // MIDI Stop
371 0, // Reserved
372 0, // Active Sense
373 0, // Reset
374 };
375
376 uint8_t midi_status = continued_sysex ? 0xf0 : 0x00;
377
378 while( pos < len ) {
379 if( !(stream[pos] & 0x80) ) {
380 if( !continued_sysex ) {
381 ESP_LOGE(BLEMIDI_TAG, "missing timestampLow in parsed message");
382 return -3;
383 }
384 } else {
385 timestamp &= ~0x7f;
386 timestamp |= stream[pos++] & 0x7f;
387 continued_sysex = 0;
388 blemidi_continued_sysex_pos[blemidi_port] = 0;
389 }
390
391 if( stream[pos] & 0x80 ) {
392 midi_status = stream[pos++];
393 }
394
395 if( midi_status == 0xf0 ) {
396 size_t num_bytes;
397 for(num_bytes=0; stream[pos+num_bytes] < 0x80; ++num_bytes) {
398 if( (pos+num_bytes) >= len ) {
399 break;
400 }
401 }
402 if( _callback_midi_message_received ) {
403 callback_midi_message_received(blemidi_port, timestamp, midi_status, &stream[pos], num_bytes, blemidi_continued_sysex_pos[blemidi_port], callback_arg);
404 }
405 pos += num_bytes;
406 blemidi_continued_sysex_pos[blemidi_port] += num_bytes; // we expect another packet with the remaining SysEx stream
407 } else {
408 uint8_t num_bytes = midi_expected_bytes_common[(midi_status >> 4) & 0x7];
409 if( num_bytes == 0 ) { // System Message
410 num_bytes = midi_expected_bytes_system[midi_status & 0xf];
411 }
412
413 if( (pos+num_bytes) > len ) {
414 ESP_LOGE(BLEMIDI_TAG, "missing %d bytes in parsed message", num_bytes);
415 return -5;
416 } else {
417 if( _callback_midi_message_received ) {
418 callback_midi_message_received(blemidi_port, timestamp, midi_status, &stream[pos], num_bytes, 0, callback_arg);
419 }
420 pos += num_bytes;
421 }
422 }
423 }
424 }
425 }
426 return 0; // no error
427 }
428
429 ////////////////////////////////////////////////////////////////////////////////
430 // GAP SECTION
431 ////////////////////////////////////////////////////////////////////////////////
432
433 static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
434 {
435 uint8_t *adv_name = NULL;
436 uint8_t adv_name_len = 0;
437 switch (event) {
438 case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: {
439 //the unit of the duration is second
440 uint32_t duration = 30;
441 esp_ble_gap_start_scanning(duration);
442 break;
443 }
444 case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT:
445 //scan start complete event to indicate scan start successfully or failed
446 if (param->scan_start_cmpl.status != ESP_BT_STATUS_SUCCESS) {
447 ESP_LOGE(BLEMIDI_TAG, "scan start failed, error status = %x", param->scan_start_cmpl.status);
448 break;
449 }
450 ESP_LOGI(BLEMIDI_TAG, "scan start success");
451
452 break;
453 case ESP_GAP_BLE_SCAN_RESULT_EVT: {
454 esp_ble_gap_cb_param_t *scan_result = (esp_ble_gap_cb_param_t *)param;
455 switch (scan_result->scan_rst.search_evt) {
456 case ESP_GAP_SEARCH_INQ_RES_EVT:
457 esp_log_buffer_hex(BLEMIDI_TAG, scan_result->scan_rst.bda, 6);
458 ESP_LOGI(BLEMIDI_TAG, "searched Adv Data Len %d, Scan Response Len %d", scan_result->scan_rst.adv_data_len, scan_result->scan_rst.scan_rsp_len);
459 adv_name = esp_ble_resolve_adv_data(scan_result->scan_rst.ble_adv,
460 ESP_BLE_AD_TYPE_NAME_CMPL, &adv_name_len);
461 ESP_LOGI(BLEMIDI_TAG, "searched Device Name Len %d", adv_name_len);
462 esp_log_buffer_char(BLEMIDI_TAG, adv_name, adv_name_len);
463 ESP_LOGI(BLEMIDI_TAG, "\n");
464
465 if (adv_name != NULL) {
466 if (strlen(remote_device_name) == adv_name_len && strncmp((char *)adv_name, remote_device_name, adv_name_len) == 0) {
467 ESP_LOGI(BLEMIDI_TAG, "searched device %s\n", remote_device_name);
468 if (connect == false) {
469 connect = true;
470 ESP_LOGI(BLEMIDI_TAG, "connect to the remote device.");
471 esp_ble_gap_stop_scanning();
472 esp_ble_gattc_open(gl_profile_tab[PROFILE_A_APP_ID].gattc_if, scan_result->scan_rst.bda, scan_result->scan_rst.ble_addr_type, true);
473 }
474 }
475 }
476 break;
477 case ESP_GAP_SEARCH_INQ_CMPL_EVT:
478 break;
479 default:
480 break;
481 }
482 break;
483 }
484 case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT:
485 if (param->scan_stop_cmpl.status != ESP_BT_STATUS_SUCCESS){
486 ESP_LOGE(BLEMIDI_TAG, "scan stop failed, error status = %x", param->scan_stop_cmpl.status);
487 break;
488 }
489 ESP_LOGI(BLEMIDI_TAG, "stop scan successfully");
490 break;
491 case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT:
492 adv_config_done &= (~ADV_CONFIG_FLAG);
493 if (adv_config_done == 0){
494 esp_ble_gap_start_advertising(&adv_params);
495 }
496 break;
497 case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT:
498 adv_config_done &= (~SCAN_RSP_CONFIG_FLAG);
499 if (adv_config_done == 0){
500 esp_ble_gap_start_advertising(&adv_params);
501 }
502 break;
503 case ESP_GAP_BLE_ADV_START_COMPLETE_EVT:
504 /* advertising start complete event to indicate advertising start successfully or failed */
505 if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) {
506 ESP_LOGE(BLEMIDI_TAG, "advertising start failed");
507 }else{
508 ESP_LOGI(BLEMIDI_TAG, "advertising start successfully");
509 }
510 break;
511 case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT:
512 if (param->adv_stop_cmpl.status != ESP_BT_STATUS_SUCCESS) {
513 ESP_LOGE(BLEMIDI_TAG, "Advertising stop failed");
514 }
515 else {
516 ESP_LOGI(BLEMIDI_TAG, "Stop adv successfully\n");
517 }
518 break;
519 case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT:
520 ESP_LOGI(BLEMIDI_TAG, "update connection params status = %d, min_int = %d, max_int = %d,conn_int = %d,latency = %d, timeout = %d",
521 param->update_conn_params.status,
522 param->update_conn_params.min_int,
523 param->update_conn_params.max_int,
524 param->update_conn_params.conn_int,
525 param->update_conn_params.latency,
526 param->update_conn_params.timeout);
527 break;
528 default:
529 break;
530 }
531 }
532
533 ////////////////////////////////////////////////////////////////////////////////
534 // GATT CLIENT SECTION
535 ////////////////////////////////////////////////////////////////////////////////
536
537 static esp_ble_scan_params_t ble_scan_params = {
538 .scan_type = BLE_SCAN_TYPE_ACTIVE,
539 .own_addr_type = BLE_ADDR_TYPE_PUBLIC,
540 .scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL,
541 .scan_interval = 0x50,
542 .scan_window = 0x30,
543 .scan_duplicate = BLE_SCAN_DUPLICATE_DISABLE
544 };
545
546 static esp_bt_uuid_t remote_filter_service_uuid = {
547 .len = ESP_UUID_LEN_128,
548 .uuid = {.uuid128 = {REMOTE_SERVICE_UUID},},
549 };
550
551 static esp_bt_uuid_t remote_filter_char_uuid = {
552 .len = ESP_UUID_LEN_128,
553 .uuid = {.uuid128 = {REMOTE_CHAR_UUID},},
554 };
555
556 static esp_bt_uuid_t notify_descr_uuid = {
557 .len = ESP_UUID_LEN_16,
558 .uuid = {.uuid16 = ESP_GATT_UUID_CHAR_CLIENT_CONFIG,},
559 };
560
561 static void gattc_profile_event_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
562 {
563 esp_ble_gattc_cb_param_t *p_data = (esp_ble_gattc_cb_param_t *)param;
564 switch (event) {
565 case ESP_GATTC_REG_EVT:
566 ESP_LOGI(BLEMIDI_TAG, "REG_EVT");
567 esp_err_t scan_ret = esp_ble_gap_set_scan_params(&ble_scan_params);
568 if (scan_ret){
569 ESP_LOGE(BLEMIDI_TAG, "set scan params error, error code = %x", scan_ret);
570 }
571 // esp_err_t ret = esp_ble_gap_config_adv_data(&adv_data);
572 // ret = esp_ble_gap_config_adv_data(&scan_rsp_data);
573 break;
574 case ESP_GATTC_CONNECT_EVT:{
575 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTC_CONNECT_EVT conn_id %d, if %d", p_data->connect.conn_id, gattc_if);
576 gl_profile_tab[PROFILE_A_APP_ID].conn_id = p_data->connect.conn_id;
577 memcpy(gl_profile_tab[PROFILE_A_APP_ID].remote_bda, p_data->connect.remote_bda, sizeof(esp_bd_addr_t));
578 ESP_LOGI(BLEMIDI_TAG, "REMOTE BDA:");
579 esp_log_buffer_hex(BLEMIDI_TAG, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, sizeof(esp_bd_addr_t));
580 esp_err_t mtu_ret = esp_ble_gattc_send_mtu_req (gattc_if, p_data->connect.conn_id);
581 if (mtu_ret){
582 ESP_LOGE(BLEMIDI_TAG, "config MTU error, error code = %x", mtu_ret);
583 }
584 break;
585 }
586 case ESP_GATTC_OPEN_EVT:
587 if (param->open.status != ESP_GATT_OK){
588 ESP_LOGE(BLEMIDI_TAG, "open failed, status %d", p_data->open.status);
589 break;
590 }
591 ESP_LOGI(BLEMIDI_TAG, "open success");
592 break;
593 case ESP_GATTC_DIS_SRVC_CMPL_EVT:
594 if (param->dis_srvc_cmpl.status != ESP_GATT_OK){
595 ESP_LOGE(BLEMIDI_TAG, "discover service failed, status %d", param->dis_srvc_cmpl.status);
596 break;
597 }
598 ESP_LOGI(BLEMIDI_TAG, "discover service complete conn_id %d", param->dis_srvc_cmpl.conn_id);
599 esp_ble_gattc_search_service(gattc_if, param->cfg_mtu.conn_id, &remote_filter_service_uuid);
600 break;
601 case ESP_GATTC_CFG_MTU_EVT:
602 if (param->cfg_mtu.status != ESP_GATT_OK){
603 ESP_LOGE(BLEMIDI_TAG,"config mtu failed, error status = %x", param->cfg_mtu.status);
604 }
605 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTC_CFG_MTU_EVT, Status %d, MTU %d, conn_id %d", param->cfg_mtu.status, param->cfg_mtu.mtu, param->cfg_mtu.conn_id);
606 break;
607 case ESP_GATTC_SEARCH_RES_EVT: {
608 ESP_LOGI(BLEMIDI_TAG, "SEARCH RES: conn_id = %x is primary service %d", p_data->search_res.conn_id, p_data->search_res.is_primary);
609 ESP_LOGI(BLEMIDI_TAG, "start handle %d end handle %d current handle value %d", p_data->search_res.start_handle, p_data->search_res.end_handle, p_data->search_res.srvc_id.inst_id);
610 if (p_data->search_res.srvc_id.uuid.len == ESP_UUID_LEN_128) {
611 ESP_LOGI(BLEMIDI_TAG, "service found with UUID128");
612 get_server = true;
613 gl_profile_tab[PROFILE_A_APP_ID].service_start_handle = p_data->search_res.start_handle;
614 gl_profile_tab[PROFILE_A_APP_ID].service_end_handle = p_data->search_res.end_handle;
615 }
616 break;
617 }
618 case ESP_GATTC_SEARCH_CMPL_EVT:
619 if (p_data->search_cmpl.status != ESP_GATT_OK){
620 ESP_LOGE(BLEMIDI_TAG, "search service failed, error status = %x", p_data->search_cmpl.status);
621 break;
622 }
623 if(p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_REMOTE_DEVICE) {
624 ESP_LOGI(BLEMIDI_TAG, "Get service information from remote device");
625 } else if (p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_NVS_FLASH) {
626 ESP_LOGI(BLEMIDI_TAG, "Get service information from flash");
627 } else {
628 ESP_LOGI(BLEMIDI_TAG, "unknown service source");
629 }
630 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTC_SEARCH_CMPL_EVT");
631 if (get_server){
632 uint16_t count = 0;
633 esp_gatt_status_t status = esp_ble_gattc_get_attr_count( gattc_if,
634 p_data->search_cmpl.conn_id,
635 ESP_GATT_DB_CHARACTERISTIC,
636 gl_profile_tab[PROFILE_A_APP_ID].service_start_handle,
637 gl_profile_tab[PROFILE_A_APP_ID].service_end_handle,
638 INVALID_HANDLE,
639 &count);
640 if (status != ESP_GATT_OK){
641 ESP_LOGE(BLEMIDI_TAG, "esp_ble_gattc_get_attr_count error");
642 }
643 if (count > 0){
644 char_elem_result = (esp_gattc_char_elem_t *)malloc(sizeof(esp_gattc_char_elem_t) * count);
645 if (!char_elem_result){
646 ESP_LOGE(BLEMIDI_TAG, "gattc no mem");
647 }else{
648 status = esp_ble_gattc_get_char_by_uuid( gattc_if,
649 p_data->search_cmpl.conn_id,
650 gl_profile_tab[PROFILE_A_APP_ID].service_start_handle,
651 gl_profile_tab[PROFILE_A_APP_ID].service_end_handle,
652 remote_filter_char_uuid,
653 char_elem_result,
654 &count);
655 if (status != ESP_GATT_OK){
656 ESP_LOGE(BLEMIDI_TAG, "esp_ble_gattc_get_char_by_uuid error");
657 }
658
659 /* Every service have only one char in our 'ESP_GATTS_DEMO' demo, so we used first 'char_elem_result' */
660 if (count > 0 && (char_elem_result[0].properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY)){
661 gl_profile_tab[PROFILE_A_APP_ID].char_handle = char_elem_result[0].char_handle;
662 esp_ble_gattc_register_for_notify (gattc_if, gl_profile_tab[PROFILE_A_APP_ID].remote_bda, char_elem_result[0].char_handle);
663 }
664 }
665 /* free char_elem_result */
666 free(char_elem_result);
667 }else{
668 ESP_LOGE(BLEMIDI_TAG, "no char found");
669 }
670 }
671 break;
672 case ESP_GATTC_REG_FOR_NOTIFY_EVT: {
673 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTC_REG_FOR_NOTIFY_EVT");
674 if (p_data->reg_for_notify.status != ESP_GATT_OK){
675 ESP_LOGE(BLEMIDI_TAG, "REG FOR NOTIFY failed: error status = %d", p_data->reg_for_notify.status);
676 }else{
677 uint16_t count = 0;
678 uint16_t notify_en = 1;
679 esp_gatt_status_t ret_status = esp_ble_gattc_get_attr_count( gattc_if,
680 gl_profile_tab[PROFILE_A_APP_ID].conn_id,
681 ESP_GATT_DB_DESCRIPTOR,
682 gl_profile_tab[PROFILE_A_APP_ID].service_start_handle,
683 gl_profile_tab[PROFILE_A_APP_ID].service_end_handle,
684 gl_profile_tab[PROFILE_A_APP_ID].char_handle,
685 &count);
686 if (ret_status != ESP_GATT_OK){
687 ESP_LOGE(BLEMIDI_TAG, "esp_ble_gattc_get_attr_count error");
688 }
689 if (count > 0){
690 descr_elem_result = malloc(sizeof(esp_gattc_descr_elem_t) * count);
691 if (!descr_elem_result){
692 ESP_LOGE(BLEMIDI_TAG, "malloc error, gattc no mem");
693 }else{
694 ret_status = esp_ble_gattc_get_descr_by_char_handle( gattc_if,
695 gl_profile_tab[PROFILE_A_APP_ID].conn_id,
696 p_data->reg_for_notify.handle,
697 notify_descr_uuid,
698 descr_elem_result,
699 &count);
700 if (ret_status != ESP_GATT_OK){
701 ESP_LOGE(BLEMIDI_TAG, "esp_ble_gattc_get_descr_by_char_handle error");
702 }
703 /* Every char has only one descriptor in our 'ESP_GATTS_DEMO' demo, so we used first 'descr_elem_result' */
704 if (count > 0 && descr_elem_result[0].uuid.len == ESP_UUID_LEN_16 && descr_elem_result[0].uuid.uuid.uuid16 == ESP_GATT_UUID_CHAR_CLIENT_CONFIG){
705 ret_status = esp_ble_gattc_write_char_descr( gattc_if,
706 gl_profile_tab[PROFILE_A_APP_ID].conn_id,
707 descr_elem_result[0].handle,
708 sizeof(notify_en),
709 (uint8_t *)&notify_en,
710 ESP_GATT_WRITE_TYPE_RSP,
711 ESP_GATT_AUTH_REQ_NONE);
712 }
713
714 if (ret_status != ESP_GATT_OK){
715 ESP_LOGE(BLEMIDI_TAG, "esp_ble_gattc_write_char_descr error");
716 }
717
718 /* free descr_elem_result */
719 free(descr_elem_result);
720 }
721 }
722 else{
723 ESP_LOGE(BLEMIDI_TAG, "decsr not found");
724 }
725
726 }
727 break;
728 }
729 case ESP_GATTC_NOTIFY_EVT:
730 if (p_data->notify.is_notify){
731 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTC_NOTIFY_EVT, receive notify value:");
732 }else{
733 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTC_NOTIFY_EVT, receive indicate value:");
734 }
735 esp_log_buffer_hex(BLEMIDI_TAG, p_data->notify.value, p_data->notify.value_len);
736 blemidi_receive_packet(0, p_data->notify.value, p_data->notify.value_len, blemidi_callback_midi_message_received);
737 break;
738 case ESP_GATTC_WRITE_DESCR_EVT:
739 if (p_data->write.status != ESP_GATT_OK){
740 ESP_LOGE(BLEMIDI_TAG, "write descr failed, error status = %x", p_data->write.status);
741 break;
742 }
743 ESP_LOGI(BLEMIDI_TAG, "write descr success ");
744 uint8_t write_char_data[35];
745 for (int i = 0; i < sizeof(write_char_data); ++i)
746 {
747 write_char_data[i] = i % 256;
748 }
749 esp_ble_gattc_write_char( gattc_if,
750 gl_profile_tab[PROFILE_A_APP_ID].conn_id,
751 gl_profile_tab[PROFILE_A_APP_ID].char_handle,
752 sizeof(write_char_data),
753 write_char_data,
754 ESP_GATT_WRITE_TYPE_RSP,
755 ESP_GATT_AUTH_REQ_NONE);
756 break;
757 case ESP_GATTC_SRVC_CHG_EVT: {
758 esp_bd_addr_t bda;
759 memcpy(bda, p_data->srvc_chg.remote_bda, sizeof(esp_bd_addr_t));
760 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTC_SRVC_CHG_EVT, bd_addr:");
761 esp_log_buffer_hex(BLEMIDI_TAG, bda, sizeof(esp_bd_addr_t));
762 break;
763 }
764 case ESP_GATTC_WRITE_CHAR_EVT:
765 if (p_data->write.status != ESP_GATT_OK){
766 ESP_LOGE(BLEMIDI_TAG, "write char failed, error status = %x", p_data->write.status);
767 break;
768 }
769 ESP_LOGI(BLEMIDI_TAG, "write char success ");
770 break;
771 case ESP_GATTC_DISCONNECT_EVT:
772 connect = false;
773 get_server = false;
774 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTC_DISCONNECT_EVT, reason = %d", p_data->disconnect.reason);
775 break;
776 default:
777 break;
778 }
779 }
780
781 static void esp_gattc_cb(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t *param)
782 {
783 /* If event is register event, store the gattc_if for each profile */
784 if (event == ESP_GATTC_REG_EVT) {
785 if (param->reg.status == ESP_GATT_OK) {
786 gl_profile_tab[param->reg.app_id].gattc_if = gattc_if;
787 } else {
788 ESP_LOGI(BLEMIDI_TAG, "reg app failed, app_id %04x, status %d",
789 param->reg.app_id,
790 param->reg.status);
791 return;
792 }
793 }
794
795 /* If the gattc_if equal to profile A, call profile A cb handler,
796 * so here call each profile's callback */
797 do {
798 int idx;
799 for (idx = 0; idx < PROFILE_NUM; idx++) {
800 if (gattc_if == ESP_GATT_IF_NONE || /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
801 gattc_if == gl_profile_tab[idx].gattc_if) {
802 if (gl_profile_tab[idx].gattc_cb) {
803 gl_profile_tab[idx].gattc_cb(event, gattc_if, param);
804 }
805 }
806 }
807 } while (0);
808 }
809
810 ////////////////////////////////////////////////////////////////////////////////
811 // GATT SERVER SECTION
812 ////////////////////////////////////////////////////////////////////////////////
813
814 typedef struct {
815 uint8_t *prepare_buf;
816 int prepare_len;
817 } prepare_type_env_t;
818
819 static prepare_type_env_t prepare_write_env;
820
821 // scan response data
822 static esp_ble_adv_data_t scan_rsp_data = {
823 .set_scan_rsp = true,
824 .include_name = true,
825 .include_txpower = true,
826 .min_interval = 0x0006,
827 .max_interval = 0x0010,
828 .appearance = 0x00,
829 .manufacturer_len = 0, //TEST_MANUFACTURER_DATA_LEN,
830 .p_manufacturer_data = NULL, //&test_manufacturer[0],
831 .service_data_len = 0,
832 .p_service_data = NULL,
833 .service_uuid_len = sizeof(midi_service_uuid),
834 .p_service_uuid = midi_service_uuid,
835 .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
836 };
837
838 /* Service */
839 static const uint16_t primary_service_uuid = ESP_GATT_UUID_PRI_SERVICE;
840 static const uint16_t character_declaration_uuid = ESP_GATT_UUID_CHAR_DECLARE;
841 static const uint16_t character_client_config_uuid = ESP_GATT_UUID_CHAR_CLIENT_CONFIG;
842 // RM: commented below
843 //static const uint8_t char_prop_read = ESP_GATT_CHAR_PROP_BIT_READ;
844 //static const uint8_t char_prop_write = ESP_GATT_CHAR_PROP_BIT_WRITE;
845 //static const uint8_t char_prop_read_write_notify = ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_NOTIFY;
846 static const uint8_t char_prop_read_write_writenr_notify = ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_NOTIFY | ESP_GATT_CHAR_PROP_BIT_WRITE_NR;
847
848 static const uint8_t char_value[3] = {0x80, 0x80, 0xfe};
849 static const uint8_t blemidi_ccc[2] = {0x00, 0x00};
850
851 // Full Database Description - Used to add attributes into the database
852 static const esp_gatts_attr_db_t gatt_db[HRS_IDX_NB] =
853 {
854 // Service Declaration
855 [IDX_SVC] =
856 {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&primary_service_uuid, ESP_GATT_PERM_READ,
857 16, sizeof(midi_service_uuid), (uint8_t *)&midi_service_uuid}},
858
859 // Characteristic Declaration
860 [IDX_CHAR_A] =
861 {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_declaration_uuid, ESP_GATT_PERM_READ,
862 CHAR_DECLARATION_SIZE, CHAR_DECLARATION_SIZE, (uint8_t *)&char_prop_read_write_writenr_notify}},
863
864 // Characteristic Value
865 [IDX_CHAR_VAL_A] =
866 {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_128, (uint8_t *)&midi_characteristics_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
867 GATTS_MIDI_CHAR_VAL_LEN_MAX, sizeof(char_value), (uint8_t *)char_value}},
868
869 // Client Characteristic Configuration Descriptor (this is a BLE2902 descriptor)
870 [IDX_CHAR_CFG_A] =
871 {{ESP_GATT_AUTO_RSP}, {ESP_UUID_LEN_16, (uint8_t *)&character_client_config_uuid, ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
872 sizeof(uint16_t), sizeof(blemidi_ccc), (uint8_t *)blemidi_ccc}},
873 };
874
875 static void blemidi_prepare_write_event_env(esp_gatt_if_t gatts_if, prepare_type_env_t *prepare_write_env, esp_ble_gatts_cb_param_t *param)
876 {
877 ESP_LOGI(BLEMIDI_TAG, "prepare write, handle = %d, value len = %d", param->write.handle, param->write.len);
878 esp_gatt_status_t status = ESP_GATT_OK;
879 if (prepare_write_env->prepare_buf == NULL) {
880 prepare_write_env->prepare_buf = (uint8_t *)malloc(PREPARE_BUF_MAX_SIZE * sizeof(uint8_t));
881 prepare_write_env->prepare_len = 0;
882 if (prepare_write_env->prepare_buf == NULL) {
883 ESP_LOGE(BLEMIDI_TAG, "%s, Gatt_server prep no mem", __func__);
884 status = ESP_GATT_NO_RESOURCES;
885 }
886 } else {
887 if(param->write.offset > PREPARE_BUF_MAX_SIZE) {
888 status = ESP_GATT_INVALID_OFFSET;
889 } else if ((param->write.offset + param->write.len) > PREPARE_BUF_MAX_SIZE) {
890 status = ESP_GATT_INVALID_ATTR_LEN;
891 }
892 }
893 /*send response when param->write.need_rsp is true */
894 if (param->write.need_rsp){
895 esp_gatt_rsp_t *gatt_rsp = (esp_gatt_rsp_t *)malloc(sizeof(esp_gatt_rsp_t));
896 if (gatt_rsp != NULL){
897 gatt_rsp->attr_value.len = param->write.len;
898 gatt_rsp->attr_value.handle = param->write.handle;
899 gatt_rsp->attr_value.offset = param->write.offset;
900 gatt_rsp->attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
901 memcpy(gatt_rsp->attr_value.value, param->write.value, param->write.len);
902 esp_err_t response_err = esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, status, gatt_rsp);
903 if (response_err != ESP_OK){
904 ESP_LOGE(BLEMIDI_TAG, "Send response error");
905 }
906 free(gatt_rsp);
907 }else{
908 ESP_LOGE(BLEMIDI_TAG, "%s, malloc failed", __func__);
909 }
910 }
911 if (status != ESP_GATT_OK){
912 return;
913 }
914 memcpy(prepare_write_env->prepare_buf + param->write.offset,
915 param->write.value,
916 param->write.len);
917 prepare_write_env->prepare_len += param->write.len;
918 }
919
920 static void blemidi_exec_write_event_env(prepare_type_env_t *prepare_write_env, esp_ble_gatts_cb_param_t *param){
921 if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC && prepare_write_env->prepare_buf){
922 esp_log_buffer_hex(BLEMIDI_TAG, prepare_write_env->prepare_buf, prepare_write_env->prepare_len);
923 }else{
924 ESP_LOGI(BLEMIDI_TAG,"ESP_GATT_PREP_WRITE_CANCEL");
925 }
926 if (prepare_write_env->prepare_buf) {
927 free(prepare_write_env->prepare_buf);
928 prepare_write_env->prepare_buf = NULL;
929 }
930 prepare_write_env->prepare_len = 0;
931 }
932
933 static void gatts_profile_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
934 {
935 switch (event) {
936 case ESP_GATTS_REG_EVT:{
937 esp_err_t set_dev_name_ret = esp_ble_gap_set_device_name(current_device_name);
938 if (set_dev_name_ret){
939 ESP_LOGE(BLEMIDI_TAG, "set device name failed, error code = %x", set_dev_name_ret);
940 }
941
942 //config adv data
943 esp_err_t ret = esp_ble_gap_config_adv_data(&adv_data);
944 if (ret){
945 ESP_LOGE(BLEMIDI_TAG, "config adv data failed, error code = %x", ret);
946 }
947 adv_config_done |= ADV_CONFIG_FLAG;
948 //config scan response data
949 ret = esp_ble_gap_config_adv_data(&scan_rsp_data);
950 if (ret){
951 ESP_LOGE(BLEMIDI_TAG, "config scan response data failed, error code = %x", ret);
952 }
953 adv_config_done |= SCAN_RSP_CONFIG_FLAG;
954
955 esp_err_t create_attr_ret = esp_ble_gatts_create_attr_tab(gatt_db, gatts_if, HRS_IDX_NB, SVC_INST_ID);
956 if (create_attr_ret){
957 ESP_LOGE(BLEMIDI_TAG, "create attr table failed, error code = %x", create_attr_ret);
958 }
959 }
960 break;
961 case ESP_GATTS_READ_EVT:
962 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTS_READ_EVT");
963 break;
964 case ESP_GATTS_WRITE_EVT:
965 if (!param->write.is_prep){
966 if (midi_handle_table[IDX_CHAR_VAL_A] == param->write.handle ) {
967 // the data length of gattc write must be less than blemidi_mtu.
968 #if 0
969 ESP_LOGI(BLEMIDI_TAG, "GATT_WRITE_EVT, handle = %d, value len = %d, value :", param->write.handle, param->write.len);
970 esp_log_buffer_hex(BLEMIDI_TAG, param->write.value, param->write.len);
971 #endif
972 blemidi_receive_packet(0, param->write.value, param->write.len, blemidi_callback_midi_message_received);
973 }
974 } else {
975 /* handle prepare write */
976 blemidi_prepare_write_event_env(gatts_if, &prepare_write_env, param);
977 }
978 break;
979 case ESP_GATTS_EXEC_WRITE_EVT:
980 // the length of gattc prepare write data must be less than blemidi_mtu.
981 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTS_EXEC_WRITE_EVT");
982 blemidi_exec_write_event_env(&prepare_write_env, param);
983 break;
984 case ESP_GATTS_MTU_EVT:
985 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTS_MTU_EVT, MTU %d", param->mtu.mtu);
986
987 // change MTU for BLE MIDI transactions
988 if( param->mtu.mtu <= 3 ) {
989 blemidi_mtu = 3; // very unlikely...
990 } else {
991 // we decrease -10 to prevent following driver warning:
992 // (30774) BT_GATT: attribute value too long, to be truncated to 97
993 blemidi_mtu = param->mtu.mtu - 3;
994 // failsave
995 if( blemidi_mtu > (GATTS_MIDI_CHAR_VAL_LEN_MAX-3) )
996 blemidi_mtu = (GATTS_MIDI_CHAR_VAL_LEN_MAX-3);
997 }
998 break;
999 case ESP_GATTS_CONF_EVT:
1000 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTS_CONF_EVT, status = %d, attr_handle %d", param->conf.status, param->conf.handle);
1001 break;
1002 case ESP_GATTS_START_EVT:
1003 ESP_LOGI(BLEMIDI_TAG, "SERVICE_START_EVT, status %d, service_handle %d", param->start.status, param->start.service_handle);
1004 break;
1005 case ESP_GATTS_CONNECT_EVT:
1006 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTS_CONNECT_EVT, conn_id = %d", param->connect.conn_id);
1007 esp_log_buffer_hex(BLEMIDI_TAG, param->connect.remote_bda, 6);
1008 esp_ble_conn_update_params_t conn_params = {0};
1009 memcpy(conn_params.bda, param->connect.remote_bda, sizeof(esp_bd_addr_t));
1010 /* For the iOS system, please refer to Apple official documents about the BLE connection parameters restrictions. */
1011 conn_params.latency = 0;
1012 conn_params.max_int = 0x10; // max_int = 0x10*1.25ms = 20ms
1013 conn_params.min_int = 0x0b; // min_int = 0x0b*1.25ms = 15ms
1014 conn_params.timeout = 400; // timeout = 400*10ms = 4000ms
1015 //start sent the update connection parameters to the peer device.
1016 esp_ble_gap_update_conn_params(&conn_params);
1017 break;
1018 case ESP_GATTS_DISCONNECT_EVT:
1019 ESP_LOGI(BLEMIDI_TAG, "ESP_GATTS_DISCONNECT_EVT, reason = 0x%x", param->disconnect.reason);
1020 esp_ble_gap_start_advertising(&adv_params);
1021 break;
1022 case ESP_GATTS_CREAT_ATTR_TAB_EVT:{
1023 if (param->add_attr_tab.status != ESP_GATT_OK){
1024 ESP_LOGE(BLEMIDI_TAG, "create attribute table failed, error code=0x%x", param->add_attr_tab.status);
1025 }
1026 else if (param->add_attr_tab.num_handle != HRS_IDX_NB){
1027 ESP_LOGE(BLEMIDI_TAG, "create attribute table abnormally, num_handle (%d) \
1028 doesn't equal to HRS_IDX_NB(%d)", param->add_attr_tab.num_handle, HRS_IDX_NB);
1029 }
1030 else {
1031 ESP_LOGI(BLEMIDI_TAG, "create attribute table successfully, the number handle = %d\n",param->add_attr_tab.num_handle);
1032 memcpy(midi_handle_table, param->add_attr_tab.handles, sizeof(midi_handle_table));
1033 esp_ble_gatts_start_service(midi_handle_table[IDX_SVC]);
1034 }
1035 break;
1036 }
1037 case ESP_GATTS_STOP_EVT:
1038 case ESP_GATTS_OPEN_EVT:
1039 case ESP_GATTS_CANCEL_OPEN_EVT:
1040 case ESP_GATTS_CLOSE_EVT:
1041 case ESP_GATTS_LISTEN_EVT:
1042 case ESP_GATTS_CONGEST_EVT:
1043 case ESP_GATTS_UNREG_EVT:
1044 case ESP_GATTS_DELETE_EVT:
1045 default:
1046 break;
1047 }
1048 }
1049
1050 static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
1051 {
1052 /* If event is register event, store the gatts_if for each profile */
1053 if (event == ESP_GATTS_REG_EVT) {
1054 if (param->reg.status == ESP_GATT_OK) {
1055 midi_profile_tab[PROFILE_APP_IDX].gatts_if = gatts_if;
1056 } else {
1057 ESP_LOGE(BLEMIDI_TAG, "reg app failed, app_id %04x, status %d",
1058 param->reg.app_id,
1059 param->reg.status);
1060 return;
1061 }
1062 }
1063 do {
1064 int idx;
1065 for (idx = 0; idx < PROFILE_NUM; idx++) {
1066 /* ESP_GATT_IF_NONE, not specify a certain gatt_if, need to call every profile cb function */
1067 if (gatts_if == ESP_GATT_IF_NONE || gatts_if == midi_profile_tab[idx].gatts_if) {
1068 if (midi_profile_tab[idx].gatts_cb) {
1069 midi_profile_tab[idx].gatts_cb(event, gatts_if, param);
1070 }
1071 }
1072 }
1073 } while (0);
1074 }
1075
1076 ///////////////////////////////////////////////////////////////////////////////
1077 // INITIALIZING THE BLE MIDI SERVER
1078 //
1079 // This function should be called from the Faust MIDI handler
1080 // It initializes both a GATT client and a GATT server. This might somewhat
1081 // risky so if there are bugs, that should be the first place to look.
1082 ///////////////////////////////////////////////////////////////////////////////
1083
1084 int32_t blemidi_init(void *_callback_midi_message_received, const char* device_name, const char* remote_name, void *arg)
1085 {
1086 esp_err_t ret;
1087
1088 current_device_name = device_name;
1089 remote_device_name = remote_name;
1090 callback_arg = arg;
1091
1092 // callback will be installed if driver was booted successfully
1093 blemidi_callback_midi_message_received = NULL;
1094
1095 /* Initialize NVS. */
1096 ret = nvs_flash_init();
1097 if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
1098 ESP_ERROR_CHECK(nvs_flash_erase());
1099 ret = nvs_flash_init();
1100 }
1101 ESP_ERROR_CHECK( ret );
1102
1103 ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT));
1104
1105 /* Initialize Bluedroid. */
1106 esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
1107 ret = esp_bt_controller_init(&bt_cfg);
1108 if (ret) {
1109 ESP_LOGE(BLEMIDI_TAG, "%s enable controller failed: %s", __func__, esp_err_to_name(ret));
1110 return -1;
1111 }
1112
1113 ret = esp_bt_controller_enable(ESP_BT_MODE_BLE);
1114 if (ret) {
1115 ESP_LOGE(BLEMIDI_TAG, "%s enable controller failed: %s", __func__, esp_err_to_name(ret));
1116 return -2;
1117 }
1118
1119 ret = esp_bluedroid_init();
1120 if (ret) {
1121 ESP_LOGE(BLEMIDI_TAG, "%s init bluetooth failed: %s", __func__, esp_err_to_name(ret));
1122 return -3;
1123 }
1124
1125 ret = esp_bluedroid_enable();
1126 if (ret) {
1127 ESP_LOGE(BLEMIDI_TAG, "%s enable bluetooth failed: %s", __func__, esp_err_to_name(ret));
1128 return -4;
1129 }
1130
1131 ret = esp_ble_gatts_register_callback(gatts_event_handler);
1132 if (ret){
1133 ESP_LOGE(BLEMIDI_TAG, "gatts register error, error code = %x", ret);
1134 return -5;
1135 }
1136
1137 ret = esp_ble_gap_register_callback(gap_event_handler);
1138 if (ret){
1139 ESP_LOGE(BLEMIDI_TAG, "gap register error, error code = %x", ret);
1140 return -6;
1141 }
1142
1143 ret = esp_ble_gatts_app_register(ESP_APP_ID);
1144 if (ret){
1145 ESP_LOGE(BLEMIDI_TAG, "gatts app register error, error code = %x", ret);
1146 return -7;
1147 }
1148
1149 if(strcmp(remote_name,"") != 0){
1150 ret = esp_ble_gattc_register_callback(esp_gattc_cb);
1151 if (ret){
1152 ESP_LOGE(BLEMIDI_TAG, "gattc register failed, error code = %x", ret);
1153 return -8;
1154 }
1155
1156 ret = esp_ble_gattc_app_register(PROFILE_A_APP_ID);
1157 if (ret){
1158 ESP_LOGE(BLEMIDI_TAG, "gattc app register error, error code = %x", ret);
1159 return -9;
1160 }
1161 }
1162
1163 esp_err_t local_mtu_ret = esp_ble_gatt_set_local_mtu(GATTS_MIDI_CHAR_VAL_LEN_MAX);
1164 if (local_mtu_ret){
1165 ESP_LOGE(BLEMIDI_TAG, "set local MTU failed, error code = %x", local_mtu_ret);
1166 return -10;
1167 }
1168
1169 // Output Buffer
1170 {
1171 uint32_t blemidi_port;
1172 for(blemidi_port=0; blemidi_port<BLEMIDI_NUM_PORTS; ++blemidi_port) {
1173 blemidi_outbuffer_len[blemidi_port] = 0;
1174 blemidi_continued_sysex_pos[blemidi_port] = 0;
1175 }
1176 }
1177
1178 // Finally install callback
1179 blemidi_callback_midi_message_received = _callback_midi_message_received;
1180
1181 esp_log_level_set(BLEMIDI_TAG, ESP_LOG_WARN); // can be changed with the "blemidi_debug on" console command
1182
1183 return 0; // no error
1184 }