android蓝牙at指令
‘壹’ Android 发送AT指令
1、hardware\ril\reference-ril\Reference-ril.c 中 onRequest() 处理RIL_REQUEST_DIAL 时会 调用requestDial();
2、requestDial()中转换RIL_REQUEST_DIAL 请求为AT指令;
3、通过at_send_command()下发;
4、经过at_send_command_full,at_send_command_full_nolock ,writeline()写到设备中。
‘贰’ Android蓝牙串口调试程序问题:这个程序连接蓝牙模块后,蓝牙模块的上的灯变闪烁为一直亮,为什么
现在市面上常用的蓝牙模块就是连接以后指示灯由闪烁变为常亮,表示已连接。
‘叁’ android怎么在代码中执行AT指令
AT指令集是从终端设备(Terminal Equipment,TE)或数据终端设备(Data Terminal Equipment,DTE)向终端适配器(Terminal Adapter,TA)或数据电路终端设备(Data Circuit Terminal Equipment,DCE)发送的。
其对所传输的数据包大小有定义:即对于AT指令的发送,除AT两个字符外,最多可以接收1056个字符的长度(包括最后的空字符)。
每个AT命令行中只能包含一条AT指令;对于由终端设备主动向PC端报告的URC指示或者response响应,也要求一行最多有一个,不允许上报的一行中有多条指示或者响应。AT指令以回车作为结尾,响应或上报以回车换行为结尾。
‘肆’ android 蓝牙信号强度值怎么转换成距离
30、查询蓝牙设备
指令 响应 参数
Param1:蓝牙地址
Param2:设备类 AT+INQ +INQ: <Param1>,<Param2>,<Param3>,
OK
Param3:RSSI 信号强度
举例说明 1:
at+init\r\n ——初始化 SPP库(不能重复初始化) OK
at+iac=9e8b33\r\n——查询任意访问码的历胡蓝牙设备 OK
at+class=0\r\n ——查询各种蓝牙设备类
at+inqm=1,9,48\r\n—肢搭拦—查询模式:带 RSSI信号强度指示,超过 9个蓝牙枝昌设备响应则终止查询,设定超 时
为 48x1.28=61.44秒。
At+inq\r\n ——查询周边蓝牙设备
+INQ:2:72:D2224,3E0104,FFBC
+INQ:1234:56:0,1F1F,FFC1
+INQ:1234:56:0,1F1F,FFC0
+INQ:1234:56:0,1F1F,FFC1
+INQ:2:72:D2224,3F0104,FFAD
+INQ:1234:56:0,1F1F,FFBE
+INQ:1234:56:0,1F1F,FFC2
+INQ:1234:56:0,1F1F,FFBE
+INQ:2:72:D2224,3F0104,FFBC OK
‘伍’ android添加蓝牙电量
1. HFP 命令AT+IPHONEACCEV
描述:报告耳机的状态变更
发起者:耳机
格式:AT+IPHONEACCEV=[Number of key/value pairs ],[key1 ],[val1 ],[key2
],[val2 ],…
参数:
Number of key/value pairs :接下来参数的数量
key:被报告状态变化的类型
1 =电量等级
2 =暂停状态
val:更改的值
Battery events:0-9之间数字的字符串 A
string value between ‘0’ and ‘9’.
Dock state: 0 = undocked, 1 = docked.
Example:AT+IPHONEACCEV=1,1,3
2.android framework 修改点
packages/apps/Bluetooth/src/com/android/bluetooth/hfp/HeadsetStateMachine.java
BluetoothAssignedNumbers.APPLE可以随便用哪个公司的,但注册广播时要一致就行。
static {
classInitNative();
型乱磨 VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID = new HashMap();
VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID.put("+XEVENT",BluetoothAssignedNumbers.PLANTRONICS);
VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID.put("+ANDROID",BluetoothAssignedNumbers.GOOGLE); 陪绝 +VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID.put("+XAPL",BluetoothAssignedNumbers.APPLE);
+VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID.put("+IPHONEACCEV",BluetoothAssignedNumbers.APPLE);
}
获取蓝牙电量需要向蓝牙发送回复的at命令:
private (String atString) {
log("processVendorSpecificAt - atString = " + atString);
// Currently we accept only SET type commands.
int indexOfEqual = atString.indexOf("=");
if (indexOfEqual == -1) {
Log.e(TAG, "processVendorSpecificAt: command type error in " +atString);
return false;
}
String command = atString.substring(0, indexOfEqual);
Integer companyId = VENDOR_SPECIFIC_AT_COMMAND_COMPANY_ID.get(command);
if (companyId == null) {
Log.e(TAG, "processVendorSpecificAt: unsupported command: " +atString);
卜斗 return false;
}
String arg = atString.substring(indexOfEqual + 1);
if (arg.startsWith("?")) {
Log.e(TAG, "processVendorSpecificAt: command type error in " +atString);
return false;
}
Object[] args = generateArgs(arg);
+ if ("+XAPL".equals(command)) {
+ processAtXapl(args);
+ }
(command,
companyId,
BluetoothHeadset.AT_CMD_TYPE_SET,
args,
mCurrentDevice);
atResponseCodeNative(HeadsetHalConstants.AT_RESPONSE_OK, 0);
return true;
}
/**
* Process AT+XAPL AT command
* @param args command arguments after theequal sign
* @param device Remote device that hassent this command
*/
private void processAtXapl(Object[] args){
if (args.length != 2) {
Log.w(TAG, "processAtXapl()args length must be 2: " + String.valueOf(args.length));
return;
}
if (!(args[0] instanceof String) ||!(args[1] instanceof Integer)) {
Log.w(TAG, "processAtXapl()argument types not match");
return;
}
// feature = 2 indicates that wesupport battery level reporting only
Log.d("tsq77","+XAPL=iPhone,");
atResponseStringNative("+XAPL=iPhone," + String.valueOf(2));
}
2.上层app监听广播获取电量
packages/apps/Settings/src/com/android/settings/bluetooth/BluetoothSettings.java
在settings中的蓝牙界面中注册广播,然后把电量显示出来。
//aaron
IntentFilter filter=new IntentFilter();
filter.addAction(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT);
//filter.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY+"."+BluetoothAssignedNumbers.
APPLE);
filter.addCategory(BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_COMPANY_ID_CATEGORY+"."+BluetoothAssignedNumbers.
APPLE);
getActivity().registerReceiver(mIntentReceiver,filter);
Log.i("a", "registerReceiver ");
//end
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothHeadset.ACTION_VENDOR_SPECIFIC_HEADSET_EVENT)) {
Log.i("a","intent "+intent);
String command=intent.getStringExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_CMD);
if("+IPHONEACCEV".equals(command)) {
Object[] args = (Object[])intent.getSerializableExtra(BluetoothHeadset.EXTRA_VENDOR_SPECIFIC_HEADSET_EVENT_ARGS);
if (args.length >= 3&& args[0] instanceof Integer &&((Integer)args[0])*2+1<=args.length) {
for (inti=0;i<((Integer)args[0]);i++) {
if(!(args[i*2+1] instanceof Integer) || !(args[i*2+2] instanceof Integer)) {
continue;
}
if(args[i*2+1].equals(1)) {
floatlevel=(((Integer)args[i*2+2])+1)/10.0f;//获取的电量百分比
break;
}
}
}
}
}
}
};
‘陆’ android_studio手机蓝牙串口通信源代码
初涉android的蓝牙操作,按照固定MAC地址连接获取Device时,程序始终是异常终止,查了好多天代码都没查出原因。今天改了一下API版本,突然就成功连接了。总结之后发现果然是个坑爹之极的错误。
为了这种错误拼命查原因浪费大把时间是非常不值得的,但是问题不解决更是揪心。可惜我网络了那么多,都没有给出确切原因。今天特此mark,希望后来者遇到这个问题的时候能轻松解决。
下面是我的连接过程,中间崩溃原因及解决办法。
1:用AT指令获得蓝牙串口的MAC地址,地址是简写的,按照常理猜测可得标准格式。
2:开一个String adress= "************" //MAC地址, String MY_UUID= "************"//UUID根据通信而定,网上都有。
3:取得本地Adapter用getDefaultAdapter(); 远程的则用getRemoteDevice(adress); 之后便可用UUID开socket进行通信。
如果中途各种在getRemoteDevice处崩溃,大家可以查看一下当前的API版本,如果是2.1或以下版本的话,便能确定是API版本问题,只要换成2.2或者以上就都可以正常运行了~ 这么坑爹的错误的确很为难初学者。 唉·········· 为这种小trick浪费很多时间真是难过。
(另外有个重要地方,别忘了给manifest里面加以下两个蓝牙操作权限哦~)
<uses-permissionandroid:name="android.permission.BLUETOOTH"></uses-permission>
<uses-permissionandroid:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>
=null;
=null;
privateOutputStreamoutStream=null;
privateInputStreaminStream=null;
privatestaticfinalUUIDMY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//这条是蓝牙串口通用的UUID,不要更改
privatestaticStringaddress="00:12:02:22:06:61";//<==要连接的蓝牙设备MAC地址
/*获得通信线路过程*/
/*1:获取本地BlueToothAdapter*/
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter==null)
{
Toast.makeText(this,"Bluetoothisnotavailable.",Toast.LENGTH_LONG).show();
finish();
return;
}
if(!mBluetoothAdapter.isEnabled())
{
Toast.makeText(this,"-runthisprogram.",Toast.LENGTH_LONG).show();
finish();
return;
}
/*2:获取远程BlueToothDevice*/
BluetoothDevicedevice=mBluetoothAdapter.getRemoteDevice(address);
if(mBluetoothAdapter==null)
{
Toast.makeText(this,"Can'tgetremotedevice.",Toast.LENGTH_LONG).show();
finish();
return;
}
/*3:获得Socket*/
try{
btSocket=device.(MY_UUID);
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Socketcreationfailed.",e);
}
/*4:取消discovered节省资源*/
mBluetoothAdapter.cancelDiscovery();
/*5:连接*/
try{
btSocket.connect();
Log.e(TAG,"ONRESUME:BTconnectionestablished,datatransferlinkopen.");
}catch(IOExceptione){
try{
btSocket.close();
}catch(IOExceptione2){
Log.e(TAG,"ONRESUME:",e2);
}
}
/*此时可以通信了,放在任意函数中*/
/*try{
outStream=btSocket.getOutputStream();
inStream=btSocket.getInputStream();//可在TextView里显示
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Outputstreamcreationfailed.",e);
}
Stringmessage="1";
byte[]msgBuffer=message.getBytes();
try{
outStream.write(msgBuffer);
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);
}
*/
packagecom.example.seed2;
importandroid.app.Activity;
importandroid.app.AlertDialog;
importandroid.app.Dialog;
importandroid.os.Bundle;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.UUID;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothDevice;
importandroid.bluetooth.BluetoothSocket;
importandroid.content.DialogInterface;
importandroid.util.Log;
importandroid.view.KeyEvent;
importandroid.widget.Toast;
{
privatestaticfinalStringTAG="BluetoothTest";
=null;
=null;
privateOutputStreamoutStream=null;
privateInputStreaminStream=null;
privateVerticalSeekBarvskb=null;
privatestaticfinalUUIDMY_UUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//这条是蓝牙串口通用的UUID,不要更改
privatestaticStringaddress="00:12:02:22:06:61";//<==要连接的蓝牙设备MAC地址
/**.*/
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.vskb=(VerticalSeekBar)super.findViewById(R.id.mskb);
this.vskb.setOnSeekBarChangeListener(newOnSeekBarChangeListenerX());
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter==null)
{
Toast.makeText(this,"Bluetoothisnotavailable.",Toast.LENGTH_LONG).show();
finish();
return;
}
if(!mBluetoothAdapter.isEnabled())
{
Toast.makeText(this,"-runthisprogram.",Toast.LENGTH_LONG).show();
finish();
return;
}
}
.OnSeekBarChangeListener{
publicvoidonProgressChanged(VerticalSeekBarseekBar,intprogress,booleanfromUser){
//Main.this.clue.setText(seekBar.getProgress());
/*Stringmessage;
byte[]msgBuffer;
try{
outStream=btSocket.getOutputStream();
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);
}
message=Integer.toString(seekBar.getProgress());
msgBuffer=message.getBytes();
try{
outStream.write(msgBuffer);
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);
}*/
}
(VerticalSeekBarseekBar){
Stringmessage;
byte[]msgBuffer;
try{
outStream=btSocket.getOutputStream();
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);
}
message=Integer.toString(seekBar.getProgress());
msgBuffer=message.getBytes();
try{
outStream.write(msgBuffer);
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);
}
}
publicvoidonStopTrackingTouch(VerticalSeekBarseekBar){
Stringmessage;
byte[]msgBuffer;
try{
outStream=btSocket.getOutputStream();
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:OutputStreamcreationfailed.",e);
}
message=Integer.toString(seekBar.getProgress());
msgBuffer=message.getBytes();
try{
outStream.write(msgBuffer);
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);
}
}
}
@Override
publicvoidonStart()
{
super.onStart();
}
@Override
publicvoidonResume()
{
super.onResume();
BluetoothDevicedevice=mBluetoothAdapter.getRemoteDevice(address);
try{
btSocket=device.(MY_UUID);
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Socketcreationfailed.",e);
}
mBluetoothAdapter.cancelDiscovery();
try{
btSocket.connect();
Log.e(TAG,"ONRESUME:BTconnectionestablished,datatransferlinkopen.");
}catch(IOExceptione){
try{
btSocket.close();
}catch(IOExceptione2){
Log.e(TAG,"ONRESUME:",e2);
}
}
//.
/*try{
outStream=btSocket.getOutputStream();
inStream=btSocket.getInputStream();
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Outputstreamcreationfailed.",e);
}
Stringmessage="read";
byte[]msgBuffer=message.getBytes();
try{
outStream.write(msgBuffer);
}catch(IOExceptione){
Log.e(TAG,"ONRESUME:Exceptionringwrite.",e);
}
intret=-1;
while(ret!=-1)
{
try{
ret=inStream.read();
}catch(IOExceptione)
{
e.printStackTrace();
}
}
*/
}
@Override
下面附上Android蓝牙操作中用固定MAC地址传输信息的模板,通用搜索模式日后再补删模板:
通用搜索模式代码模板:
简洁简洁方式1 demo
作用: 用VerticalSeekBar控制一个 LED屏幕的亮暗。
直接上码咯~
‘柒’ android 怎么通过蓝牙向一个硬件发送AT指令
将16进制的字符串转换成bytes,通过hexstring2bytes转换,从而发送指令。
‘捌’ Android平台到底能不能通过串口发送AT指令呢,急!!!
AT命令(Attention)在手机中,用于对modem(也就是移动模块)通过串口命令进行操作,处理与语音电话、短信和数据。
关于AT命令:
Android系统与AT命令
对于智能手机,AP和BP分离的情况,在AP上的系统通过串口和BP通信是个不错方式。在Android的源码中有一个内部包com.android.internal.telephony中有对AT命令的封装和解析,但这种internal的包开发者不能调用的SDK部分,可以用来封装ROM。这说明Android对AT command的方式是支持的。
对于Android如何调用AT command
用root登录命令行,直接对串口进行操作,如echo -e "AT " > /dev/smd0
具体的串口,不同设备会有不同,甚至不一定会提供。这种方式,开发者是可以调用的,通过Runtime.exec直接执行命令行命令,但要求是root,例如echo -e "ATD123456789; " > /dev/smd0,拨打123456789的号码。
目前最新的AT命令标准发布与2014.6.27,似乎还活得挺滋润的。但是给出的keywords是UMTS, GSM, command, terminal, LTE这说明CDMA确实很可能不是采用AT命令的方式。
‘玖’ android怎么通过蓝牙向一个硬件发送AT指令
将16进制的字符串转换成bytes,通过hexstring2bytes转换而不能直接用getbytes
String string = "41542B50494F392C310D";
mmOutStream.write(string.getBytes());
读取inputsteam中的
?
Log.d("example", "do read");
不执行,完整代码如下:
?
/迟纯**
* This thread runs ring a connection with a remote device. It handles all
* incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
Log.d("example", "do read");
try {
/如冲/ Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes,
-1, buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
/渣旦歼/ Start the service over to restart listening mode
BluetoothChatService.this.start();
break;
}
}
}
/**
* Write to the connected OutStream.
*
* @param buffer
* The bytes to write
*/
public void write(byte[] buffer) {
String string = "41542B50494F392C310D";
try {
mmOutStream.write(string.getBytes());
// Share the sent message back to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1,
buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception ring write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}