├── library.properties ├── keywords.txt ├── examples ├── USBH_MIDI_dump │ └── USBH_MIDI_dump.ino ├── eVY1_sample │ └── eVY1_sample.ino ├── USB_MIDI_converter │ └── USB_MIDI_converter.ino ├── USB_MIDI_converter_multi │ └── USB_MIDI_converter_multi.ino ├── USB_MIDI_converter_wSysEx │ └── USB_MIDI_converter_wSysEx.ino ├── bidirectional_converter │ └── bidirectional_converter.ino └── USB_MIDI_desc │ └── USB_MIDI_desc.ino ├── README.md ├── usbh_midi.h ├── LICENSE └── usbh_midi.cpp /library.properties: -------------------------------------------------------------------------------- 1 | name=USBH_MIDI 2 | version=1.0.0 3 | author=Yuuichi Akagawa <@YuuichiAkagawa> 4 | maintainer=Yuuichi Akagawa <@YuuichiAkagawa> 5 | sentence=USB MIDI class driver for Arduino USB Host Shield 2.0 Library. 6 | paragraph= 7 | category=Communication 8 | url=https://github.com/YuuichiAkagawa/USBH_MIDI/ 9 | architectures=* 10 | depends=USB Host Shield Library 2.0 11 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map For USBH_MIDI 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | USBH_MIDI KEYWORD1 9 | USBH_MIDI.h KEYWORD1 10 | ####################################### 11 | # Methods and Functions (KEYWORD2) 12 | ####################################### 13 | RecvData KEYWORD2 14 | SendData KEYWORD2 15 | RecvRawData KEYWORD2 16 | SendRawData KEYWORD2 17 | SendSysEx KEYWORD2 18 | extractSysExData KEYWORD2 19 | lookupMsgSize KEYWORD2 20 | attachOnInit KEYWORD2 21 | ####################################### 22 | # Instances (KEYWORD2) 23 | ####################################### 24 | Midi KEYWORD2 25 | ####################################### 26 | # Constants (LITERAL1) 27 | ####################################### 28 | 29 | -------------------------------------------------------------------------------- /examples/USBH_MIDI_dump/USBH_MIDI_dump.ino: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * USB-MIDI dump utility 4 | * Copyright (C) 2013-2021 Yuuichi Akagawa 5 | * 6 | * for use with USB Host Shield 2.0 from Circuitsathome.com 7 | * https://github.com/felis/USB_Host_Shield_2.0 8 | * 9 | * This is sample program. Do not expect perfect behavior. 10 | ******************************************************************************* 11 | */ 12 | 13 | #include 14 | #include 15 | 16 | USB Usb; 17 | USBHub Hub(&Usb); 18 | USBH_MIDI Midi(&Usb); 19 | 20 | void MIDI_poll(); 21 | 22 | void onInit() 23 | { 24 | char buf[20]; 25 | uint16_t vid = Midi.idVendor(); 26 | uint16_t pid = Midi.idProduct(); 27 | sprintf(buf, "VID:%04X, PID:%04X", vid, pid); 28 | Serial.println(buf); 29 | } 30 | 31 | void setup() 32 | { 33 | Serial.begin(115200); 34 | 35 | if (Usb.Init() == -1) { 36 | while (1); //halt 37 | }//if (Usb.Init() == -1... 38 | delay( 200 ); 39 | 40 | // Register onInit() function 41 | Midi.attachOnInit(onInit); 42 | } 43 | 44 | void loop() 45 | { 46 | Usb.Task(); 47 | if ( Midi ) { 48 | MIDI_poll(); 49 | } 50 | } 51 | 52 | // Poll USB MIDI Controler and send to serial MIDI 53 | void MIDI_poll() 54 | { 55 | char buf[16]; 56 | uint8_t bufMidi[MIDI_EVENT_PACKET_SIZE]; 57 | uint16_t rcvd; 58 | 59 | if (Midi.RecvData( &rcvd, bufMidi) == 0 ) { 60 | uint32_t time = (uint32_t)millis(); 61 | sprintf(buf, "%04X%04X:%3d:", (uint16_t)(time >> 16), (uint16_t)(time & 0xFFFF), rcvd); // Split variable to prevent warnings on the ESP8266 platform 62 | Serial.print(buf); 63 | 64 | for (int i = 0; i < MIDI_EVENT_PACKET_SIZE; i++) { 65 | sprintf(buf, " %02X", bufMidi[i]); 66 | Serial.print(buf); 67 | } 68 | Serial.println(""); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /examples/eVY1_sample/eVY1_sample.ino: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | eVY1 Shield sample - Say 'Konnichiwa' 4 | Copyright (C) 2014-2021 Yuuichi Akagawa 5 | 6 | This is sample program. Do not expect perfect behavior. 7 | ******************************************************************************* 8 | */ 9 | #include 10 | #include 11 | 12 | USB Usb; 13 | //USBHub Hub(&Usb); 14 | USBH_MIDI Midi(&Usb); 15 | 16 | void MIDI_poll(); 17 | void noteOn(uint8_t note); 18 | void noteOff(uint8_t note); 19 | 20 | uint8_t exdata[] = { 21 | 0xf0, 0x43, 0x79, 0x09, 0x00, 0x50, 0x10, 22 | 'k', ' ', 'o', ',', //Ko 23 | 'N', '\\', ',', //N 24 | 'J', ' ', 'i', ',', //Ni 25 | 't', 'S', ' ', 'i', ',', //Chi 26 | 'w', ' ', 'a', //Wa 27 | 0x00, 0xf7 28 | }; 29 | 30 | void onInit() 31 | { 32 | // Send Phonetic symbols via SysEx 33 | Midi.SendSysEx(exdata, sizeof(exdata)); 34 | delay(500); 35 | } 36 | 37 | void setup() 38 | { 39 | if (Usb.Init() == -1) { 40 | while (1); //halt 41 | }//if (Usb.Init() == -1... 42 | delay( 200 ); 43 | 44 | // Register onInit() function 45 | Midi.attachOnInit(onInit); 46 | } 47 | 48 | void loop() 49 | { 50 | Usb.Task(); 51 | if ( Midi ) { 52 | MIDI_poll(); 53 | noteOn(0x3f); 54 | delay(400); 55 | noteOff(0x3f); 56 | delay(100); 57 | } 58 | } 59 | 60 | // Poll USB MIDI Controler 61 | void MIDI_poll() 62 | { 63 | uint8_t inBuf[ 3 ]; 64 | Midi.RecvData(inBuf); 65 | } 66 | 67 | //note On 68 | void noteOn(uint8_t note) 69 | { 70 | uint8_t buf[3]; 71 | buf[0] = 0x90; 72 | buf[1] = note; 73 | buf[2] = 0x7f; 74 | Midi.SendData(buf); 75 | } 76 | 77 | //note Off 78 | void noteOff(uint8_t note) 79 | { 80 | uint8_t buf[3]; 81 | buf[0] = 0x80; 82 | buf[1] = note; 83 | buf[2] = 0x00; 84 | Midi.SendData(buf); 85 | } 86 | -------------------------------------------------------------------------------- /examples/USB_MIDI_converter/USB_MIDI_converter.ino: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * USB-MIDI to Legacy Serial MIDI converter 4 | * Copyright 2012-2021 Yuuichi Akagawa 5 | * 6 | * Idea from LPK25 USB-MIDI to Serial MIDI converter 7 | * by Collin Cunningham - makezine.com, narbotic.com 8 | * 9 | * for use with USB Host Shield 2.0 from Circuitsathome.com 10 | * https://github.com/felis/USB_Host_Shield_2.0 11 | ******************************************************************************* 12 | * This program 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 2 of the License, or 15 | * (at your option) any later version. 16 | * 17 | * This program 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 this program. If not, see 24 | ******************************************************************************* 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | #ifdef USBCON 31 | #define _MIDI_SERIAL_PORT Serial1 32 | #else 33 | #define _MIDI_SERIAL_PORT Serial 34 | #endif 35 | ////////////////////////// 36 | // MIDI Pin assign 37 | // 2 : GND 38 | // 4 : +5V(Vcc) with 220ohm 39 | // 5 : TX 40 | ////////////////////////// 41 | 42 | USB Usb; 43 | USBH_MIDI Midi(&Usb); 44 | 45 | void MIDI_poll(); 46 | 47 | void setup() 48 | { 49 | _MIDI_SERIAL_PORT.begin(31250); 50 | 51 | if (Usb.Init() == -1) { 52 | while (1); //halt 53 | }//if (Usb.Init() == -1... 54 | delay( 200 ); 55 | } 56 | 57 | void loop() 58 | { 59 | Usb.Task(); 60 | 61 | if ( Midi ) { 62 | MIDI_poll(); 63 | } 64 | //delay(1ms) if you want 65 | //delayMicroseconds(1000); 66 | } 67 | 68 | // Poll USB MIDI Controler and send to serial MIDI 69 | void MIDI_poll() 70 | { 71 | uint8_t outBuf[ 3 ]; 72 | uint8_t size; 73 | 74 | do { 75 | if ( (size = Midi.RecvData(outBuf)) > 0 ) { 76 | //MIDI Output 77 | _MIDI_SERIAL_PORT.write(outBuf, size); 78 | } 79 | } while (size > 0); 80 | } 81 | -------------------------------------------------------------------------------- /examples/USB_MIDI_converter_multi/USB_MIDI_converter_multi.ino: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * USB-MIDI to Legacy Serial MIDI converter 4 | * Copyright 2012-2021 Yuuichi Akagawa 5 | * 6 | * Idea from LPK25 USB-MIDI to Serial MIDI converter 7 | * by Collin Cunningham - makezine.com, narbotic.com 8 | * 9 | * for use with USB Host Shield 2.0 from Circuitsathome.com 10 | * https://github.com/felis/USB_Host_Shield_2.0 11 | ******************************************************************************* 12 | * This program 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 2 of the License, or 15 | * (at your option) any later version. 16 | * 17 | * This program 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 this program. If not, see 24 | ******************************************************************************* 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | #ifdef USBCON 31 | #define _MIDI_SERIAL_PORT Serial1 32 | #else 33 | #define _MIDI_SERIAL_PORT Serial 34 | #endif 35 | ////////////////////////// 36 | // MIDI Pin assign 37 | // 2 : GND 38 | // 4 : +5V(Vcc) with 220ohm 39 | // 5 : TX 40 | ////////////////////////// 41 | 42 | USB Usb; 43 | USBHub Hub1(&Usb); 44 | USBH_MIDI Midi1(&Usb); 45 | USBH_MIDI Midi2(&Usb); 46 | 47 | void MIDI_poll(USBH_MIDI &Midi); 48 | 49 | void setup() 50 | { 51 | _MIDI_SERIAL_PORT.begin(31250); 52 | 53 | if (Usb.Init() == -1) { 54 | while (1); //halt 55 | }//if (Usb.Init() == -1... 56 | delay( 200 ); 57 | } 58 | 59 | void loop() 60 | { 61 | Usb.Task(); 62 | 63 | if ( Midi1 ) { 64 | MIDI_poll(Midi1); 65 | } 66 | if ( Midi2 ) { 67 | MIDI_poll(Midi2); 68 | } 69 | //delay(1ms) if you want 70 | //delayMicroseconds(1000); 71 | } 72 | 73 | // Poll USB MIDI Controler and send to serial MIDI 74 | void MIDI_poll(USBH_MIDI &Midi) 75 | { 76 | uint8_t outBuf[ 3 ]; 77 | uint8_t size; 78 | 79 | do { 80 | if ( (size = Midi.RecvData(outBuf)) > 0 ) { 81 | //MIDI Output 82 | _MIDI_SERIAL_PORT.write(outBuf, size); 83 | } 84 | } while (size > 0); 85 | } 86 | -------------------------------------------------------------------------------- /examples/USB_MIDI_converter_wSysEx/USB_MIDI_converter_wSysEx.ino: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * USB-MIDI to Legacy Serial MIDI converter with SysEx support 4 | * Copyright 2017-2021 Yuuichi Akagawa 5 | * 6 | * Idea from LPK25 USB-MIDI to Serial MIDI converter 7 | * by Collin Cunningham - makezine.com, narbotic.com 8 | * 9 | * for use with USB Host Shield 2.0 from Circuitsathome.com 10 | * https://github.com/felis/USB_Host_Shield_2.0 11 | ******************************************************************************* 12 | * This program 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 2 of the License, or 15 | * (at your option) any later version. 16 | * 17 | * This program 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 this program. If not, see 24 | ******************************************************************************* 25 | */ 26 | 27 | #include 28 | #include 29 | 30 | #ifdef USBCON 31 | #define _MIDI_SERIAL_PORT Serial1 32 | #else 33 | #define _MIDI_SERIAL_PORT Serial 34 | #endif 35 | ////////////////////////// 36 | // MIDI Pin assign 37 | // 2 : GND 38 | // 4 : +5V(Vcc) with 220ohm 39 | // 5 : TX 40 | ////////////////////////// 41 | 42 | USB Usb; 43 | USBH_MIDI Midi(&Usb); 44 | 45 | void MIDI_poll(); 46 | 47 | void setup() 48 | { 49 | _MIDI_SERIAL_PORT.begin(31250); 50 | 51 | if (Usb.Init() == -1) { 52 | while (1); //halt 53 | }//if (Usb.Init() == -1... 54 | delay( 200 ); 55 | } 56 | 57 | void loop() 58 | { 59 | Usb.Task(); 60 | 61 | if ( Midi ) { 62 | MIDI_poll(); 63 | } 64 | //delay(1ms) if you want 65 | //delayMicroseconds(1000); 66 | } 67 | 68 | // Poll USB MIDI Controler and send to serial MIDI 69 | void MIDI_poll() 70 | { 71 | uint8_t size; 72 | uint8_t outBuf[4]; 73 | uint8_t sysexBuf[3]; 74 | 75 | do { 76 | if ( (size = Midi.RecvRawData(outBuf)) > 0 ) { 77 | //MIDI Output 78 | uint8_t rc = Midi.extractSysExData(outBuf, sysexBuf); 79 | if ( rc != 0 ) { //SysEx 80 | _MIDI_SERIAL_PORT.write(sysexBuf, rc); 81 | } else { //SysEx 82 | _MIDI_SERIAL_PORT.write(outBuf + 1, size); 83 | } 84 | } 85 | } while (size > 0); 86 | } 87 | -------------------------------------------------------------------------------- /examples/bidirectional_converter/bidirectional_converter.ino: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | Legacy Serial MIDI and USB Host bidirectional converter 4 | Copyright (C) 2013-2021 Yuuichi Akagawa 5 | 6 | for use with Arduino MIDI library 7 | https://github.com/FortySevenEffects/arduino_midi_library/ 8 | 9 | Note: 10 | - If you want use with Leonardo, you must choose Arduino MIDI library v4.0 or higher. 11 | - This is sample program. Do not expect perfect behavior. 12 | ******************************************************************************* 13 | */ 14 | 15 | #include 16 | #include 17 | #include 18 | 19 | //Arduino MIDI library v4.2 compatibility 20 | #ifdef MIDI_CREATE_DEFAULT_INSTANCE 21 | MIDI_CREATE_DEFAULT_INSTANCE(); 22 | #endif 23 | #ifdef USBCON 24 | #define _MIDI_SERIAL_PORT Serial1 25 | #else 26 | #define _MIDI_SERIAL_PORT Serial 27 | #endif 28 | 29 | ////////////////////////// 30 | // MIDI Pin assign 31 | // 2 : GND 32 | // 4 : +5V(Vcc) with 220ohm 33 | // 5 : TX 34 | ////////////////////////// 35 | 36 | USB Usb; 37 | USBH_MIDI Midi(&Usb); 38 | 39 | void MIDI_poll(); 40 | 41 | //If you want handle System Exclusive message, enable this #define otherwise comment out it. 42 | #define USBH_MIDI_SYSEX_ENABLE 43 | 44 | #ifdef USBH_MIDI_SYSEX_ENABLE 45 | //SysEx: 46 | void handle_sysex( byte* sysexmsg, unsigned sizeofsysex) { 47 | Midi.SendSysEx(sysexmsg, sizeofsysex); 48 | } 49 | #endif 50 | 51 | void setup() 52 | { 53 | MIDI.begin(MIDI_CHANNEL_OMNI); 54 | MIDI.turnThruOff(); 55 | #ifdef USBH_MIDI_SYSEX_ENABLE 56 | MIDI.setHandleSystemExclusive(handle_sysex); 57 | #endif 58 | if (Usb.Init() == -1) { 59 | while (1); //halt 60 | }//if (Usb.Init() == -1... 61 | delay( 200 ); 62 | } 63 | 64 | void loop() 65 | { 66 | uint8_t msg[4]; 67 | 68 | Usb.Task(); 69 | if ( Midi ) { 70 | MIDI_poll(); 71 | if (MIDI.read()) { 72 | msg[0] = MIDI.getType(); 73 | switch (msg[0]) { 74 | case midi::ActiveSensing : 75 | break; 76 | case midi::SystemExclusive : 77 | //SysEx is handled by event. 78 | break; 79 | default : 80 | if( msg[0] < 0xf0 ){ 81 | msg[0] |= MIDI.getChannel() - 1; 82 | } 83 | msg[1] = MIDI.getData1(); 84 | msg[2] = MIDI.getData2(); 85 | Midi.SendData(msg, 0); 86 | break; 87 | } 88 | } 89 | } 90 | } 91 | 92 | // Poll USB MIDI Controler and send to serial MIDI 93 | void MIDI_poll() 94 | { 95 | uint8_t size; 96 | #ifdef USBH_MIDI_SYSEX_ENABLE 97 | uint8_t recvBuf[MIDI_EVENT_PACKET_SIZE]; 98 | uint8_t rcode = 0; //return code 99 | uint16_t rcvd; 100 | uint8_t readPtr = 0; 101 | 102 | rcode = Midi.RecvData( &rcvd, recvBuf); 103 | 104 | //data check 105 | if (rcode != 0) return; 106 | if ( recvBuf[0] == 0 && recvBuf[1] == 0 && recvBuf[2] == 0 && recvBuf[3] == 0 ) { 107 | return ; 108 | } 109 | 110 | uint8_t *p = recvBuf; 111 | while (readPtr < MIDI_EVENT_PACKET_SIZE) { 112 | if (*p == 0 && *(p + 1) == 0) break; //data end 113 | 114 | uint8_t outbuf[3]; 115 | uint8_t rc = Midi.extractSysExData(p, outbuf); 116 | if ( rc == 0 ) { 117 | p++; 118 | size = Midi.lookupMsgSize(*p); 119 | _MIDI_SERIAL_PORT.write(p, size); 120 | p += 3; 121 | } else { 122 | _MIDI_SERIAL_PORT.write(outbuf, rc); 123 | p += 4; 124 | } 125 | readPtr += 4; 126 | } 127 | #else 128 | uint8_t outBuf[3]; 129 | do { 130 | if ( (size = Midi.RecvData(outBuf)) > 0 ) { 131 | //MIDI Output 132 | _MIDI_SERIAL_PORT.write(outBuf, size); 133 | } 134 | } while (size > 0); 135 | #endif 136 | } 137 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # USBH_MIDI v1.0.0 2 | 3 | USB-MIDI 1.0 class driver for Arduino [USB Host Shield 2.0 Library][UHS2] 4 | 5 | USBH_MIDI is USB-MIDI class driver for Arduino USB Host Shield 2.0 Library. 6 | USBH_MIDI is included in [USB Host Shield 2.0 Library][UHS2]. You don't need install separatery. 7 | 8 | If you want use with [Arduino MIDI Library][MIDILIB], try the [Transport][UHS2MIDI] 9 | 10 | ### for single device 11 | > File->Examples->USBH_MIDI->USB_MIDI_converter 12 | 13 | ### for single device with SysEx support 14 | > File->Examples->USBH_MIDI->USB_MIDI_converter_wSysEx 15 | 16 | ### for multiple device (with USB hub) 17 | > File->Examples->USBH_MIDI->USB_MIDI_converter_multi 18 | 19 | ### for bidirectional conversion 20 | > File->Examples->USBH_MIDI->bidirectional_converter 21 | 22 | ### Examine the descriptor of your USB-MIDI device. 23 | > File->Examples->USBH_MIDI->USB_MIDI_desc 24 | If your device does not work, please report this information. 25 | 26 | ## API 27 | 28 | - `uint8_t RecvData(uint8_t *outBuf)` 29 | 30 | Receive MIDI message (3 bytes) 31 | return value is MIDI message length(0-3) 32 | 33 | - `uint8_t RecvData(uint16_t *bytes_rcvd, uint8_t *dataptr)` 34 | 35 | Receive raw USB-MIDI Event Packets (each 4 bytes, upto 64 bytes) 36 | `dataptr` must allocate 64bytes buffer. 37 | return value is 0:Success, non-zero:Error(MAX3421E HRSLT) and bytes_rcvd is received USB packet length. 38 | note: USB packet length is not necessarily the length of the MIDI message. 39 | 40 | - `uint8_t RecvRawData(uint8_t *outBuf)` 41 | 42 | Receive MIDI Event Packet (4 bytes) 43 | return value is MIDI message length(0-3) 44 | 45 | - `uint8_t SendData(uint8_t *dataptr, uint8_t nCable=0)` 46 | 47 | Send MIDI message. You can set CableNumber(default=0). 48 | return value is 0:Success, non-zero:Error(MAX3421E HRSLT) 49 | 50 | - `uint8_t SendRawData(uint16_t bytes_send, uint8_t *dataptr)` 51 | 52 | Send raw data. You can send any data to MIDI. (no compliant USB-MIDI event packet) 53 | return value is 0:Success, non-zero:Error(MAX3421E HRSLT) 54 | 55 | - `uint8_t SendSysEx(uint8_t *dataptr, uint8_t datasize, uint8_t nCable=0)` 56 | 57 | Send SysEx MIDI message. You can set CableNumber(default=0). 58 | return value is 0:Success, non-zero:Error(MAX3421E HRSLT) 59 | note: 60 | - You must set first byte:0xf0 and last byte:0xf7 61 | - Max message length is up to 256 bytes. If you want extend it change the MIDI_MAX_SYSEX_SIZE. 62 | 63 | - `void attachOnInit(void (*funcOnInit)(void))` 64 | 65 | Register a user function to call when the controller is successfully initialized. 66 | See 'eVY1_sample' example. 67 | 68 | - `void attachOnRelease(void (*funcOnRelease)(void))` 69 | 70 | Register a user function to call when the device is removed. 71 | 72 | - `uint16_t idVendor())` 73 | 74 | Get the vendor ID. 75 | 76 | - `uint16_t idProduct())` 77 | 78 | Get the product ID. 79 | 80 | - `uint8_t GetAddress()` 81 | 82 | Get the USB device address. 83 | 84 | ## ChangeLog 85 | 2022.4.22 (1.0.0) 86 | * Add OnRelease() callback. 87 | * The timing for enabling PollEnable has been changed to before the onInit() callback. 88 | * Update vender specific code for Novation. 89 | 90 | 2022.1.6 (0.6.1) 91 | * Fix for RecvData(uint8_t) does not work when CableNumber(CN) is non-zero. 92 | 93 | 2021.5.9 (0.6.0) 94 | * Change configuration descriptor parser. Supports large descriptors. 95 | * Fixed an issue when the endpoint size exceeded 64 bytes 96 | * Add OnInit() callback 97 | * Add a predefined macro "USBH_MIDI_VERSION". 98 | * Changed the method of deriving the message length 99 | * Refine the examples 100 | 101 | 2021.1.11 (0.5.1) 102 | * Fix for bool operator. 103 | 104 | 2020.11.23 (0.5.0) 105 | * Change to Windows style enumeration process. 106 | 107 | 2020.11.21 (0.4.1) 108 | * Add new example USB_MIDI_desc 109 | * Update vender specific code for Novation 110 | 111 | 2018.03.24 (0.4.0) 112 | * Add boolean operator 113 | * Add idVendor()/idProduct() function. vid/pid variables have been change to private. 114 | * Update the examples using new feature. 115 | * Vendor/Device specific setup (workaround for novation LaunchPad series) 116 | 117 | 2017.02.22 (0.3.2) 118 | * Improve reconnect stability. 119 | * Fix for MIDI out only device support. 120 | * Update SysEx code 121 | * Remove MidiSysEx class 122 | * Add new example USB_MIDI_converter_wSysEx 123 | * Fix typo: the example name was corrected from 'bidrectional_converter' to 'bidirectional_converter'. 124 | 125 | 2016.04.26 (0.3.1) 126 | * Change the type of the variables from byte to uint8_t. 127 | 128 | 2016.04.24 (0.3.0) 129 | * Limited support for System Exclusive message on bidirectional_converter example. 130 | * Add MidiSysEx Class for System Exclusive packet data management. 131 | 132 | 2016.04.09 (0.2.2) 133 | * Improve SysExSend() performance. 134 | * Add SendRawData() 135 | * Update debug messages 136 | 137 | 2016.03.21 (0.2.1) 138 | * Join the USB Host Shield 2.0 Library. 139 | * Adjust indentation 140 | 141 | 2015.09.06 (0.2.0) 142 | * Compatible with USB Host Shield 2.0 Library 1.0.0 or lator. 143 | * Compatible with Arduino IDE 1.6.0 or lator. 144 | * Fix for less than 64 bytes USB packet devices 145 | * SysEx message was broken since felis/USB_Host_Shield_2.0@45df706 146 | 147 | 2014.07.06 (0.1.0) 148 | * Merge IOP_ArduinoMIDI branch into master 149 | * Change class name to USBH_MIDI 150 | * Rename the function RcvData to RecvData (Old name is still available) 151 | * Fix examples for Arduino MIDI Library 4.2 compatibility 152 | * Add SendSysEx() 153 | * Add new example (eVY1_sample) 154 | 155 | 2014.03.23 156 | * Fix examples for Arduino MIDI Library 4.0 compatibility and Leonardo 157 | 158 | 2013.12.20 159 | * Fix multiple MIDI message problem. 160 | * Add new example (USBH_MIDI_dump) 161 | 162 | 2013.11.05 163 | * Removed all unnecessary includes. (latest UHS2 compatibility) 164 | * Rename all example extensions to .ino 165 | 166 | 2013.08.28 167 | * Fix MIDI Channel issue. 168 | 169 | 2013.08.18 170 | * RcvData() Return type is changed to uint8_t. 171 | * Fix examples. 172 | 173 | 2012.06.22 174 | * Support MIDI out and loosen device check 175 | 176 | 2012.04.21 177 | * First release 178 | 179 | 180 | ## License 181 | 182 | Copyright © 2012-2021 Yuuichi Akagawa 183 | 184 | Licensed under the [GNU General Public License v2.0][GPL2] 185 | 186 | [GPL2]: http://www.gnu.org/licenses/gpl2.html 187 | [wiki]: https://github.com/YuuichiAkagawa/USBH_MIDI/wiki 188 | [UHS2]: https://github.com/felis/USB_Host_Shield_2.0 189 | [GHP]: http://yuuichiakagawa.github.io/USBH_MIDI/ 190 | [MIDILIB]: https://github.com/FortySevenEffects/arduino_midi_library 191 | [UHS2MIDI]: https://github.com/YuuichiAkagawa/Arduino-UHS2MIDI 192 | -------------------------------------------------------------------------------- /usbh_midi.h: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * USB-MIDI class driver for USB Host Shield 2.0 Library 4 | * Copyright (c) 2012-2022 Yuuichi Akagawa 5 | * 6 | * Idea from LPK25 USB-MIDI to Serial MIDI converter 7 | * by Collin Cunningham - makezine.com, narbotic.com 8 | * 9 | * for use with USB Host Shield 2.0 from Circuitsathome.com 10 | * https://github.com/felis/USB_Host_Shield_2.0 11 | ******************************************************************************* 12 | * This program 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 2 of the License, or 15 | * (at your option) any later version. 16 | * 17 | * This program 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 this program. If not, see 24 | ******************************************************************************* 25 | */ 26 | 27 | #if !defined(_USBH_MIDI_H_) 28 | #define _USBH_MIDI_H_ 29 | #include "Usb.h" 30 | 31 | #define USBH_MIDI_VERSION 10000 32 | #define MIDI_MAX_ENDPOINTS 3 //endpoint 0, bulk_IN(MIDI), bulk_OUT(MIDI) 33 | #define USB_SUBCLASS_MIDISTREAMING 3 34 | #define MIDI_EVENT_PACKET_SIZE 64 35 | #define MIDI_MAX_SYSEX_SIZE 256 36 | 37 | namespace _ns_USBH_MIDI { 38 | const uint8_t cin2len[] PROGMEM = {0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1}; 39 | const uint8_t sys2cin[] PROGMEM = {0, 2, 3, 2, 0, 0, 5, 0, 0xf, 0, 0xf, 0xf, 0xf, 0, 0xf, 0xf}; 40 | } 41 | 42 | // Endpoint Descriptor extracter Class 43 | class UsbMidiConfigXtracter { 44 | public: 45 | //virtual void ConfigXtract(const USB_CONFIGURATION_DESCRIPTOR *conf) = 0; 46 | //virtual void InterfaceXtract(uint8_t conf, const USB_INTERFACE_DESCRIPTOR *iface) = 0; 47 | 48 | virtual bool EndpointXtract(uint8_t conf __attribute__((unused)), uint8_t iface __attribute__((unused)), uint8_t alt __attribute__((unused)), uint8_t proto __attribute__((unused)), const USB_ENDPOINT_DESCRIPTOR *ep __attribute__((unused))) { 49 | return true; 50 | }; 51 | }; 52 | // Configuration Descriptor Parser Class 53 | class MidiDescParser : public USBReadParser { 54 | UsbMidiConfigXtracter *theXtractor; 55 | MultiValueBuffer theBuffer; 56 | MultiByteValueParser valParser; 57 | ByteSkipper theSkipper; 58 | uint8_t varBuffer[16 /*sizeof(USB_CONFIGURATION_DESCRIPTOR)*/]; 59 | 60 | uint8_t stateParseDescr; // ParseDescriptor state 61 | 62 | uint8_t dscrLen; // Descriptor length 63 | uint8_t dscrType; // Descriptor type 64 | uint8_t nEPs; // number of valid endpoint 65 | bool isMidiSearch; //Configuration mode true: MIDI, false: Vendor specific 66 | 67 | bool isGoodInterface; // Apropriate interface flag 68 | uint8_t confValue; // Configuration value 69 | 70 | bool ParseDescriptor(uint8_t **pp, uint16_t *pcntdn); 71 | 72 | public: 73 | MidiDescParser(UsbMidiConfigXtracter *xtractor, bool modeMidi); 74 | void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset); 75 | inline uint8_t getConfValue() { return confValue; }; 76 | inline uint8_t getNumEPs() { return nEPs; }; 77 | }; 78 | 79 | /** This class implements support for a MIDI device. */ 80 | class USBH_MIDI : public USBDeviceConfig, public UsbMidiConfigXtracter 81 | { 82 | protected: 83 | static const uint8_t epDataInIndex = 1; // DataIn endpoint index(MIDI) 84 | static const uint8_t epDataOutIndex= 2; // DataOUT endpoint index(MIDI) 85 | 86 | /* mandatory members */ 87 | USB *pUsb; 88 | uint8_t bAddress; 89 | bool bPollEnable; 90 | uint16_t pid, vid; // ProductID, VendorID 91 | uint8_t bTransferTypeMask; 92 | /* Endpoint data structure */ 93 | EpInfo epInfo[MIDI_MAX_ENDPOINTS]; 94 | /* MIDI Event packet buffer */ 95 | uint8_t recvBuf[MIDI_EVENT_PACKET_SIZE]; 96 | uint8_t readPtr; 97 | 98 | uint16_t countSysExDataSize(uint8_t *dataptr); 99 | void setupDeviceSpecific(); 100 | inline uint8_t convertStatus2Cin(uint8_t status) { 101 | return ((status < 0xf0) ? ((status & 0xF0) >> 4) : pgm_read_byte_near(_ns_USBH_MIDI::sys2cin + (status & 0x0F))); 102 | }; 103 | inline uint8_t getMsgSizeFromCin(uint8_t cin) { 104 | return pgm_read_byte_near(_ns_USBH_MIDI::cin2len + cin); 105 | }; 106 | 107 | /* UsbConfigXtracter implementation */ 108 | bool EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); 109 | 110 | #ifdef DEBUG_USB_HOST 111 | void PrintEndpointDescriptor( const USB_ENDPOINT_DESCRIPTOR* ep_ptr ); 112 | #endif 113 | public: 114 | USBH_MIDI(USB *p); 115 | // Misc functions 116 | operator bool() { return (bPollEnable); } 117 | uint16_t idVendor() { return vid; } 118 | uint16_t idProduct() { return pid; } 119 | // Methods for recieving and sending data 120 | uint8_t RecvData(uint16_t *bytes_rcvd, uint8_t *dataptr); 121 | uint8_t RecvData(uint8_t *outBuf, bool isRaw=false); 122 | inline uint8_t RecvRawData(uint8_t *outBuf) { return RecvData(outBuf, true); }; 123 | uint8_t SendData(uint8_t *dataptr, uint8_t nCable=0); 124 | inline uint8_t SendRawData(uint16_t bytes_send, uint8_t *dataptr) { return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, bytes_send, dataptr); }; 125 | uint8_t lookupMsgSize(uint8_t midiMsg, uint8_t cin=0); 126 | uint8_t SendSysEx(uint8_t *dataptr, uint16_t datasize, uint8_t nCable=0); 127 | uint8_t extractSysExData(uint8_t *p, uint8_t *buf); 128 | // backward compatibility functions 129 | inline uint8_t RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr) { return RecvData(bytes_rcvd, dataptr); }; 130 | inline uint8_t RcvData(uint8_t *outBuf) { return RecvData(outBuf); }; 131 | 132 | // USBDeviceConfig implementation 133 | virtual uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed); 134 | virtual uint8_t Release(); 135 | virtual uint8_t GetAddress() { return bAddress; }; 136 | 137 | void attachOnInit(void (*funcOnInit)(void)) { 138 | pFuncOnInit = funcOnInit; 139 | }; 140 | 141 | void attachOnRelease(void (*funcOnRelease)(void)) { 142 | pFuncOnRelease = funcOnRelease; 143 | }; 144 | private: 145 | void (*pFuncOnInit)(void) = nullptr; // Pointer to function called in onInit() 146 | void (*pFuncOnRelease)(void) = nullptr; // Pointer to function called in onRelease() 147 | }; 148 | 149 | #endif //_USBH_MIDI_H_ 150 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /examples/USB_MIDI_desc/USB_MIDI_desc.ino: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * USB-MIDI descriptor dump utility 4 | * modified from USB_desc.ino 5 | * 6 | * for use with USB Host Shield 2.0 from Circuitsathome.com 7 | * https://github.com/felis/USB_Host_Shield_2.0 8 | ******************************************************************************* 9 | */ 10 | 11 | #include 12 | 13 | USB Usb; 14 | //USBHub Hub1(&Usb); 15 | //USBHub Hub2(&Usb); 16 | //USBHub Hub3(&Usb); 17 | //USBHub Hub4(&Usb); 18 | //USBHub Hub5(&Usb); 19 | //USBHub Hub6(&Usb); 20 | //USBHub Hub7(&Usb); 21 | 22 | #define BUFFER_SIZE 512 23 | 24 | //MS Class-Specific Interface Descriptor Subtypes 25 | #define MSIF_MS_DESCRIPTOR_UNDEFINED (0x00) 26 | #define MSIF_MS_HEADER (0x01) 27 | #define MSIF_MIDI_IN_JACK (0x02) 28 | #define MSIF_MIDI_OUT_JACK (0x03) 29 | #define MSIF_ELEMENT (0x04) 30 | 31 | //MS Class-Specific Endpoint Descriptor Subtypes 32 | #define MSEP_DESCRIPTOR_UNDEFINED (0x00) 33 | #define MSEP_MS_GENERAL (0x01) 34 | 35 | //MS MIDI IN and OUT Jack types 36 | #define MSJT_JACK_TYPE_UNDEFINED (0x00) 37 | #define MSJT_EMBEDDED (0x01) 38 | #define MSJT_EXTERNAL (0x02) 39 | 40 | /* descriptor type */ 41 | #define USB_DESCRIPTOR_CS_INTERFACE (0x24) 42 | #define USB_DESCRIPTOR_CS_ENDPOINT (0x25) 43 | 44 | #define LOBYTE(x) ((char*)(&(x)))[0] 45 | #define HIBYTE(x) ((char*)(&(x)))[1] 46 | 47 | const char Gen_Error_str[] PROGMEM = "\r\nRequest error. Error code:\t"; 48 | const char Dev_Header_str[] PROGMEM = "\r\nDevice descriptor: "; 49 | const char Dev_Length_str[] PROGMEM = "\r\nDescriptor Length:\t"; 50 | const char Dev_Type_str[] PROGMEM = "\r\nDescriptor type:\t"; 51 | const char Dev_Version_str[] PROGMEM = "\r\nUSB version:\t\t"; 52 | const char Dev_Class_str[] PROGMEM = "\r\nDevice class:\t\t"; 53 | const char Dev_Subclass_str[] PROGMEM = "\r\nDevice Subclass:\t"; 54 | const char Dev_Protocol_str[] PROGMEM = "\r\nDevice Protocol:\t"; 55 | const char Dev_Pktsize_str[] PROGMEM = "\r\nMax.packet size:\t"; 56 | const char Dev_Vendor_str[] PROGMEM = "\r\nVendor ID:\t\t"; 57 | const char Dev_Product_str[] PROGMEM = "\r\nProduct ID:\t\t"; 58 | const char Dev_Revision_str[] PROGMEM = "\r\nRevision ID:\t\t"; 59 | const char Dev_Mfg_str[] PROGMEM = "\r\nMfg.string index:\t"; 60 | const char Dev_Prod_str[] PROGMEM = "\r\nProd.string index:\t"; 61 | const char Dev_Serial_str[] PROGMEM = "\r\nSerial number index:\t"; 62 | const char Dev_Nconf_str[] PROGMEM = "\r\nNumber of conf.:\t"; 63 | const char Conf_Trunc_str[] PROGMEM = "Total length truncated to 256 bytes"; 64 | const char Conf_Header_str[] PROGMEM = "\r\nConfiguration descriptor:"; 65 | const char Conf_Totlen_str[] PROGMEM = "\r\nTotal length:\t\t"; 66 | const char Conf_Nint_str[] PROGMEM = "\r\nNum.intf:\t\t"; 67 | const char Conf_Value_str[] PROGMEM = "\r\nConf.value:\t\t"; 68 | const char Conf_String_str[] PROGMEM = "\r\nConf.string:\t\t"; 69 | const char Conf_Attr_str[] PROGMEM = "\r\nAttr.:\t\t\t"; 70 | const char Conf_Pwr_str[] PROGMEM = "\r\nMax.pwr:\t\t"; 71 | const char Int_Header_str[] PROGMEM = "\r\n\r\nInterface descriptor:"; 72 | const char Int_Number_str[] PROGMEM = "\r\nIntf.number:\t\t"; 73 | const char Int_Alt_str[] PROGMEM = "\r\nAlt.:\t\t\t"; 74 | const char Int_Endpoints_str[] PROGMEM = "\r\nEndpoints:\t\t"; 75 | const char Int_Class_str[] PROGMEM = "\r\nIntf. Class:\t\t"; 76 | const char Int_Subclass_str[] PROGMEM = "\r\nIntf. Subclass:\t\t"; 77 | const char Int_Protocol_str[] PROGMEM = "\r\nIntf. Protocol:\t\t"; 78 | const char Int_String_str[] PROGMEM = "\r\nIntf.string:\t\t"; 79 | const char End_Header_str[] PROGMEM = "\r\n\r\nEndpoint descriptor:"; 80 | const char End_Address_str[] PROGMEM = "\r\nEndpoint address:\t"; 81 | const char End_Attr_str[] PROGMEM = "\r\nAttr.:\t\t\t"; 82 | const char End_Pktsize_str[] PROGMEM = "\r\nMax.pkt size:\t\t"; 83 | const char End_Interval_str[] PROGMEM = "\r\nPolling interval:\t"; 84 | const char End_Attr_control_str[] PROGMEM = "(Control)"; 85 | const char End_Attr_iso_str[] PROGMEM = "(Isochronous)"; 86 | const char End_Attr_bulk_str[] PROGMEM = "(Bulk)"; 87 | const char End_Attr_int_str[] PROGMEM = "(Interrupt)"; 88 | const char Unk_Header_str[] PROGMEM = "\r\nUnknown descriptor:"; 89 | const char Unk_Length_str[] PROGMEM = "\r\nLength:\t\t"; 90 | const char Unk_Type_str[] PROGMEM = "\r\nType:\t\t"; 91 | const char Unk_Contents_str[] PROGMEM = "\r\nContents:\t"; 92 | const char Int_AC_str[] PROGMEM = "\r\n\r\n<<>>"; 93 | const char Int_AS_str[] PROGMEM = "\r\n\r\n<<>>"; 94 | const char Int_MS_str[] PROGMEM = "\r\n\r\n<<>>"; 95 | const char Int_CS_Header_str[] PROGMEM = "\r\n\r\nMS Interface descriptor"; 96 | const char End_CS_Header_str[] PROGMEM = "\r\n\r\nMS Endpoint descriptor"; 97 | const char Int_CS_Type_str[] PROGMEM = "\r\nUSB_DESCRIPTOR_CS_INTERFACE :\t"; 98 | const char End_CS_Type_str[] PROGMEM = "\r\nUSB_DESCRIPTOR_CS_ENDPOINT :\t"; 99 | const char CS_MS_Version_str[] PROGMEM = "\r\nMIDIStreaming SubClass Specification Release number: "; 100 | const char CS_MS_Length_str[] PROGMEM = "\r\nwTotalLength:\t\t"; 101 | const char CS_MS_Subtype_str[] PROGMEM = "\r\nDescriptorSubtype: "; 102 | const char CS_MS_Jacktype_str[] PROGMEM = "\r\nJackType:\t"; 103 | const char CS_MIDI_JACKID_str[] PROGMEM = "\r\nJackID:\t\t"; 104 | const char CS_MIDI_NrInputPins_str[] PROGMEM = "\r\nNrInputPins:\t"; 105 | const char CS_Subtype_UNDEF_str[] PROGMEM = "Undefined"; 106 | const char CS_Subtype_MS_HEADER_str[] PROGMEM = "MS_HEADER"; 107 | const char CS_Subtype_MIDI_IN_JACK_str[] PROGMEM = "MIDI_IN_JACK"; 108 | const char CS_Subtype_MIDI_OUT_JACK_str[] PROGMEM = "MIDI_OUT_JACK"; 109 | const char CS_Subtype_ELEMENT_str[] PROGMEM = "ELEMENT"; 110 | const char CS_Subtype_MIDI_JACK_TYPE_UNDEFINED_str[] PROGMEM = "(Undefined)"; 111 | const char CS_Subtype_MIDI_JACK_TYPE_EMBEDDED_str[] PROGMEM = "(Embedded)"; 112 | const char CS_Subtype_MIDI_JACK_TYPE_EXTERNAL_str[] PROGMEM = "(External)"; 113 | const char CS_Subtype_MS_GENERAL_str[] PROGMEM = "MS_GENERAL"; 114 | const char CS_MIDI_NrEmbJacks_str[] PROGMEM = "\r\nbNumEmbMIDIJack: "; 115 | const char CRLF_str[] PROGMEM = "\r\n"; 116 | 117 | typedef struct { 118 | uint8_t bLength; // Length of this descriptor. 119 | uint8_t bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE). 120 | uint8_t bDescriptorSubtype; // INTERFACE descriptor sub type 121 | uint16_t bcdMSC; // 122 | uint16_t wTotalLength; // 123 | } __attribute__((packed)) USB_MS_INTERFACE_DESCRIPTOR; 124 | 125 | typedef struct { 126 | uint8_t bLength; // Length of this descriptor. 127 | uint8_t bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE). 128 | uint8_t bDescriptorSubtype; // INTERFACE descriptor sub type 129 | uint8_t bJackType; //EMBEDDED or EXTERNAL 130 | uint8_t bJackID; //Constant uniquely identifying the MIDI IN Jack within the USB-MIDI function 131 | uint8_t iJack; //Index of a string descriptor, describing the MIDI IN Jack. 132 | } __attribute__((packed)) USB_MS_INTERFACE_MIDI_IN_JACK_DESCRIPTOR; 133 | 134 | typedef struct { 135 | uint8_t bLength; // Length of this descriptor. 136 | uint8_t bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE). 137 | uint8_t bDescriptorSubtype; // INTERFACE descriptor sub type 138 | uint8_t bJackType; //EMBEDDED or EXTERNAL 139 | uint8_t bJackID; //Constant uniquely identifying the MIDI IN Jack within the USB-MIDI function 140 | uint8_t bNrInputPins; // 141 | uint8_t *baSources; // 142 | } __attribute__((packed)) USB_MS_INTERFACE_MIDI_OUT_JACK_DESCRIPTOR; 143 | 144 | typedef struct { 145 | uint8_t bLength; // Length of this descriptor. 146 | uint8_t bDescriptorType; // ENDPOINT descriptor type (USB_DESCRIPTOR_ENDPOINT). 147 | uint8_t bDescriptorSubtype; // ENDPOINT descriptor sub type 148 | uint8_t bNumEmbMIDIJack; // Number of embedded MIDI IN Jacks. 149 | uint8_t *BaAssocJackIDs; // ID of the Embedded MIDI IN Jack. 150 | } __attribute__((packed)) USB_MS_ENDPOINT_DESCRIPTOR; 151 | 152 | void PrintAllAddresses(UsbDevice *pdev) 153 | { 154 | UsbDeviceAddress adr; 155 | adr.devAddress = pdev->address.devAddress; 156 | Serial.print("\r\nAddr:"); 157 | Serial.print(adr.devAddress, HEX); 158 | Serial.print("("); 159 | Serial.print(adr.bmHub, HEX); 160 | Serial.print("."); 161 | Serial.print(adr.bmParent, HEX); 162 | Serial.print("."); 163 | Serial.print(adr.bmAddress, HEX); 164 | Serial.println(")"); 165 | } 166 | 167 | void PrintAddress(uint8_t addr) 168 | { 169 | UsbDeviceAddress adr; 170 | adr.devAddress = addr; 171 | Serial.print("\r\nADDR:\t"); 172 | Serial.println(adr.devAddress, HEX); 173 | Serial.print("DEV:\t"); 174 | Serial.println(adr.bmAddress, HEX); 175 | Serial.print("PRNT:\t"); 176 | Serial.println(adr.bmParent, HEX); 177 | Serial.print("HUB:\t"); 178 | Serial.println(adr.bmHub, HEX); 179 | } 180 | 181 | void setup() 182 | { 183 | Serial.begin( 115200 ); 184 | #if !defined(__MIPSEL__) 185 | while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection 186 | #endif 187 | Serial.println("Start"); 188 | 189 | if (Usb.Init() == -1) 190 | Serial.println("OSC did not start."); 191 | 192 | delay( 200 ); 193 | } 194 | 195 | uint8_t getdevdescr( uint8_t addr, uint8_t &num_conf ); 196 | 197 | void PrintDescriptors(uint8_t addr) 198 | { 199 | uint8_t rcode = 0; 200 | uint8_t num_conf = 0; 201 | 202 | rcode = getdevdescr( (uint8_t)addr, num_conf ); 203 | if ( rcode ) 204 | { 205 | printProgStr(Gen_Error_str); 206 | print_hex( rcode, 8 ); 207 | } 208 | Serial.print("\r\n"); 209 | 210 | for (int i = 0; i < num_conf; i++) 211 | { 212 | rcode = getconfdescr( addr, i ); // get configuration descriptor 213 | if ( rcode ) 214 | { 215 | printProgStr(Gen_Error_str); 216 | print_hex(rcode, 8); 217 | } 218 | Serial.println("\r\n"); 219 | } 220 | } 221 | 222 | void PrintAllDescriptors(UsbDevice *pdev) 223 | { 224 | Serial.println("\r\n"); 225 | print_hex(pdev->address.devAddress, 8); 226 | Serial.println("\r\n--"); 227 | getallstrdescr(pdev->address.devAddress); 228 | PrintDescriptors( pdev->address.devAddress ); 229 | } 230 | 231 | void loop() 232 | { 233 | Usb.Task(); 234 | 235 | if ( Usb.getUsbTaskState() == USB_STATE_RUNNING ) 236 | { 237 | Usb.ForEachUsbDevice(&PrintAllDescriptors); 238 | Usb.ForEachUsbDevice(&PrintAllAddresses); 239 | 240 | while ( 1 ) { // stop 241 | #ifdef ESP8266 242 | yield(); // needed in order to reset the watchdog timer on the ESP8266 243 | #endif 244 | } 245 | } 246 | } 247 | 248 | uint8_t getdevdescr( uint8_t addr, uint8_t &num_conf ) 249 | { 250 | USB_DEVICE_DESCRIPTOR buf; 251 | uint8_t rcode; 252 | rcode = Usb.getDevDescr( addr, 0, 0x12, ( uint8_t *)&buf ); 253 | if ( rcode ) { 254 | return ( rcode ); 255 | } 256 | printProgStr(Dev_Header_str); 257 | printProgStr(Dev_Length_str); 258 | print_hex( buf.bLength, 8 ); 259 | printProgStr(Dev_Type_str); 260 | print_hex( buf.bDescriptorType, 8 ); 261 | printProgStr(Dev_Version_str); 262 | print_hex( buf.bcdUSB, 16 ); 263 | printProgStr(Dev_Class_str); 264 | print_hex( buf.bDeviceClass, 8 ); 265 | printProgStr(Dev_Subclass_str); 266 | print_hex( buf.bDeviceSubClass, 8 ); 267 | printProgStr(Dev_Protocol_str); 268 | print_hex( buf.bDeviceProtocol, 8 ); 269 | printProgStr(Dev_Pktsize_str); 270 | print_hex( buf.bMaxPacketSize0, 8 ); 271 | printProgStr(Dev_Vendor_str); 272 | print_hex( buf.idVendor, 16 ); 273 | printProgStr(Dev_Product_str); 274 | print_hex( buf.idProduct, 16 ); 275 | printProgStr(Dev_Revision_str); 276 | print_hex( buf.bcdDevice, 16 ); 277 | printProgStr(Dev_Mfg_str); 278 | print_hex( buf.iManufacturer, 8 ); 279 | printProgStr(Dev_Prod_str); 280 | print_hex( buf.iProduct, 8 ); 281 | printProgStr(Dev_Serial_str); 282 | print_hex( buf.iSerialNumber, 8 ); 283 | printProgStr(Dev_Nconf_str); 284 | print_hex( buf.bNumConfigurations, 8 ); 285 | num_conf = buf.bNumConfigurations; 286 | return ( 0 ); 287 | } 288 | 289 | void printhubdescr(uint8_t *descrptr) 290 | { 291 | HubDescriptor *pHub = (HubDescriptor*) descrptr; 292 | uint8_t len = *((uint8_t*)descrptr); 293 | 294 | printProgStr(PSTR("\r\n\r\nHub Descriptor:\r\n")); 295 | printProgStr(PSTR("bDescLength:\t\t")); 296 | Serial.println(pHub->bDescLength, HEX); 297 | 298 | printProgStr(PSTR("bDescriptorType:\t")); 299 | Serial.println(pHub->bDescriptorType, HEX); 300 | 301 | printProgStr(PSTR("bNbrPorts:\t\t")); 302 | Serial.println(pHub->bNbrPorts, HEX); 303 | 304 | printProgStr(PSTR("LogPwrSwitchMode:\t")); 305 | Serial.println(pHub->LogPwrSwitchMode, BIN); 306 | 307 | printProgStr(PSTR("CompoundDevice:\t\t")); 308 | Serial.println(pHub->CompoundDevice, BIN); 309 | 310 | printProgStr(PSTR("OverCurrentProtectMode:\t")); 311 | Serial.println(pHub->OverCurrentProtectMode, BIN); 312 | 313 | printProgStr(PSTR("TTThinkTime:\t\t")); 314 | Serial.println(pHub->TTThinkTime, BIN); 315 | 316 | printProgStr(PSTR("PortIndicatorsSupported:")); 317 | Serial.println(pHub->PortIndicatorsSupported, BIN); 318 | 319 | printProgStr(PSTR("Reserved:\t\t")); 320 | Serial.println(pHub->Reserved, HEX); 321 | 322 | printProgStr(PSTR("bPwrOn2PwrGood:\t\t")); 323 | Serial.println(pHub->bPwrOn2PwrGood, HEX); 324 | 325 | printProgStr(PSTR("bHubContrCurrent:\t")); 326 | Serial.println(pHub->bHubContrCurrent, HEX); 327 | 328 | for (uint8_t i = 7; i < len; i++) 329 | print_hex(descrptr[i], 8); 330 | } 331 | 332 | uint8_t getconfdescr( uint8_t addr, uint8_t conf ) 333 | { 334 | uint8_t buf[ BUFFER_SIZE ]; 335 | uint8_t* buf_ptr = buf; 336 | uint8_t rcode; 337 | uint8_t descr_length; 338 | uint8_t descr_type; 339 | uint16_t total_length; 340 | bool isMidiStreaming = false; 341 | rcode = Usb.getConfDescr( addr, 0, 4, conf, buf ); //get total length 342 | LOBYTE( total_length ) = buf[ 2 ]; 343 | HIBYTE( total_length ) = buf[ 3 ]; 344 | if ( total_length > BUFFER_SIZE ) { //check if total length is larger than buffer 345 | printProgStr(Conf_Trunc_str); 346 | total_length = BUFFER_SIZE; 347 | } 348 | rcode = Usb.getConfDescr( addr, 0, total_length, conf, buf ); //get the whole descriptor 349 | while ( buf_ptr < buf + total_length ) { //parsing descriptors 350 | descr_length = *( buf_ptr ); 351 | descr_type = *( buf_ptr + 1 ); 352 | switch ( descr_type ) { 353 | case ( USB_DESCRIPTOR_CONFIGURATION ): 354 | printconfdescr( buf_ptr ); 355 | break; 356 | case ( USB_DESCRIPTOR_INTERFACE ): 357 | isMidiStreaming = printintfdescr( buf_ptr ); 358 | break; 359 | case ( USB_DESCRIPTOR_ENDPOINT ): 360 | printepdescr( buf_ptr ); 361 | break; 362 | case 0x29: 363 | printhubdescr( buf_ptr ); 364 | break; 365 | case ( USB_DESCRIPTOR_CS_INTERFACE ): 366 | if ( isMidiStreaming ) { 367 | printmsifdescr( buf_ptr ); 368 | } else { 369 | printunkdescr( buf_ptr ); 370 | } 371 | break; 372 | case ( USB_DESCRIPTOR_CS_ENDPOINT ): 373 | if ( isMidiStreaming ) { 374 | printmsepdescr( buf_ptr ); 375 | } else { 376 | printunkdescr( buf_ptr ); 377 | } 378 | break; 379 | default: 380 | printunkdescr( buf_ptr ); 381 | break; 382 | }//switch( descr_type 383 | buf_ptr = ( buf_ptr + descr_length ); //advance buffer pointer 384 | }//while( buf_ptr <=... 385 | return ( rcode ); 386 | } 387 | 388 | // function to get all string descriptors 389 | uint8_t getallstrdescr(uint8_t addr) 390 | { 391 | uint8_t rcode = 0; 392 | Usb.Task(); 393 | if ( Usb.getUsbTaskState() >= USB_STATE_CONFIGURING ) { // state configuring or higher 394 | USB_DEVICE_DESCRIPTOR buf; 395 | rcode = Usb.getDevDescr( addr, 0, DEV_DESCR_LEN, ( uint8_t *)&buf ); 396 | if ( rcode ) { 397 | return ( rcode ); 398 | } 399 | Serial.println("String Descriptors:"); 400 | if ( buf.iManufacturer > 0 ) { 401 | Serial.print("Manufacturer:\t\t"); 402 | rcode = getstrdescr( addr, buf.iManufacturer ); // get manufacturer string 403 | if ( rcode ) { 404 | Serial.println( rcode, HEX ); 405 | } 406 | Serial.print("\r\n"); 407 | } 408 | if ( buf.iProduct > 0 ) { 409 | Serial.print("Product:\t\t"); 410 | rcode = getstrdescr( addr, buf.iProduct ); // get product string 411 | if ( rcode ) { 412 | Serial.println( rcode, HEX ); 413 | } 414 | Serial.print("\r\n"); 415 | } 416 | if ( buf.iSerialNumber > 0 ) { 417 | Serial.print("Serial:\t\t\t"); 418 | rcode = getstrdescr( addr, buf.iSerialNumber ); // get serial string 419 | if ( rcode ) { 420 | Serial.println( rcode, HEX ); 421 | } 422 | Serial.print("\r\n"); 423 | } 424 | } 425 | return rcode; 426 | } 427 | 428 | // function to get single string description 429 | uint8_t getstrdescr( uint8_t addr, uint8_t idx ) 430 | { 431 | uint8_t buf[ 256 ]; 432 | uint8_t rcode; 433 | uint8_t length; 434 | uint8_t i; 435 | uint16_t langid; 436 | rcode = Usb.getStrDescr( addr, 0, 1, 0, 0, buf ); //get language table length 437 | if ( rcode ) { 438 | Serial.println("Error retrieving LangID table length"); 439 | return ( rcode ); 440 | } 441 | length = buf[ 0 ]; //length is the first byte 442 | rcode = Usb.getStrDescr( addr, 0, length, 0, 0, buf ); //get language table 443 | if ( rcode ) { 444 | Serial.print("Error retrieving LangID table "); 445 | return ( rcode ); 446 | } 447 | langid = (buf[3] << 8) | buf[2]; 448 | rcode = Usb.getStrDescr( addr, 0, 1, idx, langid, buf ); 449 | if ( rcode ) { 450 | Serial.print("Error retrieving string length "); 451 | return ( rcode ); 452 | } 453 | length = buf[ 0 ]; 454 | rcode = Usb.getStrDescr( addr, 0, length, idx, langid, buf ); 455 | if ( rcode ) { 456 | Serial.print("Error retrieving string "); 457 | return ( rcode ); 458 | } 459 | for ( i = 2; i < length; i += 2 ) { //string is UTF-16LE encoded 460 | Serial.print((char) buf[i]); 461 | } 462 | return ( rcode ); 463 | } 464 | 465 | /* prints hex numbers with leading zeroes */ 466 | // copyright, Peter H Anderson, Baltimore, MD, Nov, '07 467 | // source: http://www.phanderson.com/arduino/arduino_display.html 468 | void print_hex(int v, int num_places) 469 | { 470 | int mask = 0, n, num_nibbles, digit; 471 | 472 | for (n = 1; n <= num_places; n++) { 473 | mask = (mask << 1) | 0x0001; 474 | } 475 | v = v & mask; // truncate v to specified number of places 476 | 477 | num_nibbles = num_places / 4; 478 | if ((num_places % 4) != 0) { 479 | ++num_nibbles; 480 | } 481 | do { 482 | digit = ((v >> (num_nibbles - 1) * 4)) & 0x0f; 483 | Serial.print(digit, HEX); 484 | } 485 | while (--num_nibbles); 486 | } 487 | 488 | /* function to print configuration descriptor */ 489 | void printconfdescr( uint8_t* descr_ptr ) 490 | { 491 | USB_CONFIGURATION_DESCRIPTOR* conf_ptr = ( USB_CONFIGURATION_DESCRIPTOR* )descr_ptr; 492 | printProgStr(Conf_Header_str); 493 | printProgStr(Conf_Totlen_str); 494 | print_hex( conf_ptr->wTotalLength, 16 ); 495 | printProgStr(Conf_Nint_str); 496 | print_hex( conf_ptr->bNumInterfaces, 8 ); 497 | printProgStr(Conf_Value_str); 498 | print_hex( conf_ptr->bConfigurationValue, 8 ); 499 | printProgStr(Conf_String_str); 500 | print_hex( conf_ptr->iConfiguration, 8 ); 501 | printProgStr(Conf_Attr_str); 502 | print_hex( conf_ptr->bmAttributes, 8 ); 503 | printProgStr(Conf_Pwr_str); 504 | print_hex( conf_ptr->bMaxPower, 8 ); 505 | return; 506 | } 507 | 508 | /* function to print interface descriptor */ 509 | bool printintfdescr( uint8_t* descr_ptr ) 510 | { 511 | bool r = false; 512 | USB_INTERFACE_DESCRIPTOR* intf_ptr = ( USB_INTERFACE_DESCRIPTOR* )descr_ptr; 513 | printProgStr(Int_Header_str); 514 | printProgStr(Int_Number_str); 515 | print_hex( intf_ptr->bInterfaceNumber, 8 ); 516 | printProgStr(Int_Alt_str); 517 | print_hex( intf_ptr->bAlternateSetting, 8 ); 518 | printProgStr(Int_Endpoints_str); 519 | print_hex( intf_ptr->bNumEndpoints, 8 ); 520 | printProgStr(Int_Class_str); 521 | print_hex( intf_ptr->bInterfaceClass, 8 ); 522 | printProgStr(Int_Subclass_str); 523 | print_hex( intf_ptr->bInterfaceSubClass, 8 ); 524 | printProgStr(Int_Protocol_str); 525 | print_hex( intf_ptr->bInterfaceProtocol, 8 ); 526 | printProgStr(Int_String_str); 527 | print_hex( intf_ptr->iInterface, 8 ); 528 | 529 | //Audio Class 530 | if (intf_ptr->bInterfaceClass == 1 ) { 531 | switch ( intf_ptr->bInterfaceSubClass ) { 532 | case 1 : //Audio Control 533 | printProgStr(Int_AC_str); 534 | break; 535 | case 2 : //Audio Streaming 536 | printProgStr(Int_AS_str); 537 | break; 538 | case 3 : //Midi Streaming 539 | printProgStr(Int_MS_str); 540 | r = true; 541 | break; 542 | } 543 | } 544 | return r; 545 | } 546 | 547 | /* function to print endpoint descriptor */ 548 | void printepdescr( uint8_t* descr_ptr ) 549 | { 550 | USB_ENDPOINT_DESCRIPTOR* ep_ptr = ( USB_ENDPOINT_DESCRIPTOR* )descr_ptr; 551 | printProgStr(End_Header_str); 552 | printProgStr(End_Address_str); 553 | print_hex( ep_ptr->bEndpointAddress, 8 ); 554 | printProgStr(End_Attr_str); 555 | print_hex( ep_ptr->bmAttributes, 8 ); 556 | switch(ep_ptr->bmAttributes & 3){ 557 | case USB_TRANSFER_TYPE_CONTROL: 558 | printProgStr(End_Attr_control_str); 559 | break; 560 | case USB_TRANSFER_TYPE_ISOCHRONOUS: 561 | printProgStr(End_Attr_iso_str); 562 | break; 563 | case USB_TRANSFER_TYPE_BULK: 564 | printProgStr(End_Attr_bulk_str); 565 | break; 566 | case USB_TRANSFER_TYPE_INTERRUPT: 567 | printProgStr(End_Attr_int_str); 568 | break; 569 | } 570 | printProgStr(End_Pktsize_str); 571 | print_hex( ep_ptr->wMaxPacketSize, 16 ); 572 | printProgStr(End_Interval_str); 573 | print_hex( ep_ptr->bInterval, 8 ); 574 | 575 | return; 576 | } 577 | 578 | /* function to print unknown descriptor */ 579 | void printunkdescr( uint8_t* descr_ptr ) 580 | { 581 | uint8_t length = *descr_ptr - 2; 582 | uint8_t i; 583 | printProgStr(Unk_Header_str); 584 | printProgStr(Unk_Length_str); 585 | print_hex( *descr_ptr, 8 ); 586 | printProgStr(Unk_Type_str); 587 | print_hex( *(descr_ptr + 1 ), 8 ); 588 | printProgStr(Unk_Contents_str); 589 | descr_ptr += 2; 590 | for ( i = 0; i < length; i++ ) { 591 | print_hex( *descr_ptr, 8 ); 592 | descr_ptr++; 593 | } 594 | } 595 | 596 | void printDumpHex(uint8_t* descr_ptr, uint8_t length) 597 | { 598 | printProgStr(CRLF_str); 599 | for ( int i = 0; i < length; i++ ) { 600 | print_hex( *descr_ptr, 8 ); 601 | descr_ptr++; 602 | } 603 | //printProgStr(CRLF_str); 604 | } 605 | 606 | /* function to print USB_DESCRIPTOR_CS_INTERFACE descriptor */ 607 | void printmsifdescr( uint8_t* descr_ptr ) 608 | { 609 | USB_MS_INTERFACE_DESCRIPTOR* if_ptr = ( USB_MS_INTERFACE_DESCRIPTOR* )descr_ptr; 610 | printProgStr(Int_CS_Header_str); 611 | printDumpHex(descr_ptr, if_ptr->bLength); 612 | printProgStr(CS_MS_Subtype_str); 613 | print_hex( if_ptr->bDescriptorSubtype, 8 ); 614 | printProgStr(Int_CS_Type_str); 615 | 616 | if ( if_ptr->bDescriptorSubtype == MSIF_MS_HEADER) { //MS_HEADER 617 | printProgStr(CS_Subtype_MS_HEADER_str); 618 | printProgStr(CS_MS_Version_str); 619 | print_hex( if_ptr->bcdMSC, 16 ); 620 | printProgStr(CS_MS_Length_str); 621 | print_hex( if_ptr->wTotalLength, 16 ); 622 | } else if ( if_ptr->bDescriptorSubtype == MSIF_MIDI_IN_JACK) { //MIDI_IN_JACK 623 | USB_MS_INTERFACE_MIDI_IN_JACK_DESCRIPTOR* if_inptr = (USB_MS_INTERFACE_MIDI_IN_JACK_DESCRIPTOR*)descr_ptr; 624 | printProgStr(CS_Subtype_MIDI_IN_JACK_str); 625 | printmsjacktype(if_inptr->bJackType); 626 | printProgStr(CS_MIDI_JACKID_str); 627 | print_hex( if_inptr->bJackID, 8 ); 628 | } else if ( if_ptr->bDescriptorSubtype == MSIF_MIDI_OUT_JACK) { //MIDI_OUT_JACK 629 | USB_MS_INTERFACE_MIDI_OUT_JACK_DESCRIPTOR* if_outptr = (USB_MS_INTERFACE_MIDI_OUT_JACK_DESCRIPTOR*)descr_ptr; 630 | printProgStr(CS_Subtype_MIDI_OUT_JACK_str); 631 | printmsjacktype(if_outptr->bJackType); 632 | printProgStr(CS_MIDI_JACKID_str); 633 | print_hex( if_outptr->bJackID, 8 ); 634 | printProgStr(CS_MIDI_NrInputPins_str); 635 | print_hex( if_outptr->bNrInputPins, 8 ); 636 | printDumpHex(descr_ptr + 6, if_outptr->bNrInputPins * 2 + 1); 637 | } else if ( if_ptr->bDescriptorSubtype == MSIF_ELEMENT) { //ELEMENT 638 | printProgStr(CS_Subtype_ELEMENT_str); 639 | } else { 640 | printProgStr(CS_Subtype_UNDEF_str); 641 | } 642 | } 643 | 644 | /* function to print MIDI IN/OUT Jack Descriptor JackType */ 645 | void printmsjacktype( uint8_t bJackType ) 646 | { 647 | switch (bJackType) { 648 | case MSJT_JACK_TYPE_UNDEFINED: 649 | printProgStr(CS_Subtype_MIDI_JACK_TYPE_UNDEFINED_str); 650 | break; 651 | case MSJT_EMBEDDED: 652 | printProgStr(CS_Subtype_MIDI_JACK_TYPE_EMBEDDED_str); 653 | break; 654 | case MSJT_EXTERNAL: 655 | printProgStr(CS_Subtype_MIDI_JACK_TYPE_EXTERNAL_str); 656 | break; 657 | default: 658 | printProgStr(CRLF_str); 659 | break; 660 | } 661 | printProgStr(CS_MS_Jacktype_str); 662 | print_hex( bJackType, 8 ); 663 | } 664 | 665 | /* function to print CS_MS_ENDPOINT descriptor */ 666 | void printmsepdescr( uint8_t* descr_ptr ) 667 | { 668 | USB_MS_ENDPOINT_DESCRIPTOR* ep_ptr = ( USB_MS_ENDPOINT_DESCRIPTOR* )descr_ptr; 669 | printProgStr(End_CS_Header_str); 670 | printDumpHex(descr_ptr, ep_ptr->bLength); 671 | switch ( ep_ptr->bDescriptorSubtype ) { 672 | case 1: //MS_GENERAL 673 | printProgStr(End_CS_Type_str); 674 | printProgStr(CS_Subtype_MS_GENERAL_str); 675 | printProgStr(CS_MIDI_NrEmbJacks_str); 676 | print_hex( ep_ptr->bNumEmbMIDIJack, 8 ); 677 | 678 | printDumpHex(descr_ptr + 4, ep_ptr->bNumEmbMIDIJack); 679 | break; 680 | default: 681 | printunkdescr( descr_ptr ); 682 | break; 683 | } 684 | } 685 | 686 | /* Print a string from Program Memory directly to save RAM */ 687 | void printProgStr(const char* str) 688 | { 689 | char c; 690 | if (!str) return; 691 | while ((c = pgm_read_byte(str++))) 692 | Serial.print(c); 693 | } 694 | -------------------------------------------------------------------------------- /usbh_midi.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ******************************************************************************* 3 | * USB-MIDI class driver for USB Host Shield 2.0 Library 4 | * Copyright (c) 2012-2022 Yuuichi Akagawa 5 | * 6 | * Idea from LPK25 USB-MIDI to Serial MIDI converter 7 | * by Collin Cunningham - makezine.com, narbotic.com 8 | * 9 | * for use with USB Host Shield 2.0 from Circuitsathome.com 10 | * https://github.com/felis/USB_Host_Shield_2.0 11 | ******************************************************************************* 12 | * This program 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 2 of the License, or 15 | * (at your option) any later version. 16 | * 17 | * This program 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 this program. If not, see 24 | ******************************************************************************* 25 | */ 26 | 27 | #include "usbh_midi.h" 28 | // To enable serial debugging see "settings.h" 29 | //#define EXTRADEBUG // Uncomment to get even more debugging data 30 | 31 | ////////////////////////// 32 | // MIDI MESAGES 33 | // midi.org/techspecs/ 34 | ////////////////////////// 35 | // STATUS BYTES 36 | // 0x8n == noteOff 37 | // 0x9n == noteOn 38 | // 0xAn == afterTouch 39 | // 0xBn == controlChange 40 | // n == Channel(0x0-0xf) 41 | ////////////////////////// 42 | //DATA BYTE 1 43 | // note# == (0-127) 44 | // or 45 | // control# == (0-119) 46 | ////////////////////////// 47 | // DATA BYTE 2 48 | // velocity == (0-127) 49 | // or 50 | // controlVal == (0-127) 51 | /////////////////////////////////////////////////////////////////////////////// 52 | // USB-MIDI Event Packets 53 | // usb.org - Universal Serial Bus Device Class Definition for MIDI Devices 1.0 54 | /////////////////////////////////////////////////////////////////////////////// 55 | //+-------------+-------------+-------------+-------------+ 56 | //| Byte 0 | Byte 1 | Byte 2 | Byte 3 | 57 | //+------+------+-------------+-------------+-------------+ 58 | //|Cable | Code | | | | 59 | //|Number|Index | MIDI_0 | MIDI_1 | MIDI_2 | 60 | //| |Number| | | | 61 | //|(4bit)|(4bit)| (8bit) | (8bit) | (8bit) | 62 | //+------+------+-------------+-------------+-------------+ 63 | // CN == 0x0-0xf 64 | //+-----+-----------+------------------------------------------------------------------- 65 | //| CIN |MIDI_x size|Description 66 | //+-----+-----------+------------------------------------------------------------------- 67 | //| 0x0 | 1, 2 or 3 |Miscellaneous function codes. Reserved for future extensions. 68 | //| 0x1 | 1, 2 or 3 |Cable events. Reserved for future expansion. 69 | //| 0x2 | 2 |Two-byte System Common messages like MTC, SongSelect, etc. 70 | //| 0x3 | 3 |Three-byte System Common messages like SPP, etc. 71 | //| 0x4 | 3 |SysEx starts or continues 72 | //| 0x5 | 1 |Single-byte System Common Message or SysEx ends with following single byte. 73 | //| 0x6 | 2 |SysEx ends with following two bytes. 74 | //| 0x7 | 3 |SysEx ends with following three bytes. 75 | //| 0x8 | 3 |Note-off 76 | //| 0x9 | 3 |Note-on 77 | //| 0xA | 3 |Poly-KeyPress 78 | //| 0xB | 3 |Control Change 79 | //| 0xC | 2 |Program Change 80 | //| 0xD | 2 |Channel Pressure 81 | //| 0xE | 3 |PitchBend Change 82 | //| 0xF | 1 |Single Byte 83 | //+-----+-----------+------------------------------------------------------------------- 84 | 85 | USBH_MIDI::USBH_MIDI(USB *p) : 86 | pUsb(p), 87 | bAddress(0), 88 | bPollEnable(false), 89 | readPtr(0) { 90 | // initialize endpoint data structures 91 | for(uint8_t i=0; iRegisterDeviceClass(this); 99 | } 100 | } 101 | 102 | /* Connection initialization of an MIDI Device */ 103 | uint8_t USBH_MIDI::Init(uint8_t parent, uint8_t port, bool lowspeed) 104 | { 105 | uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; 106 | USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); 107 | uint8_t rcode; 108 | UsbDevice *p = NULL; 109 | EpInfo *oldep_ptr = NULL; 110 | uint8_t num_of_conf; // number of configurations 111 | uint8_t bConfNum = 0; // configuration number 112 | uint8_t bNumEP = 1; // total number of EP in the configuration 113 | 114 | USBTRACE("\rMIDI Init\r\n"); 115 | #ifdef DEBUG_USB_HOST 116 | Notify(PSTR("USBH_MIDI version "), 0x80), D_PrintHex((uint8_t) (USBH_MIDI_VERSION / 10000), 0x80), D_PrintHex((uint8_t) (USBH_MIDI_VERSION / 100 % 100), 0x80), D_PrintHex((uint8_t) (USBH_MIDI_VERSION % 100), 0x80), Notify(PSTR("\r\n"), 0x80); 117 | #endif 118 | 119 | //for reconnect 120 | for(uint8_t i=epDataInIndex; i<=epDataOutIndex; i++) { 121 | epInfo[i].bmSndToggle = 0; 122 | epInfo[i].bmRcvToggle = 0; 123 | // If you want to retry if you get a NAK response when sending, enable the following: 124 | // epInfo[i].bmNakPower = (i==epDataOutIndex) ? 10 : USB_NAK_NOWAIT; 125 | } 126 | 127 | // get memory address of USB device address pool 128 | AddressPool &addrPool = pUsb->GetAddressPool(); 129 | 130 | // check if address has already been assigned to an instance 131 | if (bAddress) { 132 | return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; 133 | } 134 | // Get pointer to pseudo device with address 0 assigned 135 | p = addrPool.GetUsbDevicePtr(bAddress); 136 | if (!p) { 137 | return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; 138 | } 139 | if (!p->epinfo) { 140 | return USB_ERROR_EPINFO_IS_NULL; 141 | } 142 | 143 | // Save old pointer to EP_RECORD of address 0 144 | oldep_ptr = p->epinfo; 145 | 146 | // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence 147 | p->epinfo = epInfo; 148 | p->lowspeed = lowspeed; 149 | 150 | // First Device Descriptor Request (Initially first 8 bytes) 151 | // https://techcommunity.microsoft.com/t5/microsoft-usb-blog/how-does-usb-stack-enumerate-a-device/ba-p/270685#_First_Device_Descriptor 152 | rcode = pUsb->getDevDescr( 0, 0, 8, (uint8_t*)buf ); 153 | 154 | // Restore p->epinfo 155 | p->epinfo = oldep_ptr; 156 | 157 | if( rcode ){ 158 | goto FailGetDevDescr; 159 | } 160 | 161 | // Allocate new address according to device class 162 | bAddress = addrPool.AllocAddress(parent, false, port); 163 | if (!bAddress) { 164 | return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; 165 | } 166 | 167 | // Extract Max Packet Size from device descriptor 168 | epInfo[0].maxPktSize = udd->bMaxPacketSize0; 169 | 170 | // Assign new address to the device 171 | rcode = pUsb->setAddr( 0, 0, bAddress ); 172 | if (rcode) { 173 | p->lowspeed = false; 174 | addrPool.FreeAddress(bAddress); 175 | bAddress = 0; 176 | return rcode; 177 | }//if (rcode... 178 | USBTRACE2("Addr:", bAddress); 179 | 180 | p->lowspeed = false; 181 | 182 | //get pointer to assigned address record 183 | p = addrPool.GetUsbDevicePtr(bAddress); 184 | if (!p) { 185 | return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; 186 | } 187 | p->lowspeed = lowspeed; 188 | 189 | // Second Device Descriptor Request (Full) 190 | rcode = pUsb->getDevDescr( bAddress, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf ); 191 | if( rcode ){ 192 | goto FailGetDevDescr; 193 | } 194 | vid = udd->idVendor; 195 | pid = udd->idProduct; 196 | num_of_conf = udd->bNumConfigurations; 197 | 198 | // Assign epInfo to epinfo pointer 199 | rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); 200 | if (rcode) { 201 | USBTRACE("setEpInfoEntry failed"); 202 | goto FailSetDevTblEntry; 203 | } 204 | 205 | USBTRACE("VID:"), D_PrintHex(vid, 0x80); 206 | USBTRACE(" PID:"), D_PrintHex(pid, 0x80); 207 | USBTRACE2(" #Conf:", num_of_conf); 208 | 209 | //Setup for well known vendor/device specific configuration 210 | bTransferTypeMask = bmUSB_TRANSFER_TYPE; 211 | setupDeviceSpecific(); 212 | 213 | // STEP1: Check if attached device is a MIDI device and fill endpoint data structure 214 | USBTRACE("\r\nSTEP1: MIDI Start\r\n"); 215 | for(uint8_t i = 0; i < num_of_conf; i++) { 216 | MidiDescParser midiDescParser(this, true); // Check for MIDI device 217 | rcode = pUsb->getConfDescr(bAddress, 0, i, &midiDescParser); 218 | if(rcode) // Check error code 219 | goto FailGetConfDescr; 220 | bNumEP += midiDescParser.getNumEPs(); 221 | if(bNumEP > 1) {// All endpoints extracted 222 | bConfNum = midiDescParser.getConfValue(); 223 | break; 224 | } 225 | } 226 | USBTRACE2("STEP1: MIDI,NumEP:", bNumEP); 227 | //Found the MIDI device? 228 | if( bNumEP == 1 ){ //Device not found. 229 | USBTRACE("MIDI not found.\r\nSTEP2: Attempts vendor specific bulk device\r\n"); 230 | // STEP2: Check if attached device is a MIDI device and fill endpoint data structure 231 | for(uint8_t i = 0; i < num_of_conf; i++) { 232 | MidiDescParser midiDescParser(this, false); // Allow all devices, vendor specific class with Bulk transfer 233 | rcode = pUsb->getConfDescr(bAddress, 0, i, &midiDescParser); 234 | if(rcode) // Check error code 235 | goto FailGetConfDescr; 236 | bNumEP += midiDescParser.getNumEPs(); 237 | if(bNumEP > 1) {// All endpoints extracted 238 | bConfNum = midiDescParser.getConfValue(); 239 | break; 240 | } 241 | } 242 | USBTRACE2("\r\nSTEP2: Vendor,NumEP:", bNumEP); 243 | } 244 | 245 | if( bNumEP < 2 ){ //Device not found. 246 | rcode = 0xff; 247 | goto FailGetConfDescr; 248 | } 249 | 250 | // Assign epInfo to epinfo pointer 251 | rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo); 252 | USBTRACE2("Conf:", bConfNum); 253 | USBTRACE2("EPin :", (uint8_t)(epInfo[epDataInIndex].epAddr + 0x80)); 254 | USBTRACE2("EPout:", epInfo[epDataOutIndex].epAddr); 255 | 256 | // Set Configuration Value 257 | rcode = pUsb->setConf(bAddress, 0, bConfNum); 258 | if (rcode) 259 | goto FailSetConfDescr; 260 | 261 | bPollEnable = true; 262 | 263 | if(pFuncOnInit) 264 | pFuncOnInit(); // Call the user function 265 | 266 | USBTRACE("Init done.\r\n"); 267 | return 0; 268 | FailGetDevDescr: 269 | FailSetDevTblEntry: 270 | FailGetConfDescr: 271 | FailSetConfDescr: 272 | Release(); 273 | return rcode; 274 | } 275 | 276 | /* Performs a cleanup after failed Init() attempt */ 277 | uint8_t USBH_MIDI::Release() 278 | { 279 | if(pFuncOnRelease && bPollEnable) 280 | pFuncOnRelease(); // Call the user function 281 | 282 | pUsb->GetAddressPool().FreeAddress(bAddress); 283 | bAddress = 0; 284 | bPollEnable = false; 285 | readPtr = 0; 286 | 287 | return 0; 288 | } 289 | 290 | /* Setup for well known vendor/device specific configuration */ 291 | void USBH_MIDI::setupDeviceSpecific() 292 | { 293 | // Novation 294 | if( vid == 0x1235 ) { 295 | // LaunchPad and LaunchKey endpoint attribute is interrupt 296 | // https://github.com/YuuichiAkagawa/USBH_MIDI/wiki/Novation-USB-Product-ID-List 297 | 298 | // LaunchPad: 0x20:S, 0x36:Mini, 0x51:Pro, 0x69:MK2 299 | if( pid == 0x20 || pid == 0x36 || pid == 0x51 || pid == 0x69 ) { 300 | bTransferTypeMask = 2; 301 | return; 302 | } 303 | 304 | // LaunchKey: 0x30-32, 0x35:Mini, 0x7B-0x7D:MK2, 0x0102,0x113-0x122:MiniMk3, 0x134-0x137:MK3 305 | if( (0x30 <= pid && pid <= 0x32) || pid == 0x35 || (0x7B <= pid && pid <= 0x7D) 306 | || pid == 0x102 || (0x113 <= pid && pid <= 0x122) || (0x134 <= pid && pid <= 0x137) ) { 307 | bTransferTypeMask = 2; 308 | return; 309 | } 310 | } 311 | } 312 | 313 | /* Receive data from MIDI device */ 314 | uint8_t USBH_MIDI::RecvData(uint16_t *bytes_rcvd, uint8_t *dataptr) 315 | { 316 | *bytes_rcvd = (uint16_t)epInfo[epDataInIndex].maxPktSize; 317 | uint8_t r = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr); 318 | #ifdef EXTRADEBUG 319 | if( r ) 320 | USBTRACE2("inTransfer():", r); 321 | #endif 322 | if( *bytes_rcvd < (MIDI_EVENT_PACKET_SIZE-4)){ 323 | dataptr[*bytes_rcvd] = '\0'; 324 | dataptr[(*bytes_rcvd)+1] = '\0'; 325 | } 326 | return r; 327 | } 328 | 329 | /* Receive data from MIDI device */ 330 | uint8_t USBH_MIDI::RecvData(uint8_t *outBuf, bool isRaw) 331 | { 332 | uint8_t rcode = 0; //return code 333 | uint16_t rcvd; 334 | 335 | if( bPollEnable == false ) return 0; 336 | 337 | //Checking unprocessed message in buffer. 338 | if( readPtr != 0 && readPtr < MIDI_EVENT_PACKET_SIZE ){ 339 | if(recvBuf[readPtr] == 0 && recvBuf[readPtr+1] == 0) { 340 | //no unprocessed message left in the buffer. 341 | }else{ 342 | goto RecvData_return_from_buffer; 343 | } 344 | } 345 | 346 | readPtr = 0; 347 | rcode = RecvData( &rcvd, recvBuf); 348 | if( rcode != 0 ) { 349 | return 0; 350 | } 351 | 352 | //if all data is zero, no valid data received. 353 | if( recvBuf[0] == 0 && recvBuf[1] == 0 && recvBuf[2] == 0 && recvBuf[3] == 0 ) { 354 | return 0; 355 | } 356 | 357 | RecvData_return_from_buffer: 358 | uint8_t m; 359 | uint8_t cin = recvBuf[readPtr]; 360 | if( isRaw == true ) { 361 | *(outBuf++) = cin; 362 | } 363 | readPtr++; 364 | *(outBuf++) = m = recvBuf[readPtr++]; 365 | *(outBuf++) = recvBuf[readPtr++]; 366 | *(outBuf++) = recvBuf[readPtr++]; 367 | 368 | return getMsgSizeFromCin(cin & 0x0f); 369 | } 370 | 371 | /* Send data to MIDI device */ 372 | uint8_t USBH_MIDI::SendData(uint8_t *dataptr, uint8_t nCable) 373 | { 374 | uint8_t buf[4]; 375 | uint8_t status = dataptr[0]; 376 | 377 | uint8_t cin = convertStatus2Cin(status); 378 | if ( status == 0xf0 ) { 379 | // SysEx long message 380 | return SendSysEx(dataptr, countSysExDataSize(dataptr), nCable); 381 | } 382 | 383 | //Building USB-MIDI Event Packets 384 | buf[0] = (uint8_t)(nCable << 4) | cin; 385 | buf[1] = dataptr[0]; 386 | 387 | uint8_t msglen = getMsgSizeFromCin(cin); 388 | switch(msglen) { 389 | //3 bytes message 390 | case 3 : 391 | buf[2] = dataptr[1]; 392 | buf[3] = dataptr[2]; 393 | break; 394 | 395 | //2 bytes message 396 | case 2 : 397 | buf[2] = dataptr[1]; 398 | buf[3] = 0; 399 | break; 400 | 401 | //1 byte message 402 | case 1 : 403 | buf[2] = 0; 404 | buf[3] = 0; 405 | break; 406 | default : 407 | break; 408 | } 409 | #ifdef EXTRADEBUG 410 | //Dump for raw USB-MIDI event packet 411 | Notify(PSTR("SendData():"), 0x80), D_PrintHex((buf[0]), 0x80), D_PrintHex((buf[1]), 0x80), D_PrintHex((buf[2]), 0x80), D_PrintHex((buf[3]), 0x80), Notify(PSTR("\r\n"), 0x80); 412 | #endif 413 | return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, 4, buf); 414 | } 415 | 416 | #ifdef DEBUG_USB_HOST 417 | void USBH_MIDI::PrintEndpointDescriptor( const USB_ENDPOINT_DESCRIPTOR* ep_ptr ) 418 | { 419 | USBTRACE("Endpoint descriptor:\r\n"); 420 | USBTRACE2(" Length:\t", ep_ptr->bLength); 421 | USBTRACE2(" Type:\t\t", ep_ptr->bDescriptorType); 422 | USBTRACE2(" Address:\t", ep_ptr->bEndpointAddress); 423 | USBTRACE2(" Attributes:\t", ep_ptr->bmAttributes); 424 | USBTRACE2(" MaxPktSize:\t", ep_ptr->wMaxPacketSize); 425 | USBTRACE2(" Poll Intrv:\t", ep_ptr->bInterval); 426 | } 427 | #endif 428 | 429 | /* look up a MIDI message size from spec */ 430 | /*Return */ 431 | /* 0 : undefined message */ 432 | /* 0<: Vaild message size(1-3) */ 433 | //uint8_t USBH_MIDI::lookupMsgSize(uint8_t midiMsg, uint8_t cin) 434 | uint8_t USBH_MIDI::lookupMsgSize(uint8_t status, uint8_t cin) 435 | { 436 | if( cin == 0 ){ 437 | cin = convertStatus2Cin(status); 438 | } 439 | return getMsgSizeFromCin(cin); 440 | } 441 | 442 | /* SysEx data size counter */ 443 | uint16_t USBH_MIDI::countSysExDataSize(uint8_t *dataptr) 444 | { 445 | uint16_t c = 1; 446 | 447 | if( *dataptr != 0xf0 ){ //not SysEx 448 | return 0; 449 | } 450 | 451 | //Search terminator(0xf7) 452 | while(*dataptr != 0xf7) { 453 | dataptr++; 454 | c++; 455 | //Limiter (default: 256 bytes) 456 | if(c > MIDI_MAX_SYSEX_SIZE){ 457 | c = 0; 458 | break; 459 | } 460 | } 461 | return c; 462 | } 463 | 464 | /* Send SysEx message to MIDI device */ 465 | uint8_t USBH_MIDI::SendSysEx(uint8_t *dataptr, uint16_t datasize, uint8_t nCable) 466 | { 467 | uint8_t buf[MIDI_EVENT_PACKET_SIZE]; 468 | uint8_t rc = 0; 469 | uint16_t n = datasize; 470 | uint8_t wptr = 0; 471 | uint8_t maxpkt = epInfo[epDataInIndex].maxPktSize; 472 | 473 | USBTRACE("SendSysEx:\r\t"); 474 | USBTRACE2(" Length:\t", datasize); 475 | #ifdef EXTRADEBUG 476 | uint16_t pktSize = (n+2)/3; //Calculate total USB MIDI packet size 477 | USBTRACE2(" Total pktSize:\t", pktSize); 478 | #endif 479 | 480 | while(n > 0) { 481 | //Byte 0 482 | buf[wptr] = (nCable << 4) | 0x4; //x4 SysEx starts or continues 483 | 484 | switch ( n ) { 485 | case 1 : 486 | buf[wptr++] = (nCable << 4) | 0x5; //x5 SysEx ends with following single byte. 487 | buf[wptr++] = *(dataptr++); 488 | buf[wptr++] = 0x00; 489 | buf[wptr++] = 0x00; 490 | n = 0; 491 | break; 492 | case 2 : 493 | buf[wptr++] = (nCable << 4) | 0x6; //x6 SysEx ends with following two bytes. 494 | buf[wptr++] = *(dataptr++); 495 | buf[wptr++] = *(dataptr++); 496 | buf[wptr++] = 0x00; 497 | n = 0; 498 | break; 499 | case 3 : 500 | buf[wptr] = (nCable << 4) | 0x7; //x7 SysEx ends with following three bytes. 501 | // fall through 502 | default : 503 | wptr++; 504 | buf[wptr++] = *(dataptr++); 505 | buf[wptr++] = *(dataptr++); 506 | buf[wptr++] = *(dataptr++); 507 | n = n - 3; 508 | break; 509 | } 510 | 511 | if( wptr >= maxpkt || n == 0 ){ //Reach a maxPktSize or data end. 512 | USBTRACE2(" wptr:\t", wptr); 513 | if( (rc = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, wptr, buf)) != 0 ){ 514 | break; 515 | } 516 | wptr = 0; //rewind write pointer 517 | } 518 | } 519 | return(rc); 520 | } 521 | 522 | uint8_t USBH_MIDI::extractSysExData(uint8_t *p, uint8_t *buf) 523 | { 524 | uint8_t rc = 0; 525 | uint8_t cin = *(p) & 0x0f; 526 | 527 | //SysEx message? 528 | if( (cin & 0xc) != 4 ) return rc; 529 | 530 | switch(cin) { 531 | case 4: 532 | case 7: 533 | *buf++ = *(p+1); 534 | *buf++ = *(p+2); 535 | *buf++ = *(p+3); 536 | rc = 3; 537 | break; 538 | case 6: 539 | *buf++ = *(p+1); 540 | *buf++ = *(p+2); 541 | rc = 2; 542 | break; 543 | case 5: 544 | *buf++ = *(p+1); 545 | rc = 1; 546 | break; 547 | default: 548 | break; 549 | } 550 | return(rc); 551 | } 552 | 553 | // Configuration Descriptor Parser 554 | // Copied from confdescparser.h and modifiy. 555 | MidiDescParser::MidiDescParser(UsbMidiConfigXtracter *xtractor, bool modeMidi) : 556 | theXtractor(xtractor), 557 | stateParseDescr(0), 558 | dscrLen(0), 559 | dscrType(0), 560 | nEPs(0), 561 | isMidiSearch(modeMidi){ 562 | theBuffer.pValue = varBuffer; 563 | valParser.Initialize(&theBuffer); 564 | theSkipper.Initialize(&theBuffer); 565 | } 566 | void MidiDescParser::Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset __attribute__((unused))) { 567 | uint16_t cntdn = (uint16_t)len; 568 | uint8_t *p = (uint8_t*)pbuf; 569 | 570 | while(cntdn) 571 | if(!ParseDescriptor(&p, &cntdn)) 572 | return; 573 | } 574 | 575 | bool MidiDescParser::ParseDescriptor(uint8_t **pp, uint16_t *pcntdn) { 576 | USB_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast(varBuffer); 577 | USB_INTERFACE_DESCRIPTOR* uid = reinterpret_cast(varBuffer); 578 | switch(stateParseDescr) { 579 | case 0: 580 | theBuffer.valueSize = 2; 581 | valParser.Initialize(&theBuffer); 582 | stateParseDescr = 1; 583 | // fall through 584 | case 1: 585 | if(!valParser.Parse(pp, pcntdn)) 586 | return false; 587 | dscrLen = *((uint8_t*)theBuffer.pValue); 588 | dscrType = *((uint8_t*)theBuffer.pValue + 1); 589 | stateParseDescr = 2; 590 | // fall through 591 | case 2: 592 | // This is a sort of hack. Assuming that two bytes are all ready in the buffer 593 | // the pointer is positioned two bytes ahead in order for the rest of descriptor 594 | // to be read right after the size and the type fields. 595 | // This should be used carefully. varBuffer should be used directly to handle data 596 | // in the buffer. 597 | theBuffer.pValue = varBuffer + 2; 598 | stateParseDescr = 3; 599 | // fall through 600 | case 3: 601 | switch(dscrType) { 602 | case USB_DESCRIPTOR_INTERFACE: 603 | isGoodInterface = false; 604 | break; 605 | case USB_DESCRIPTOR_CONFIGURATION: 606 | case USB_DESCRIPTOR_ENDPOINT: 607 | case HID_DESCRIPTOR_HID: 608 | break; 609 | } 610 | theBuffer.valueSize = dscrLen - 2; 611 | valParser.Initialize(&theBuffer); 612 | stateParseDescr = 4; 613 | // fall through 614 | case 4: 615 | switch(dscrType) { 616 | case USB_DESCRIPTOR_CONFIGURATION: 617 | if(!valParser.Parse(pp, pcntdn)) 618 | return false; 619 | confValue = ucd->bConfigurationValue; 620 | break; 621 | case USB_DESCRIPTOR_INTERFACE: 622 | if(!valParser.Parse(pp, pcntdn)) 623 | return false; 624 | USBTRACE("Interface descriptor:\r\n"); 625 | USBTRACE2(" Inf#:\t\t", uid->bInterfaceNumber); 626 | USBTRACE2(" Alt:\t\t", uid->bAlternateSetting); 627 | USBTRACE2(" EPs:\t\t", uid->bNumEndpoints); 628 | USBTRACE2(" IntCl:\t\t", uid->bInterfaceClass); 629 | USBTRACE2(" IntSubcl:\t", uid->bInterfaceSubClass); 630 | USBTRACE2(" Protocol:\t", uid->bInterfaceProtocol); 631 | // MIDI check mode ? 632 | if( isMidiSearch ){ //true: MIDI Streaming, false: ALL 633 | if( uid->bInterfaceClass == USB_CLASS_AUDIO && uid->bInterfaceSubClass == USB_SUBCLASS_MIDISTREAMING ) { 634 | // MIDI found. 635 | USBTRACE("+MIDI found\r\n\r\n"); 636 | }else{ 637 | USBTRACE("-MIDI not found\r\n\r\n"); 638 | break; 639 | } 640 | } 641 | isGoodInterface = true; 642 | // Initialize the counter if no two endpoints can be found in one interface. 643 | if(nEPs < 2) 644 | // reset endpoint counter 645 | nEPs = 0; 646 | break; 647 | case USB_DESCRIPTOR_ENDPOINT: 648 | if(!valParser.Parse(pp, pcntdn)) 649 | return false; 650 | if(isGoodInterface && nEPs < 2){ 651 | USBTRACE(">Extracting endpoint\r\n"); 652 | if( theXtractor->EndpointXtract(confValue, 0, 0, 0, (USB_ENDPOINT_DESCRIPTOR*)varBuffer) ) 653 | nEPs++; 654 | } 655 | break; 656 | 657 | default: 658 | if(!theSkipper.Skip(pp, pcntdn, dscrLen - 2)) 659 | return false; 660 | } 661 | theBuffer.pValue = varBuffer; 662 | stateParseDescr = 0; 663 | } 664 | return true; 665 | } 666 | 667 | /* Extracts endpoint information from config descriptor */ 668 | bool USBH_MIDI::EndpointXtract(uint8_t conf __attribute__((unused)), 669 | uint8_t iface __attribute__((unused)), 670 | uint8_t alt __attribute__((unused)), 671 | uint8_t proto __attribute__((unused)), 672 | const USB_ENDPOINT_DESCRIPTOR *pep) 673 | { 674 | uint8_t index; 675 | 676 | #ifdef DEBUG_USB_HOST 677 | PrintEndpointDescriptor(pep); 678 | #endif 679 | // Is the endpoint transfer type bulk? 680 | if((pep->bmAttributes & bTransferTypeMask) == USB_TRANSFER_TYPE_BULK) { 681 | USBTRACE("+valid EP found.\r\n"); 682 | index = (pep->bEndpointAddress & 0x80) == 0x80 ? epDataInIndex : epDataOutIndex; 683 | } else { 684 | USBTRACE("-No valid EP found.\r\n"); 685 | return false; 686 | } 687 | 688 | // Fill the rest of endpoint data structure 689 | epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); 690 | // The maximum packet size for the USB Host Shield 2.0 library is 64 bytes. 691 | if(pep->wMaxPacketSize > MIDI_EVENT_PACKET_SIZE) { 692 | epInfo[index].maxPktSize = MIDI_EVENT_PACKET_SIZE; 693 | } else { 694 | epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize; 695 | } 696 | 697 | return true; 698 | } 699 | --------------------------------------------------------------------------------