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);
}
}
}