_bulkOut.write method for sending streams of data chunk by chunk

Your code seems overly complex.

I’m also confused why you’re writing tiny amounts at once. You appear to be sending only 9 bytes per transfer; the USB stack will split much bigger transfers into the correct bulk packet size. I’ve no idea what “BUFFER_SIZE” is, but if its not 9 then you’re going to be having problems.

This doesn’t have error handling, but should work fine. It issues writes of max 4kB, which the imp will generally split up into 64 packets of 64 bytes on the wire, but the callback only fires when all 4kB has been sent.

dataToWrite <- blob(x); // this contains the data you want to write
const MAXWRITE = 4096;

function writeChunk(onComplete) {
  local remaining = dataToWrite.len() - dataToWrite.tell();
  local chunk = (remaining > MAXWRITE)?MAXWRITE:remaining;

  // Anything left to send?
  if (chunk > 0) {
    _bulkOut.write(dataToWrite.readblob(chunk), function(ep, state, data, len) {
      writeChunk(onComplete);
    });
  } else {
    // Fire complete callback
    onComplete();
  }
}

// Start the send; ensure pointer is at the start of the blob
dataToWrite.seek(0);
writeChunk(function() { server.log("transfer complete"); });