调试android SDK附带的示例BluetoothChat。在BluetoothChat的基础上实现手机蓝牙和HC-6蓝牙模块建立连接,借此通道和PC上的串口调试工具通信——实现蓝牙透传功能。
(1)调试BluetoothChat时,不能和HC-6蓝牙模块建立连接,折腾了几个小时发现是UUID的问题。
// BluetoothChat里的UUID没有用,改为BTClient里的UUID才OK
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//"fa87c0d0-afac-11de-8a39-0800200c9a66");
(2)发现AcceptThread中BluetoothServerSocket.accept()方法出现异常,但没有弄明白异常的根源在哪里。实现蓝牙透传功能不需要一个Server程序在等待,所以就不用创建Server线程,就不会执行到accept()方法。
// Start the thread to listen on a BluetoothServerSocket
/*if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}*/
(3)发现HC-6蓝牙模块有一根线和PCB板没有连上,导致手机程序无法读到数据。
(4)往蓝牙模块发送请求APDU时,需要将ASCII字符串转换为十六进制的字节数组。
// ASCII字符串转换为十六进制字节数组
private byte[] convert2HexArray(String apdu)
{
int len = apdu.length() / 2;
char[] chars = apdu.toCharArray();
String[] hexes = new String[len];
byte[] bytes = new byte[len];
for (int i = 0, j = 0; j < len; i = i + 2, j++)
{
hexes[j] = "" + chars[i] + chars[i + 1];
bytes[j] = (byte)Integer.parseInt(hexes[j],16);
}
return bytes;
}
// 在程序中调用conver2HexArray方法
byte[] send = this.convert2HexArray(message);
mChatService.write(send);
(5)接收来自蓝牙模块的响应APDU时,需要将十六进制的字节数组转换为ASCII字符串,然后才可以显示。
// 十六进制字节数组转换为ASCII字符串,指定元素个数
public String bytes2HexString(byte[] b, int count) {
String ret = "";
for (int i = 0; i < count; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
// 十六进制字节数组转换为ASCII字符串
public String bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
// 在程序中调用bytes2HexString方法
byte[] readBuf = (byte[]) msg.obj;
String readMsg = bytes2HexString(readBuf,msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMsg);