蓝牙调研

扫描设备

过滤指定的Uuid
/common/ScannerFragment.java

        final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
        final ScanSettings settings = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(750).setUseHardwareBatchingIfSupported(false).setUseHardwareFilteringIfSupported(false).build();
        final List<ScanFilter> filters = new ArrayList<>();
        filters.add(new ScanFilter.Builder().setServiceUuid(mUuid).build());
        scanner.startScan(filters, settings, scanCallback);

mUuid 的值:

public static final UUID THINGY_BASE_UUID = new UUID(0xEF6801009B354933L, 0x9B1052FFA9740042L);

配对连接

通过对扫描到的设备列表进行选择,指定要连接的设备
app/src/main/java/no/nordicsemi/android/nrfthingy/configuration/InitialConfigurationActivity.java

    @Override
    public void onDeviceSelected(BluetoothDevice device, String name) {
        if (mThingySdkManager != null) {
            mThingySdkManager.connectToThingy(this, device, ThingyService.class);
        }
        mDevice = device;
        animateStepOne();
        showConnectionProgressDialog();
    }
    public void connectToThingy(final Context context, final BluetoothDevice device, final Class<? extends BaseThingyService> service) {
        final Intent intent = new Intent(context, service);
        intent.putExtra(ThingyUtils.EXTRA_DEVICE, device);
        context.startService(intent);
    }

service 实现:thingy/ThingyService.java 继承自 BaseThingyService
连接的逻辑在 BaseThingyService 中实现.
thingylib/src/main/java/no/nordicsemi/android/thingylib/BaseThingyService.java

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            final BluetoothDevice bluetoothDevice = intent.getParcelableExtra(ThingyUtils.EXTRA_DEVICE);
            if (bluetoothDevice != null) {
                mThingyConnections.put(bluetoothDevice, new ThingyConnection(this, bluetoothDevice));
                if (!mDevices.contains(bluetoothDevice)) {
                    mDevices.add(bluetoothDevice);
                }
            }
        }

        return START_NOT_STICKY;
    }

创建ThingyConnection对象,在ThingyConnection对象里面做连接操作,此后对蓝牙设备的操作基本都在ThingyConnection对象中执行.

thingylib/src/main/java/no/nordicsemi/android/thingylib/ThingyConnection.java

    public ThingyConnection(final Context context, final BluetoothDevice bluetoothDevice) {
        connect(bluetoothDevice);
        this.mListener = (ThingyConnectionGattCallbacks) mContext;
    }

connect 方法的实现

    private void connect(final BluetoothDevice device) {
     //建立连接并注册回调
        mBluetoothGatt = device.connectGatt(mContext, false, this);
    }

BluetoothGatt的回调处理

连接状态回调

    @Override
    public final void onConnectionStateChange(final BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothGatt.STATE_CONNECTED) {
            isConnected = true;
            //发送本地广播通知连接状态
            Intent intent = new Intent(ThingyUtils.ACTION_DEVICE_CONNECTED);
            intent.putExtra(ThingyUtils.EXTRA_DATA, newState);
            intent.putExtra(ThingyUtils.EXTRA_DEVICE, mBluetoothDevice);
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
            mListener.onDeviceConnected(mBluetoothDevice, newState);
            //开启服务检索
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //结果在onServicesDiscovered回调中
                    gatt.discoverServices();
                }
            }, 200);
        } 
    }

服务检索回调务的Characteristic

    @Override
    public final void onServicesDiscovered(BluetoothGatt gatt, int status) {
        final BluetoothGattService mSoundService = gatt.getService(ThingyUtils.THINGY_SOUND_SERVICE);
        if (mSoundService != null) {
            //初始化音频服务相关的Characteristic
            mSoundConfigurationCharacteristic =        mSoundService.getCharacteristic(ThingyUtils.THINGY_SOUND_CONFIG_CHARACTERISTIC);
            mSpeakerDataCharacteristic = mSoundService.getCharacteristic(ThingyUtils.THINGY_SPEAKER_DATA_CHARACTERISTIC);
            mSpeakerStatusCharacteristic = mSoundService.getCharacteristic(ThingyUtils.THINGY_SPEAKER_STATUS_CHARACTERISTIC);
            mMicrophoneCharacteristic = mSoundService.getCharacteristic(ThingyUtils.THINGY_MICROPHONE_CHARACTERISTIC);
        }
        //读取Characteristics 数据
        readThingyCharacteristics();
    }
    private final void readThingyCharacteristics() {
        //结果在 onCharacteristicRead 回调中
        add(RequestType.READ_CHARACTERISTIC, mSoundConfigurationCharacteristic);
        add(RequestType.READ_DESCRIPTOR, mSpeakerStatusCharacteristic.getDescriptor(ThingyUtils.CLIENT_CHARACTERISTIC_CONFIGURATOIN_DESCRIPTOR));
        if (mMicrophoneCharacteristic != null) {
            add(RequestType.READ_DESCRIPTOR, mMicrophoneCharacteristic.getDescriptor(ThingyUtils.CLIENT_CHARACTERISTIC_CONFIGURATOIN_DESCRIPTOR));
        }
    
    }

CharacteristicRead回调

    @Override
    public final void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicRead(gatt, characteristic, status);
         if (mSoundConfigurationCharacteristic != null && characteristic.equals(mSoundConfigurationCharacteristic)) {
            readSoundConfigurationCharacteristic();
        }
        mHandler.post(mProcessNextTask);
    }
    //读取SpeakerMode和MicrophoneMode
    final void readSoundConfigurationCharacteristic() {
        if (mSoundConfigurationCharacteristic != null) {
            final BluetoothGattCharacteristic characteristic = mSoundConfigurationCharacteristic;
            mSpeakerMode = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
            mMicrophoneMode = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 1);
            Log.v(TAG, "Sound service configuration read completed");
        }
    }

onCharacteristicChanged回调

主要用于下面的录音流程和播放流程的数据获取

    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(gatt, characteristic);
        
         if (characteristic.equals(mSpeakerStatusCharacteristic)) {
            final int speakerStatus = mSpeakerStatusCharacteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
            switch (speakerStatus) {
                case ThingyUtils.SPEAKER_STATUS_FINISHED:
                    if (mPlayPcmRequested) {
                        mWait = false;
                        if (mQueue.size() == 0) {
                            broadcastAudioStreamComplete();
                        }
                    } else if (mPlayVoiceInput) {
                        // speak回调
                        mHandler.post(mProcessNextTask);
                    }
                    break;
            }
        } else if (characteristic.equals(mMicrophoneCharacteristic)) {
            if (mAdpcmDecoder != null) {
                if (mMtu == ThingyUtils.MAX_MTU_SIZE_THINGY) { //Pre lollipop devices may not have the max mtu size hence the check
                    final byte[] data = new byte[131];
                    final byte[] tempData = characteristic.getValue();
                    System.arraycopy(tempData, 0, data, 0, 131);
                    //数据转码后给 audiotrack 播放
                    mAdpcmDecoder.add(data);
                } else {
                    final byte[] data = characteristic.getValue();
                    mAdpcmDecoder.add(data);
                }

            }
        }
    }

播放音频流程

启动播放

thingylib/src/main/java/no/nordicsemi/android/thingylib/ThingySdkManager.java

    public void enableThingyMicrophone(final BluetoothDevice device, boolean enable) {
        if (device != null) {
            if (mBinder != null) {
                final ThingyConnection thingyConnection = mBinder.getThingyConnection(device);
                if (thingyConnection != null) {
                    thingyConnection.enableThingyMicrophoneNotifications(enable);
                }
            }
        }
    }

thingylib/src/main/java/no/nordicsemi/android/thingylib/ThingyConnection.java

    final void enableThingyMicrophoneNotifications(final boolean enable) {
        if (mMicrophoneCharacteristic != null) {
            final BluetoothGattDescriptor microphoneDescriptor = mMicrophoneCharacteristic.getDescriptor(ThingyUtils.CLIENT_CHARACTERISTIC_CONFIGURATOIN_DESCRIPTOR);
            
                if (!isNotificationsAlreadyEnabled(microphoneDescriptor)) {
                    byte[] data = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
                    add(RequestType.WRITE_DESCRIPTOR, microphoneDescriptor, data);
                }
                enableAdpcmMode(enable);
        }
    }
    private final void enableAdpcmMode(final boolean enable) {
        if (mMicrophoneCharacteristic != null) {
            mEnableThingyMicrophone = enable;
            
            if (mMicrophoneMode != ThingyUtils.ADPCM_MODE) {
                mMicrophoneMode = ThingyUtils.ADPCM_MODE;
                add(RequestType.WRITE_CHARACTERISTIC, mSoundConfigurationCharacteristic, new byte[]{ThingyUtils.ADPCM_MODE, (byte) mSpeakerMode}, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
            }

            //创建AudioTrack
            int bufferSize = AudioTrack.getMinBufferSize(16000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
            mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 16000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
            mAudioTrack.play();
            
            //CharacteristicChanged回调mAdpcmDecoder进行解码
            mAdpcmDecoder = new ADPCMDecoder(mContext, false);
            mAdpcmDecoder.setListener(new ADPCMDecoder.DecoderListener() {
                @Override
                public void onFrameDecoded(byte[] pcm, int frameNumber) {
                    if (mEnableThingyMicrophone && mAudioTrack != null) {
                        final int status = mAudioTrack.write(pcm, 0, pcm.length/*, AudioTrack.WRITE_NON_BLOCKING*/);
                }
            });
        }
    }

录入声音流程

app/src/main/java/no/nordicsemi/android/nrfthingy/sound/ThingyMicrophoneService.java

    public void startRecordingAudio(final BluetoothDevice device) {
        //创建AudioRecord对象
        final AudioRecord audioRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, AUDIO_BUFFER);
        
        if(audioRecorder != null && audioRecorder.getState() != AudioRecord.STATE_UNINITIALIZED) {
        
            byte audioData[] = new byte[AUDIO_BUFFER];
            audioRecorder.startRecording();
        
            while (mStartRecordingAudio) {
                //读取audioRecorder的数据
                int status = audioRecorder.read(audioData, 0, AUDIO_BUFFER);
                
                try {
                    //蓝牙传输数据
                    thingyConnection.playVoiceInput(downSample(audioData));
                    //发送广播通知ui
                    sendAudioRecordBroadcast(device, audioData, status);
                } catch (Exception e) {
                    break;
                }
            }
        } 
    }

thingylib/src/main/java/no/nordicsemi/android/thingylib/ThingyConnection.java

    public final void playVoiceInput(final byte[] sample) {
        if (mSpeakerDataCharacteristic != null) {
            mPlayVoiceInput = true;
            mPcmSample = sample;
            streamAudio(sample);
        }
    }
    private void streamAudio(final byte[] sample) {
        int index = 0;
        int offset = 0;
        int length;
        int mChunkSize;
        if (mMtu > ThingyUtils.MAX_MTU_SIZE_PRE_LOLLIPOP) {
            mChunkSize = ThingyUtils.MAX_AUDIO_PACKET_SIZE;
        } else {
            mChunkSize = ThingyUtils.MAX_MTU_SIZE_PRE_LOLLIPOP;
        }

        mNumOfAudioChunks = (int) Math.ceil((double) sample.length / mChunkSize);
        while (index < mNumOfAudioChunks) {
            length = Math.min(mPcmSample.length - offset, mChunkSize);
            final byte[] audio = new byte[length];
            System.arraycopy(mPcmSample, offset, audio, 0, length);
            add(RequestType.WRITE_CHARACTERISTIC, mSpeakerDataCharacteristic, audio, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
            index++;
            offset += length;
        }
    }
    private void add(RequestType type, BluetoothGattCharacteristic characteristic, byte[] data, int writeType) {
        Request request = new Request(type, characteristic, data, writeType);
        add(request);
    }
    synchronized private void add(Request request) {
        mQueue.add(request);
        if (mQueue.size() == 1) {
            mQueue.peek().start(mBluetoothGatt);
        }
    }
        void start(BluetoothGatt bluetoothGatt) {
            switch (requestType) {
                case WRITE_CHARACTERISTIC:
                    characteristic.setValue(data);
                    characteristic.setWriteType(writeType);
                    if (!bluetoothGatt.writeCharacteristic(characteristic)) {
                    } else {
                    }
                    break;
            }
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,236评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,867评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,715评论 0 340
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,899评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,895评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,733评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,085评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,722评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,025评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,696评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,816评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,447评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,057评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,009评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,254评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,204评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,561评论 2 343

推荐阅读更多精彩内容