二、蓝牙Bluetooth源码目录分析
1.Bluetooth的设置应用
路径:\packages\apps\Settings\src\com\android\settings\bluetooth
蓝牙设置应用及设置参数,蓝牙状态,蓝牙设备等。
BluetoothDevicePreference.java
蓝牙设备首选项,即蓝牙设备的配置信息,比如是否连接,是否配对,是否可见等等。该类继承了preference类,主要是提供获取蓝牙设备及通知蓝牙设备配置信息变化。
BluetoothDiscoverableEnabler.java
蓝牙搜索UI逻辑处理,包括搜索暂停,搜索恢复及蓝牙开启关闭时的蓝牙搜索处理,搜索超时等处理。该类同时使用了broadcast与handle机制,用来处理搜索的状态变化。
BluetoothEnabler.java
蓝牙功能的开启/关闭功能处理。
BluetoothEventRedirector.java
蓝牙事件转发处理,通过使用broadcast机制,在onstart里面注册了蓝牙的事件权限。
BluetoothNamePreference.java
监听蓝牙名字的变化。
BluetoothPairingDialog.java
配对时各种提示框及按键事件处理,如用户请求配对,密码输入、确认,同意等提示框。
BluetoothPairingRequest.java
配对的数据处理,为BluetoothPairingDialog.java提供数据支持以及启动;当蓝牙应用在前台并且屏幕是亮的,否则通知系统需要弹出提示框(比如蓝牙后台提示,通过notification通知提示)。
BluetoothPermissionActivity.java
允许连接的提示框处理。
BluetoothPermissionRequest.java
为BluetoothPermissionActivity.java提供数据支持,若蓝牙在前台并且屏幕是亮的,则启动BluetoothPermissionActivity.java activity,否则使用notification来提示通知。
RequestPermissionActivity.java
询问用户是否开启蓝牙及蓝牙搜索,当前蓝牙状态如果是未开启状态,则开启蓝牙及蓝牙搜索;当前蓝牙如果是开启状态,则不处理;当只针对是否开启蓝牙时,则开启蓝牙并不开启蓝牙搜索。
RequestPermissionHelperActivity.java
询问用户是否开启蓝牙及蓝牙搜索,一般由RequestPermissionActivity.java启动。
SettingsBtStatus.java
蓝牙各种状态的资源显示。
BluetoothSettings.java
蓝牙设置应用,蓝牙状态变化及设备绑定信息处理等。各个菜单处理主要是通过CachedBluetoothDevice.java来实现。主要有添加蓝牙设备,删除蓝牙设备,点击获取蓝牙设备信息,及创建具体蓝牙设备的菜单等。
ConnectSpecificProfilesActivity.java
蓝牙设备耳机、A2DP、SAP相关的设置处理。
DockService.java
蓝牙Dock相关服务,配置信息的修改,连接的修改等。
DockEventReceiver.java
接收各种dock事件,并启动DockService服务。并提供一个结束服务方法。
CachedBluetoothDevice.java
提供蓝牙设备的各种属性信息以及提供蓝牙设备连接,配对等方法。
CachedBluetoothDeviceManager.java
管理蓝牙设备,包括增加、删除蓝牙设备及通知。
LocalBluetoothManager.java
提供了一系列蓝牙方法,如开始扫描、结束扫描逻辑处理。
2. Bluetooth的app应用
路径:\packages\apps\Bluetooth\src\com\android\bluetooth
蓝牙FTP,OPP,SAP,BPP等实现,蓝牙传输及配对等实现。
3.Bluetooth免提、耳机及A2DP应用
路径:\packages\apps\Phone\src\com\android\phone\Bluetooth
主要是Bluetooth在其他应用如通话,电话本还有耳机相关的应用。
4.Bluetooth的JAVA类
路径:\frameworks\base\core\java\android\bluetooth
如BluetoothClass,BluetoothAdapter,BluetoothDevice等,Bluetooth应用就是通过这些类实现。里面有供java层使用一些类,也有对应的aidl文件联系C/C++部分的代码。
5.Bluetooth的JNI接口
路径:\frameworks\base\core\jni\android_bluetooth
主要是为Bluetooth的JAVA类提供一些底层API支持(C++实现),如headset,socket等。
6.Bluetooth的设备管理库
路径:\system\bt
kernel层(linux核心代码),是串联framework与协议栈的工具。
7.Bluetooth的kernel层
路径:\kernel\drivers\bluetooth、kernel\net\bluetooth
linux系统上Bluetooth的核心代码;具体协议实现,包括hci,hid,rfcomm,sco,SDP等协议,对各种接口的Bluetoothdevice的驱动,例如:USB接口,串口等。
参考代码路径: http://androidxref.com/kernel_3.18/ 3.18之后,谷歌暂无更新
安卓最新已经更新到kernel_4.19 ,蓝牙某些不常用的协议(如HID),可在Kernel中进行配置( CONFIG_HID_SUPPORT, CONFIG_HIDRAW)等信息,协议栈下发的数据,通过Kernel,音频数据下发到BT Chipset(蓝牙芯片),keycode按键数据下发到Input Drivers.
通话应用相关源码分析
BluetoothHandsfree.java
通话中蓝牙耳机,蓝牙免提的管理
BluetoothHeadsetService.java
提供蓝牙耳机,蓝牙免提profile
/frameworks/base/core/java/android/bluetooth
BluetoothHeadset.java
// Headset state when SCO audio is not connected
STATE_AUDIO_DISCONNECTED = 10
// Headset state when SCO audio is connecting
STATE_AUDIO_CONNECTING = 11
// Headset state when SCO audio is connected
STATE_AUDIO_CONNECTED = 12
MESSAGE_HEADSET_SERVICE_CONNECTED = 100
MESSAGE_HEADSET_SERVICE_DISCONNECTED = 101
doBind();
doUnbind();
// Initiate connection to a profile of the remote bluetooth device
connect(BluetoothDevice device);
// Initiate disconnection from a profile
disconnect(BluetoothDevice device);
//Start Bluetooth voice recognition. This methods sends the voice recognition AT command to the headset and establishes the audio connection.
startVoiceRecognition(BluetoothDevice device);
// Stop Bluetooth Voice Recognition mode, and shut down the Bluetooth audio path.
stopVoiceRecognition(BluetoothDevice device);
//Check if Bluetooth SCO audio is connected.
isAudioConnected(BluetoothDevice device);
// Get the current audio state of the Headset
getAudioState(BluetoothDevice device);
// Force SCO audio to be opened regardless any other restrictions
setForceScoAudio(boolean forced)
// Check if at least one headset's SCO audio is connected or connecting
isAudioOn()
//Initiates a connection of headset audio to the current active device
connectAudio()
//Initiates a disconnection of HFP SCO audio.
disconnectAudio()
// Initiates a SCO channel connection as a virtual voice call to the current active device Active handsfree device will be notified of incoming call and connected call.
startScoUsingVirtualVoiceCall()
//Terminates an ongoing SCO connection and the associated virtual call.
stopScoUsingVirtualVoiceCall()
// Notify Headset of phone state change.
phoneStateChanged(int numActive, int numHeld, int callState, String number, int type, String name)
// Send Headset of CLCC response
clccResponse(int index, int direction, int status, int mode, boolean mpty, String number, int type)
// Select a connected device as active.
The active device selection is per profile. An active device's purpose is profile-specific.
For example, in HFP and HSP profiles, it is the device used for phone call audio. If a remote device is not connected, it cannot be selected as active.
setActiveDevice(@Nullable BluetoothDevice device)
// Get the connected device that is active.
getActiveDevice()
// Check if in-band ringing is currently enabled. In-band ringing could be disabled during an active connection.
isInbandRingingEnabled()
// Check if in-band ringing is supported for this platform.
isInbandRingingSupported(Context context)
isEnabled()
isDisabled()
handleMessage(Message msg)
BluetoothHeadsetClientCall.java
Call state:
// Call is active
CALL_STATE_ACTIVE = 0
// Call is in held state
CALL_STATE_HELD = 1
//Outgoing call that is being dialed right now
CALL_STATE_DIALING = 2
//Outgoing call that remote party has already been alerted about
CALL_STATE_ALERTING = 3
//Incoming call that can be accepted or rejected
CALL_STATE_INCOMING = 4
//Waiting call state when there is already an active call
CALL_STATE_WAITING = 5
//Call that has been held by response and hold (see Bluetooth specification for further references).
CALL_STATE_HELD_BY_RESPONSE_AND_HOLD = 6
//Call that has been already terminated and should not be referenced as a valid call
CALL_STATE_TERMINATED = 7
BluetoothHeadsetClient.java
STATE_AUDIO_DISCONNECTED = 0
STATE_AUDIO_CONNECTING = 1
STATE_AUDIO_CONNECTED = 2
CALL_ACCEPT_NONE = 0
CALL_ACCEPT_HOLD = 1
CALL_ACCEPT_TERMINATE = 2
//Connects to remote device.
connect(BluetoothDevice device)
//Disconnects remote device
disconnect(BluetoothDevice device)
//Return the list of connected remote devices
getConnectedDevices()
//Returns state of the device
getConnectionState(BluetoothDevice device)
//Set priority of the profile,The device should already be paired.
setPriority(BluetoothDevice device, int priority)
//Get the priority of the profile.
getPriority(BluetoothDevice device)
//Starts voice recognition.
startVoiceRecognition(BluetoothDevice device)
//Stops voice recognition.
stopVoiceRecognition(BluetoothDevice device)
//Returns list of all calls in any state.
getCurrentCalls(BluetoothDevice device)
//Accepts a call
acceptCall(BluetoothDevice device, int flag)
//Holds a call.
holdCall(BluetoothDevice device)
//Rejects a call.
rejectCall(BluetoothDevice device)
//Terminates a specified call.
Works only when Extended Call Control is supported by Audio Gateway.
terminateCall(BluetoothDevice device, BluetoothHeadsetClientCall call)
//Performs explicit call transfer.
That means connect other calls and disconnect.
explicitCallTransfer(BluetoothDevice device)
//Places a call with specified number.
dial(BluetoothDevice device, String number)
//Sends DTMF code.
Possible code values : 0,1,2,3,4,5,6,7,8,9,A,B,C,D,*,#
//Get a number corresponding to last voice tag recorded on AG.
getLastVoiceTagNumber(BluetoothDevice device)
//Returns current audio state of Audio Gateway.
getAudioState(BluetoothDevice device)
//Sets whether audio routing is allowed.
setAudioRouteAllowed(BluetoothDevice device, boolean allowed)
//Returns whether audio routing is allowed.
getAudioRouteAllowed(BluetoothDevice device)
//Initiates a connection of audio channel.
It setup SCO channel with remote connected Handsfree AG device.
connectAudio(BluetoothDevice device)
//Disconnects audio channel.
It tears down the SCO channel from remote AG device.
disconnectAudio(BluetoothDevice device)
//Get Audio Gateway features
getCurrentAgFeatures(BluetoothDevice device)
isEnabled()
/packages/apps/Bluetooth/src/com/android/bluetooth/hfp
HeadsetService.java
getHeadsetService()
setHeadsetService(HeadsetService instance)
connect(BluetoothDevice device)
disconnect(BluetoothDevice device)
getConnectedDevices()
getConnectionState(BluetoothDevice device)
setPriority(BluetoothDevice device, int priority)
getPriority(BluetoothDevice device)
startVoiceRecognition(BluetoothDevice device)
stopVoiceRecognition(BluetoothDevice device)
isAudioOn()
isAudioConnected(BluetoothDevice device)
getAudioState(BluetoothDevice device)
setAudioRouteAllowed(boolean allowed)
setForceScoAudio(boolean forced)
getForceScoAudio()
getFirstConnectedAudioDevice()
setSilenceMode(BluetoothDevice device, boolean silence)
setActiveDevice(BluetoothDevice device)
getActiveDevice()
connectAudio()
connectAudio(BluetoothDevice device)
disconnectAudio()
disconnectAudio(BluetoothDevice device)
isVirtualCallStarted()
startScoUsingVirtualVoiceCall()
stopScoUsingVirtualVoiceCall()
phoneStateChanged(int numActive, int numHeld, int callState, String number, int type, String name, boolean isVirtualCall)
clccResponse(int index, int direction, int status, int mode, boolean mpty, String number, int type)
//Check if no audio mode is active
isAudioModeIdle()
//Called from {@link HeadsetStateMachine} in state machine thread when there is a audio connection state change
onAudioStateChangedFromStateMachine(BluetoothDevice device, int fromState, int toState)
broadcastActiveDevice(BluetoothDevice device)
//Check whether it is OK to accept a headset connection from a remote device
okToAcceptConnection(BluetoothDevice device)
//Checks if SCO should be connected at current system state
isScoAcceptable(BluetoothDevice device)
//Remove state machine in {@link #mStateMachines} for a {@link BluetoothDevice}
removeStateMachine(BluetoothDevice device)
/frameworks/base/core/java/android/bluetooth
BluetoothA2dp.java
//A2DP sink device is streaming music
STATE_PLAYING = 10
//A2DP sink device is NOT streaming music
STATE_NOT_PLAYING = 11
//Initiate connection to a profile of the remote Bluetooth device
connect(BluetoothDevice device)
//Initiate disconnection from a profile
disconnect(BluetoothDevice device)
getConnectedDevices()
getConnectionState(BluetoothDevice device)
//Select a connected device as active.
setActiveDevice(@Nullable BluetoothDevice device)
//Get the connected device that is active
getActiveDevice()
//Set priority of the profile
setPriority(BluetoothDevice device, int priority)
//Get the priority of the profile
getPriority(BluetoothDevice device)
//Checks if Avrcp device supports the absolute volume feature
isAvrcpAbsoluteVolumeSupported()
//Tells remote device to set an absolute volume. Only if absolute volume is supported
setAvrcpAbsoluteVolume(int volume)
//Check if A2DP profile is streaming music
isA2dpPlaying(BluetoothDevice device)
BluetoothA2dpSink.java
//Initiate connection to a profile of the remote bluetooth device.
connect(BluetoothDevice device)
//Initiate disconnection from a profile
disconnect(BluetoothDevice device)
getConnectedDevices()
getConnectionState(BluetoothDevice device)
getAudioConfig(BluetoothDevice device)
setPriority(BluetoothDevice device, int priority)
getPriority(BluetoothDevice device)
isA2dpPlaying(BluetoothDevice device)
/packages/apps/Bluetooth/src/com/android/bluetooth
A2dpService.java
getA2dpService()
setA2dpService(A2dpService instance)
connect(BluetoothDevice device)
disconnect(BluetoothDevice device)
getConnectedDevices()
okToConnect(BluetoothDevice device, boolean isOutgoingRequest)
//Get the list of devices that have state machines
getDevices()
getConnectionState(BluetoothDevice device)
storeActiveDeviceVolume()
removeActiveDevice(boolean forceStopPlayingAudio)
setSilenceMode(BluetoothDevice device, boolean silence)
setActiveDevice(BluetoothDevice device)
getActiveDevice()
isActiveDevice(BluetoothDevice device)
setPriority(BluetoothDevice device, int priority)
getPriority(BluetoothDevice device)
isAvrcpAbsoluteVolumeSupported()
setAvrcpAbsoluteVolume(int volume)
isA2dpPlaying(BluetoothDevice device)
getCodecStatus(BluetoothDevice device)
//Handle messages from native (JNI) to Java
messageFromNative(A2dpStackEvent stackEvent)
getOrCreateStateMachine(BluetoothDevice device)
updateAndBroadcastActiveDevice(BluetoothDevice device)
bondStateChanged(BluetoothDevice device, int bondState)
removeStateMachine(BluetoothDevice device)
connectionStateChanged(BluetoothDevice device, int fromState, int toState)
/packages/apps/Bluetooth/src/com/android/Bluetooth
MediaPlayerWrapper.java
isPlaybackStateReady()
isMetadataReady()
wrap(MediaController controller, Looper looper)
getPackageName()
getQueue()
getMetadata()
getCurrentMetadata()
getPlaybackState()
getActiveQueueID()
//We don't return the cached info here in order to always provide the freshest data.这里不返回缓存的信息,以便始终提供最新的数据。
getCurrentMediaData()
playItemFromQueue(long qid)
isMetadataSynced()
registerCallback(Callback callback)
unregisterCallback()
updateMediaController(MediaController newController)
sendMediaUpdate()
MediaController.Callback
onMetadataChanged(@Nullable MediaMetadata metadata)
onPlaybackStateChanged(@Nullable PlaybackState state)
onQueueChanged(@Nullable List
onSessionDestroyed()
/frameworks/base/media/java/android/media
AudioManager.java
ADJUST_RAISE = 1 //Increase the ringer volume 增加铃声音量
ADJUST_LOWER = -1 //Decrease the ringer volume 降低铃声音量
ADJUST_SAME = 0 //Maintain the previous ringer volume 保持之前的铃声音量
ADJUST_MUTE = -100 //Mute the volume 静音
ADJUST_UNMUTE = 100 //Unmute the volume 取消音量
ADJUST_TOGGLE_MUTE = 101 //Toggle the mute state 切换静音状态
//Adjusts the volume of a particular stream by one step in a direction
adjustStreamVolume(int streamType, int direction, int flags)
//Adjusts the volume of the most relevant stream调整最相关流的音量。. For example, if a call is active, it will have the highest priority regardless of if the in-call screen is showing. Another example, if music is playing in the background and a call is not active, the music stream will be adjusted.
adjustVolume(int direction, int flags)
//Adjusts the volume of the most relevant stream, or the given fallback stream.调整最相关流或给定后备流的音量。
adjustSuggestedStreamVolume(int direction, int suggestedStreamType, int flags)
//Returns the maximum volume index for a particular stream
getStreamMaxVolume(int streamType)
//Returns the minimum volume index for a particular stream
getStreamMinVolume(int streamType)
//Returns the current volume index for a particular stream
getStreamVolume(int streamType)
getLastAudibleStreamVolume(int streamType)
setStreamMute(int streamType, boolean state)
//Returns the current mute state for a particular stream
isStreamMute(int streamType)
//Sets the speakerphone on or off
setSpeakerphoneOn(boolean on)
//Checks whether the speakerphone is on or off
isSpeakerphoneOn()
SCO_AUDIO_STATE_DISCONNECTED = 0
SCO_AUDIO_STATE_CONNECTED = 1
SCO_AUDIO_STATE_CONNECTING = 2
SCO_AUDIO_STATE_ERROR = -1
//Start bluetooth SCO audio connection
startBluetoothSco()
//Start bluetooth SCO audio connection in virtual call mode.
startBluetoothScoVirtualCall()
//Stop bluetooth SCO audio connection
stopBluetoothSco()
//Request use of Bluetooth SCO headset for communications 请求使用蓝牙 SCO 耳机进行通信
setBluetoothScoOn(boolean on)
//Checks whether communications use Bluetooth SCO 检查通信是否使用蓝牙 SCO
isBluetoothScoOn()
//Checks whether a Bluetooth A2DP audio peripheral is connected or not 检查蓝牙A2DP音频外设是否连接
isBluetoothA2dpOn()
//Checks whether a wired headset is connected or not.检查有线耳机是否连接。
isWiredHeadsetOn()
//Sets the microphone mute on or off 设置麦克风静音开或关
setMicrophoneMute(boolean on)
//Checks whether the microphone mute is on or off 检查麦克风静音是打开还是关闭
isMicrophoneMute()
//Sets the audio mode 设置音频模式
setMode(int mode)
//Returns the current audio mode 返回当前音频模式
getMode()
AUDIOFOCUS_NONE = 0
AUDIOFOCUS_GAIN = 1
AUDIOFOCUS_GAIN_TRANSIENT = 2
AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK = 3
AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE = 4
AUDIOFOCUS_LOSS = -1 * AUDIOFOCUS_GAIN
AUDIOFOCUS_LOSS_TRANSIENT = -1 * AUDIOFOCUS_GAIN_TRANSIENT
AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK =
-1 * AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
MSSG_FOCUS_CHANGE = 0
MSSG_RECORDING_CONFIG_CHANGE = 1
MSSG_PLAYBACK_CONFIG_CHANGE = 2
registerAudioFocusRequest(@NonNull AudioFocusRequest afr)
unregisterAudioFocusRequest(OnAudioFocusChangeListener l)
AUDIOFOCUS_REQUEST_FAILED = 0
AUDIOFOCUS_REQUEST_GRANTED = 1
AUDIOFOCUS_REQUEST_DELAYED = 2
AUDIOFOCUS_REQUEST_WAITING_FOR_EXT_POLICY = 100
requestAudioFocus(OnAudioFocusChangeListener l, int streamType, int durationHint)
requestAudioFocus(@NonNull AudioFocusRequest focusRequest)
abandonAudioFocusRequest(@NonNull AudioFocusRequest focusRequest)
requestAudioFocusForCall(int streamType, int durationHint)
setFocusRequestResult(@NonNull AudioFocusInfo afi, @FocusRequestResult int requestResult, @NonNull AudioPolicy ap)
abandonAudioFocusForCall()
abandonAudioFocus(OnAudioFocusChangeListener l)
abandonAudioFocus(OnAudioFocusChangeListener l, AudioAttributes aa)
registerAudioPlaybackCallback(@NonNull AudioPlaybackCallback cb, Handler handler)
unregisterAudioPlaybackCallback(@NonNull AudioPlaybackCallback cb)
avrcpSupportsAbsoluteVolume(String address, boolean support)
isSilentMode()
getDevicesForStream(int streamType)
setWiredDeviceConnectionState(int type, int state, String address, String name)
setVolumeController(IVolumeController controller) stopBluetoothSco
/frameworks/av/services/audiopolicy/managerdefault
AudioPolicyManager.cpp
AudioPolicyManager.h
startOutput()
/frameworks/av/services/audiopolicy/common/managerdefinitions/src
AudioOutputDescriptor.cpp
changeRefCount()
/frameworks/base/services/core/java/com/android/server/media
MediaSessionService.java
onSessionPlaystateChanged(MediaSessionRecord record, int oldState, int newState)
onSessionPlaybackTypeChanged(MediaSessionRecord record)
onMediaButtonReceiverChanged(MediaSessionRecord record)
三、Bluetooth总结
整体框架
相关名词解释
HAL: Hardware Abstraction Layer
BTIF: Bluetooth Interface
BTA: Bluetooth Application
BTU: Bluetooth Upper layer
BTE: Bluetooth Embedded layer
BTM: Bluetooth Device Manager
CO: Call out
CI: Call in
HF: Hands free Profile
HH: HID Host Profile
HL: Health Device Profile
AV: Audio\Video
AG: Audio Gateway
AR: Audio/Video Registration
GATTC: GATT Client
GATTS: GATT Server
BLE: Bluetooth Low Energy
Android Bluetooth框架结构图
Applications:
Android蓝牙应用程序,使用蓝牙API的程序;
Framework:
Bluetooth Framework层的作用只是连接Bluetooth Service,为其它应用提供使用蓝牙的接口,起连接上下层的作用,没有太多的逻辑,例如平时使用的Bluetooth Adapter,Bluetooth Device,Bluetooth Socket等;
代码路径:frameworks/base/core/java/android/bluetooth/
Framework中蓝牙主要类:
BluetoothAdapter:代表本地蓝牙适配器,是所有蓝牙交互的入口。通过它可以搜索其它蓝牙设备,查询已经配对的设备列表,通过已知的MAC地址创建BluetoothDevice,创建BluetoothServerSocket监听来自其它设备的通信。
BluetoothDevice:代表了一个远端的蓝牙设备,使用它请求远端蓝牙设备连接或者获取远端蓝牙设备的名称、地址、种类和绑定状态。 (其信息是封装在 bluetoothsocket 中) 。
BluetoothSocket:代表了一个蓝牙套接字的接口,它是应用程序通过输入、输出流与其他蓝牙设备通信的连接点。
BluetoothServerSocket:代表打开服务连接来监听可能到来的连接请求 (属于server 端) ,为了连接两个蓝牙设备必须有一个设备作为服务器打开一个服务套接字。 当远端设备发起连 接连接请求的时候,并且已经连接到了的时候,Blueboothserversocket 类将会返回一个bluetoothsocket。
BluetoothClass:描述了一个设备的特性(profile)或该设备上的蓝牙大致可以提供哪些服务(service),但不可信。比如,设备是一个电话、计算机或手持设备。Blueboothserversocket 设备可以提供audio/telephony服务等。可以用它来进行一些UI上的提示。
BluetoothProfile:蓝牙协议
Framework中声明了BluetoothProfile接口类。蓝牙所有Profile都封装了对应的类,并且实现了BluetoothProfile接口。
Bluetooth Service:
主要功能是负责蓝牙状态的管理,连接BlueDroid,提供各种蓝牙服务。其中btAdapter主要提供蓝牙的基本操作,比如enable,disable,discovery, pair, unpair,createRfcomm等,其他的各个Profile提供自身独立的服务,除了OPP和PABP自成一体外,因为OPP和PABP实质都是文件传输,涉及到UI交互操作等,会作为两个相对独立的Service存在。
代码路径:packages\apps\Bluetooth\src\com\android\bluetooth\
Bluetooth Service与BlueDroid通过JNI接口交互,Bluetooth Service在开始时加载BlueDroid库(bluetooth.default.so),使用BlueDroid提供的操作接口,同时在调用BlueDroid接口提供的init函数时,传递回调结构体BlueDroid。
Profile对应的JNI
代码路径:packages\apps\Bluetooth\jni\
BlueDroid:
蓝牙协议栈,提供所有蓝牙的实际操作,开关蓝牙,蓝牙的管理,搜索管理,链路管理,各种profile的实现,包括HCI,ACL,SCO,L2CAP,各种profile等。这里将BlueDroid分为三部分:
I.BTIF(Bluetooth Interface):
代码路径:system/bt/btif/
BTIF:Bluetooth Application task(BTA)和JNI层之间从当媒介。对上层JNI提供所有profile功能性的接口。该层还存在Bluetooth Interface Instance,所有Profile操作接口注册在其中(GAP, AV, DM, PAN, HF,HH, HL, Storage, Sockets)。Client应用通过Instance来操作Profile。
II.BTA(Bluetooth Application):
代码路径:system/bt/bta/
BTA:蓝牙应用层。指bluedroid中对各个profile实现和处理。上层下来的请求经过BTA层,通过消息发送的方式将请求传到BTA层中处理。实现了各种Profile状态机,用户通过驱动状态机来操作Profile。
Profile状态机包含以下几个主要组成部分:
BTA_profilexx_act.c => 包含对应Profile的“Action”函数,一般来说由Profile状态机调用。
BTA_profilexx_api.c => 对应Profile的API的具体实现。通常它们是提供给用户使用,完成usecase的函数和回调。
BTA_profilexx_ci.c => 对应Profile的“call-in”函数的实现(供Profile以外的模块调用)。
BTA_profilexx_co.c => 对应Profile的“call-out”函数的实现(调用Profile以外的模块)。
BTA_profilexx_main.c => 对应Profile的状态机和处理协议栈上传消息的handler的具体实现。主要负责维护Profile状态的变化及其引起的“Action”。
III.Stack:
代码路径:system/bt/stack/
实现所有蓝牙底层的操作,其中还要分为BTM(Bluetooth manager),BTU(Bluetooth Upper Layer)等。
BlueDroid 代码框架
BTIF:
1. Co:call-out(bta的调出函数)
2. Src:
Bluetooth.c: 蓝牙HAL实现
btif_av.c: 蓝牙av实现
btif_config.c: 存储在本地的BT适配器和远程设备属性(xml)
btif_core.c: 包含HAL和BTE接口之间的核心功能函数
btif_dm.c: 包含设备管理(DM)相关功能
btif_hf.c: 免提模式蓝牙接口
btif_hh.c: HID主机配置文件的蓝牙接口
btif_hl.c: 医疗设备规范的蓝牙接口
btif_media_task.c: 这是多媒体模块的BTIF系统。它包含任务的实现av,HS和HF模式音频和视频处理
btif_pan.c: PAN模式蓝牙接口
btif_profile_queue.c: 蓝牙远程设备的连接队列的实现。
btif_rc.c: 蓝牙AVRC实现
btif_sm.c: 通用BTIF状态机的API
btif_sock.c: 蓝牙Socket接口
btif_sock_rfc.c: 虚拟串口模式蓝牙接口
btif_sock_sdp.c: 服务发现
btif_sock_thread.c: socket select thread创建socket通信的线程
btif_sock_util.c: socket操作的一些相关函数
btif_storage.c: 存储在本地的BT适配器和远程设备属性(xml)
btif_util.c: 其它辅助功能
BTA:
1. ag(audio gateway): 蓝牙音频网关的实现
2. ar(audio/video registration): 音频/视频注册模块的实现
3. av(advanced audio/video): 更先进的音频/视频实现
4. dm(device manager): bta设备管理实现
5. fs(file system): bta文件系统编译时间可配置常数及回调函数
6. gatt: gatt客户端的主要功能和状态机
7. hh(HID host): 人性化接口设备(HID),连接鼠标键盘
8. hl(Health): 健康设备模式的主要功能函数和状态机
9. jv(Java):
10.pan(蓝牙个人局域网): pan主要功能实现和状态机
11.pb(phone book): 电话薄访问服务器的私人文件
12.sys(system): bta系统管理的实现
Stack:
1. a2dp:
a2dp_api.c:高级音频传输模式OMMON的API(支持A2DP)
a2dp_sbc.c:实用功能,用于帮助建立和解析SBC编解码信息单元与媒体有效载荷。
2. avct:
avct_api.c: 音频/视频控制传输协议的API
avct_ccb.c: 操作AVCTP连接控制块的函数
avct_l2c.c: AVCTP模块接口至L2CAP
avct_lcb.c: 此模块包含链路控制状态机和操作链路控制块函数
avct_lcb_act.c: 链路控制状态机的行为函数
3. avdt:
avdt_ad.c: 此模块包含AVDTP适配层(adaption)
avdt_api.c: 音频/视频分发传输协议的API
avdt_ccb.c: 通道控制块状态机和操作该通道控制块的功能函数
avdt_ccb_act.c: 与通道控制块状态机相关的操作功能函数
avdt_l2c.c: AVDTP适配层模块接口L2CAP
avdt_msg.c: 用于分析和生成AVDTP信令消息的功能
avdt_scb.c: 流控制块及其操作函数
avdt_scb_act.c: 流控制块状态机相关的操作功能函数
4. avrc:
avrc_api.c: AVRCP必须命令接口API
avrc_opt.c: AVRCP可选命令接口API
avrc_sdp.c: AVRCP SDP相关的功能
5. bnep:
bnep_api.c: BNEP API
bnep_main.c: BNEP 主要功能函
bnep_utils.c: BNEP实用功能函数
6. btm:
btm_acl.c: 处理ACL连接,保持和嗅探模式,支持数据包类型
btm_ble.c: BLE设备的控制及安全功能
btm_ble_addr.c: BLE地址管理
btm_ble_bgconn.c: BLE白名单的操作
btm_ble_gap.c: BLE GAP
btm_dev.c: 蓝牙设备管理
btm_devctl.c: 处理BTM接口功能,包括休息,HCl缓冲大小等
btm_inq.c: 处理查询(handle inquiries),包括设置发现模式,控制基带的方式, 维护 查询响应的小型数据库
btm_main.c: BTM控制块的定义
btm_pm.c: 管理ACL链路模式功能(活跃,持有,停和嗅探模式)
btm_sco.c: 处理SCO连接,连接,断开连接,改变支持数据包类型。
btm_sec.c: 蓝牙安全管理器功能
7. btu:
btu_hcif.c: HCI传输接口,(事件接受至l2cap等事件处理程序,命令传输)
btu_init.c: 加载和关闭核心协议栈组件的例程
btu_task.c: 蓝牙上层处理循环,RFCOMM L2CAP,SDP和BTIF 为一体GKI任务。他们之 间的这种btu_task切换
8. gatt:
att_protocol.c: ATT协议功能
gatt_api.c: GATT接口API
gatt_attr.c: GATT服务器属性访问请求处理函数。
gatt_auth.c: GATT认证处理功能
gatt_cl.c: GATT客户端功能函数
gatt_db.c: GATT数据库的建立和查询
gatt_main.c: 主要的ATT功能函数
gatt_sr.c; GATT服务器功能函数
gatt_utils.c: GATT实用函数
9. hcic:
Hciblecmds.c: HCIC单元格式和发送HCI命令
Hcicmds.c: HCIC 单元格式化和发送 HCI 命令的功能
10. hid:
hidh_api.c: HID主机API
hidh_conn.c: 连接接口功能函数
11. l2cap:
l2c_api.c: L2CAP接口API
l2c_ble.c: 与ble管理相关的功能函数
l2c_csm.c: L2CAP信道状态机(channel state machine)
l2c_fcr.c: 流量控制和重传(Flow Control and retransmissions)
l2c_link.c: 与链路管理相关
l2c_main.c: L2CAP入口点
l2c_ucd.c: L2CAP UCD 代码
l2c_utils.c: L2cap实用函数
12. mcap(多通道适配协议):
mca_api.c: Multi-Channel Adaptation Protocol 接口API
mca_cact.c: 控制通道操作功能函数的实现
mca_csm.c: 控制通道的状态机的实现。
mca_dact.c: 数据通道功能的实现
mca_dsm.c: 数据信道状态机
mca_l2c.c: MCAP在L2CAP接口上的实现
mca_main.c: MCAP主控制块的实现
13. pan:
pan_api.c: pan规范接口api
pan_main.c: 支持pan命令和事件的功能函数
pan_utils.c: 支持 pan 配置文件的主要功能命令和事件
14. rfcomm:
port_api.c: 串行端口API
port_rfc.c: 端口仿真实体和RFCOMM通信
port_utils.c: 端口仿真实体函数
rfc_l2cap_if.c: L2CAP接口函数
rfc_mx_fsm.c:: RFCOMM单元的多路通道的状态机和操作例程
rfc_port_fsm.c: RFCOMM单元的端口的状态机和操作例程
rfc_port_if.c: 供RFCOMM之上运行的应用程序调用
rfc_ts_frames.c: 发送TS 07.10帧
rfc_utils.c: 使用的RFCOMM单元的实用函数
15. sdp:
sdp_api.c: SDP接口API
sdp_db.c: 处理数据库函数
sdp_discovery.c: SDP发现功能
sdp_main.c: SDP主函数
sdp_server.c: SDP服务器功能,主要是处理客户端请求
sdp_utils.c: SDP实用函数
16. smp:
Aes.c: AES实现,使用唯一的8位字节操作加密状态
smp_act.c: SMP鉴权配对密钥等信息
smp_api.c: SMP的应用程序接口
smp_cmac.c: AES128 CMAC算法实现
smp_keys.c: 安全管理器协议实用程序功能
smp_l2c.c: SMP l2cap接口上的实现
smp_main.c: SMP主函数
smp_utils.c: SMP L2Cap实用函数
HCI:
bt_hci_bdroid.c: 蓝牙主机/控制器接口库实现
bt_hw.c: 蓝牙供应商提供的回调函数
bt_utils.c: 其它辅助功能
Btsnoop.c: 生成一个蓝牙窥探文件
hci_h4.c: HCI传输发送/接收
hci_mct.c: HCI多通道传输
Lpm.c: 低功耗模式实现
Userial.c: 串行端口打开/读取/写入/关闭实现
userial_mct.c: 多通道打开/读/写/关闭功能
Utils.c: 帮助功能函数
Main:
bte_conf.c: 根据目前在conf文件条目进行运行时模块配置
bte_init.c: 包含了初始化堆栈组件的例程,在BTU任务开始之前调用
bte_logmsg.c: BTE日志信息封装
bte_main.c: BTE核心堆栈初始化和关闭代码
bte_version.c: BTE版本