我的朋友有一些奇怪的设备,它没有UUID,但我想通过蓝牙从中读取数据。所以我创造了这样的东西
class ReadData extends Thread {
byte[] buffer = new byte[1024];
ByteArrayInputStream arrayData;
OutputStream outputData;
InputStream inputData;
InputStreamReader inputDataReader;
int bytes;
MessageDigest md = null;
ReadData(BluetoothSocket bluetoothSocket) throws IOException {
outputData = bluetoothSocket.getOutputStream();
inputData = bluetoothSocket.getInputStream();
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
//byte [] bytesToSend = {0x0F, 'T', 0x01, 0x08, 0x00, 0x02, 0x05, 0x10, 0x06, 0x02, 0x00, 0x01, 0x09, 0x00, 0x00, md.digest()[0], md.digest()[1], 0x0D };
//byte [] bytesToSend = {0x0F, 'R', md.digest()[0], md.digest()[1], 0x0D };
//byte [] bytesToSend = {0x0F, 'S', md.digest()[0], md.digest()[1], 0x0D };
byte [] bytesToSend = {0x0F, 'A', md.digest()[0], md.digest()[1], 0x0D };
Log.i("BYTES TO SEND", "" + bytesToSend);
outputData.write(bytesToSend);
Log.i("DATA_TO_SEND", outputData.toString());
}
public void run(){
while(true){
try {
bytes = inputData.read(buffer, 0, inputData.available());
inputDataReader = new InputStreamReader(inputData);
Log.i("RETRIVED_DATA", "" + inputDataReader.read());
outputData.close();
inputData.close();
} catch( IOException e){
} catch ( IllegalStateException e){
Log.e("ERROR_APEARED", "" + bytes);
}
}
}
这就是我如何获得蓝牙套接字以及如何将其传递给ReadData的构造函数:
BluetoothAdapter bluetoothAdapter = null;
BluetoothSocket clientSocket = null;
BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(devices.get(i).getAddress());
Method m = remoteDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
clientSocket = (BluetoothSocket) m.invoke(remoteDevice, 1);
但是当我' Log.i'我从设备收到的数据,因为某种原因我得到了15号,为什么?我做错了什么?
PS。 bytesToSend数组是我需要发送给设备查询它的命令。但我不确定它是否正确,我得到的文件说:
commands:
'R' - request for current RTC status
<0x0F><'R'><CKSH><CKSL><0x0D>
这是对的吗?像我一样发送查询?或者我误解了文档。
答案 0 :(得分:0)
bytes = inputData.read(buffer, 0, inputData.available());
inputDataReader = new InputStreamReader(inputData);
Log.i("RETRIVED_DATA", "" + inputDataReader.read());
三行中有五个错误:
available()
,从而显示可能的读数为零或超过缓冲区长度。应该是:
bytes = inputData.read(buffer);
// Note that bytes cannot now be zero, as buffer.length > 0
if (bytes == -1)
break;
Log.i("RETRIEVED_DATA", new String(buffer, 0, bytes));
注意:
Log.i("DATA_TO_SEND", outputData.toString());
是徒劳的。转换为字符串时,I / O流不会产生任何有趣的内容。它应该是:
Log.i("DATA_TO_SEND", Arrays.toString(bytesToSend));