send method

dynamic send(
  1. Uint8List bytes
)

Implementation

send(Uint8List bytes) async {
  if (_midiService == null) return;
  if (_midiCharacteristic == null) return;

  var packetSize = 20;

  List<int> dataBytes = List.from(bytes);

  if (bytes.first == 0xF0 && bytes.last == 0xF7) {
    //  this is a sysex message, handle carefully
    if (bytes.length > packetSize - 3) {
      // Split into multiple messages of 20 bytes total

      // First packet
      List<int> packet = dataBytes.take(packetSize - 2).toList();

      // Insert header(and empty timstamp high) and timestamp low in front Sysex Start
      packet.insert(0, 0x80);
      packet.insert(0, 0x80);

      _sendBytes(packet);

      dataBytes = dataBytes.skip(packetSize - 2).toList();

      // More packets
      while (dataBytes.length > 0) {
        int pickCount = min(dataBytes.length, packetSize - 1);
        packet = dataBytes.getRange(0, pickCount).toList(); // Pick bytes for packet
        // Insert header
        packet.insert(0, 0x80);

        if (packet.length < packetSize) {
          // Last packet
          // Timestamp before Sysex End byte
          packet.insert(packet.length - 1, 0x80);
        }

        // Wait for buffer to clear
        _sendBytes(packet);

        if (dataBytes.length > packetSize - 2) {
          dataBytes = dataBytes.skip(pickCount).toList(); // Advance buffer
        } else {
          return;
        }
      }
    } else {
      // Insert timestamp low in front of Sysex End-byte
      dataBytes.insert(bytes.length - 1, 0x80);

      // Insert header(and empty timstamp high) and timestamp low in front of BLE Midi message
      dataBytes.insert(0, 0x80);
      dataBytes.insert(0, 0x80);

      _sendBytes(dataBytes);
    }
    return;
  }

  // In bluetooth MIDI we need to send each midi command separately
  List<int> currentBuffer = [];
  for (int i = 0; i < dataBytes.length; i++) {
    int byte = dataBytes[i];

    // Insert header(and empty timestamp high) and timestamp
    // low in front of BLE Midi message
    if ((byte & 0x80) != 0) {
      currentBuffer.insert(0, 0x80);
      currentBuffer.insert(0, 0x80);
    }
    currentBuffer.add(byte);

    // Send each MIDI command separately
    bool endReached = i == (dataBytes.length - 1);
    bool isCompleteCommand = endReached || (dataBytes[i + 1] & 0x80) != 0;

    if (isCompleteCommand) {
      _sendBytes(currentBuffer);
      currentBuffer = [];
    }
  }
}