BluetoothMidiDevice.java revision e0a6ca64fac5bd4f10139321604031816e90adb4
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.bluetoothmidiservice;
18
19import android.bluetooth.BluetoothDevice;
20import android.bluetooth.BluetoothGatt;
21import android.bluetooth.BluetoothGattCallback;
22import android.bluetooth.BluetoothGattCharacteristic;
23import android.bluetooth.BluetoothGattDescriptor;
24import android.bluetooth.BluetoothGattService;
25import android.bluetooth.BluetoothProfile;
26import android.content.Context;
27import android.media.midi.MidiDeviceInfo;
28import android.media.midi.MidiDeviceServer;
29import android.media.midi.MidiDeviceStatus;
30import android.media.midi.MidiManager;
31import android.media.midi.MidiReceiver;
32import android.os.Bundle;
33import android.os.IBinder;
34import android.util.Log;
35
36import com.android.internal.midi.MidiEventScheduler;
37import com.android.internal.midi.MidiEventScheduler.MidiEvent;
38
39import libcore.io.IoUtils;
40
41import java.io.IOException;
42import java.util.List;
43import java.util.UUID;
44
45/**
46 * Class used to implement a Bluetooth MIDI device.
47 */
48public final class BluetoothMidiDevice {
49
50    private static final String TAG = "BluetoothMidiDevice";
51    private static final boolean DEBUG = false;
52
53    private static final int MAX_PACKET_SIZE = 20;
54
55    //  Bluetooth MIDI Gatt service UUID
56    private static final UUID MIDI_SERVICE = UUID.fromString(
57            "03B80E5A-EDE8-4B33-A751-6CE34EC4C700");
58    // Bluetooth MIDI Gatt characteristic UUID
59    private static final UUID MIDI_CHARACTERISTIC = UUID.fromString(
60            "7772E5DB-3868-4112-A1A9-F2669D106BF3");
61    // Descriptor UUID for enabling characteristic changed notifications
62    private static final UUID CLIENT_CHARACTERISTIC_CONFIG = UUID.fromString(
63            "00002902-0000-1000-8000-00805f9b34fb");
64
65    private final BluetoothDevice mBluetoothDevice;
66    private final BluetoothMidiService mService;
67    private final MidiManager mMidiManager;
68    private MidiReceiver mOutputReceiver;
69    private final MidiEventScheduler mEventScheduler = new MidiEventScheduler();
70
71    private MidiDeviceServer mDeviceServer;
72    private BluetoothGatt mBluetoothGatt;
73
74    private BluetoothGattCharacteristic mCharacteristic;
75
76    // PacketReceiver for receiving formatted packets from our BluetoothPacketEncoder
77    private final PacketReceiver mPacketReceiver = new PacketReceiver();
78
79    private final BluetoothPacketEncoder mPacketEncoder
80            = new BluetoothPacketEncoder(mPacketReceiver, MAX_PACKET_SIZE);
81
82    private final BluetoothPacketDecoder mPacketDecoder
83            = new BluetoothPacketDecoder(MAX_PACKET_SIZE);
84
85    private final MidiDeviceServer.Callback mDeviceServerCallback
86            = new MidiDeviceServer.Callback() {
87        @Override
88        public void onDeviceStatusChanged(MidiDeviceServer server, MidiDeviceStatus status) {
89        }
90
91        @Override
92        public void onClose() {
93            close();
94        }
95    };
96
97    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
98        @Override
99        public void onConnectionStateChange(BluetoothGatt gatt, int status,
100                int newState) {
101            String intentAction;
102            if (newState == BluetoothProfile.STATE_CONNECTED) {
103                Log.i(TAG, "Connected to GATT server.");
104                Log.i(TAG, "Attempting to start service discovery:" +
105                        mBluetoothGatt.discoverServices());
106            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
107                Log.i(TAG, "Disconnected from GATT server.");
108                close();
109            }
110        }
111
112        @Override
113        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
114            if (status == BluetoothGatt.GATT_SUCCESS) {
115                List<BluetoothGattService> services = mBluetoothGatt.getServices();
116                for (BluetoothGattService service : services) {
117                    if (MIDI_SERVICE.equals(service.getUuid())) {
118                        Log.d(TAG, "found MIDI_SERVICE");
119                        List<BluetoothGattCharacteristic> characteristics
120                            = service.getCharacteristics();
121                        for (BluetoothGattCharacteristic characteristic : characteristics) {
122                            if (MIDI_CHARACTERISTIC.equals(characteristic.getUuid())) {
123                                Log.d(TAG, "found MIDI_CHARACTERISTIC");
124                                mCharacteristic = characteristic;
125
126                                // Specification says to read the characteristic first and then
127                                // switch to receiving notifications
128                                mBluetoothGatt.readCharacteristic(characteristic);
129                                break;
130                            }
131                        }
132                        break;
133                    }
134                }
135            } else {
136                Log.e(TAG, "onServicesDiscovered received: " + status);
137                close();
138            }
139        }
140
141        @Override
142        public void onCharacteristicRead(BluetoothGatt gatt,
143                BluetoothGattCharacteristic characteristic,
144                int status) {
145            Log.d(TAG, "onCharacteristicRead " + status);
146
147            // switch to receiving notifications after initial characteristic read
148            mBluetoothGatt.setCharacteristicNotification(characteristic, true);
149
150            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
151                    CLIENT_CHARACTERISTIC_CONFIG);
152            if (descriptor != null) {
153                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
154                mBluetoothGatt.writeDescriptor(descriptor);
155            } else {
156                Log.e(TAG, "No CLIENT_CHARACTERISTIC_CONFIG for device " + mBluetoothDevice);
157            }
158        }
159
160        @Override
161        public void onCharacteristicWrite(BluetoothGatt gatt,
162                BluetoothGattCharacteristic characteristic,
163                int status) {
164            Log.d(TAG, "onCharacteristicWrite " + status);
165            mPacketEncoder.writeComplete();
166        }
167
168        @Override
169        public void onCharacteristicChanged(BluetoothGatt gatt,
170                                            BluetoothGattCharacteristic characteristic) {
171            if (DEBUG) {
172                logByteArray("Received ", characteristic.getValue(), 0,
173                        characteristic.getValue().length);
174            }
175            mPacketDecoder.decodePacket(characteristic.getValue(), mOutputReceiver);
176        }
177    };
178
179    // This receives MIDI data that has already been passed through our MidiEventScheduler
180    // and has been normalized by our MidiFramer.
181
182    private class PacketReceiver implements PacketEncoder.PacketReceiver {
183        // buffers of every possible packet size
184        private final byte[][] mWriteBuffers;
185
186        public PacketReceiver() {
187            // Create buffers of every possible packet size
188            mWriteBuffers = new byte[MAX_PACKET_SIZE + 1][];
189            for (int i = 0; i <= MAX_PACKET_SIZE; i++) {
190                mWriteBuffers[i] = new byte[i];
191            }
192        }
193
194        @Override
195        public void writePacket(byte[] buffer, int count) {
196            if (mCharacteristic == null) {
197                Log.w(TAG, "not ready to send packet yet");
198                return;
199            }
200            byte[] writeBuffer = mWriteBuffers[count];
201            System.arraycopy(buffer, 0, writeBuffer, 0, count);
202            mCharacteristic.setValue(writeBuffer);
203            if (DEBUG) {
204                logByteArray("Sent ", mCharacteristic.getValue(), 0,
205                       mCharacteristic.getValue().length);
206            }
207            mBluetoothGatt.writeCharacteristic(mCharacteristic);
208        }
209    }
210
211    public BluetoothMidiDevice(Context context, BluetoothDevice device,
212            BluetoothMidiService service) {
213        mBluetoothDevice = device;
214        mService = service;
215
216        mBluetoothGatt = mBluetoothDevice.connectGatt(context, false, mGattCallback);
217
218        mMidiManager = (MidiManager)context.getSystemService(Context.MIDI_SERVICE);
219
220        Bundle properties = new Bundle();
221        properties.putString(MidiDeviceInfo.PROPERTY_NAME, mBluetoothGatt.getDevice().getName());
222        properties.putParcelable(MidiDeviceInfo.PROPERTY_BLUETOOTH_DEVICE,
223                mBluetoothGatt.getDevice());
224
225        MidiReceiver[] inputPortReceivers = new MidiReceiver[1];
226        inputPortReceivers[0] = mEventScheduler.getReceiver();
227
228        mDeviceServer = mMidiManager.createDeviceServer(inputPortReceivers, 1,
229                null, null, properties, MidiDeviceInfo.TYPE_BLUETOOTH, mDeviceServerCallback);
230
231        mOutputReceiver = mDeviceServer.getOutputPortReceivers()[0];
232
233        // This thread waits for outgoing messages from our MidiEventScheduler
234        // And forwards them to our MidiFramer to be prepared to send via Bluetooth.
235        new Thread("BluetoothMidiDevice " + mBluetoothDevice) {
236            @Override
237            public void run() {
238                while (true) {
239                    MidiEvent event;
240                    try {
241                        event = (MidiEvent)mEventScheduler.waitNextEvent();
242                    } catch (InterruptedException e) {
243                        // try again
244                        continue;
245                    }
246                    if (event == null) {
247                        break;
248                    }
249                    try {
250                        mPacketEncoder.send(event.data, 0, event.count,
251                                event.getTimestamp());
252                    } catch (IOException e) {
253                        Log.e(TAG, "mPacketAccumulator.send failed", e);
254                    }
255                    mEventScheduler.addEventToPool(event);
256                }
257                Log.d(TAG, "BluetoothMidiDevice thread exit");
258            }
259        }.start();
260    }
261
262    private void close() {
263        synchronized (mBluetoothDevice) {
264            mEventScheduler.close();
265            mService.deviceClosed(mBluetoothDevice);
266
267            if (mDeviceServer != null) {
268                IoUtils.closeQuietly(mDeviceServer);
269                mDeviceServer = null;
270            }
271            if (mBluetoothGatt != null) {
272                mBluetoothGatt.close();
273                mBluetoothGatt = null;
274            }
275        }
276    }
277
278    public IBinder getBinder() {
279        return mDeviceServer.asBinder();
280    }
281
282    private static void logByteArray(String prefix, byte[] value, int offset, int count) {
283        StringBuilder builder = new StringBuilder(prefix);
284        for (int i = offset; i < count; i++) {
285            builder.append(String.format("0x%02X", value[i]));
286            if (i != value.length - 1) {
287                builder.append(", ");
288            }
289        }
290        Log.d(TAG, builder.toString());
291    }
292}
293