From f43b60debfb38ba43b560933774270019392ccfc Mon Sep 17 00:00:00 2001 From: odbol Date: Mon, 9 Nov 2015 01:09:06 -0800 Subject: [PATCH] Fixed write() freezing entire Sketch unless MIDI port is opened by PC (Issue #4) --- src/MIDIUSB.cpp | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/MIDIUSB.cpp b/src/MIDIUSB.cpp index aca0b93..69e81cb 100644 --- a/src/MIDIUSB.cpp +++ b/src/MIDIUSB.cpp @@ -153,14 +153,23 @@ size_t MIDI_::write(const uint8_t *buffer, size_t size) // open connection isn't broken cleanly (cable is yanked out, host dies // or locks up, or host virtual serial port hangs) - int r = USB_Send(MIDI_TX, buffer, size); - - if (r > 0) - { - return r; - } else + // first, check the TX buffer to see if it's ready for writing. + // USB_Send() may block if there's no one listening on the other end. + // in that case, we don't want to block waiting for someone to connect, + // because that would freeze the whole sketch + // instead, we'll just drop the packets and hope the caller figures it out. + if (Is_udd_write_enabled(MIDI_TX)) { - return 0; + + int r = USB_Send(MIDI_TX, buffer, size); + + if (r > 0) + { + return r; + } else + { + return 0; + } } return 0; }