我正在尝试读取从外部蓝牙模块发送到我的HTC Sensation的串行数据,但是当我调用InputStream.available()时 – 它返回0,所以我不能迭代收到的字节并调用InputStream.read(byteArray).
有人可以帮我解决这个问题吗?
在阅读之前我需要检查可用字节吗?
我为技术上不准确的帖子道歉.
这是我的代码:
public class BluetoothTest extends Activity
{
TextView myLabel;
TextView snapText;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
Button closeButton = (Button)findViewById(R.id.close);
Button chkCommsButton = (Button)findViewById(R.id.chkCommsButton);
Button offButton = (Button)findViewById(R.id.offButton);
myLabel = (TextView)findViewById(R.id.mylabel);
snapText = (TextView)findViewById(R.id.snapText);
//Open Bluetooth
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Close Bluetooth
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
// Check Comms - multicast all SNAP nodes and pulse their BLUE led
chkCommsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
chkcommsButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
//Off Button - set strip to all OFF
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
offButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
}
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("BTNODE25")) // Change to match RN42 - node name
{
mmDevice = device;
Log.d("ArduinoBT", "findBT found device named " + mmDevice.getName());
Log.d("ArduinoBT", "device address is " + mmDevice.getAddress());
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("BT << " + mmDevice.getName() + " >> is now open ");
}
void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
snapText.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
void offButton() throws IOException
{
mmOutputStream.write("0".getBytes());
}
void chkcommsButton() throws IOException
{
mmOutputStream.write("1".getBytes());
}
}
解决方法:
InputStream.read()方法是阻塞的,这意味着它会阻塞你的代码,直到一些数据到达,或者某些东西破坏管道(如断开主机或关闭流).
阻塞是CPU友好的,因为线程处于WAIT状态(休眠),直到中断使其处于READY状态,因此它将被安排在CPU上运行;所以你在等待数据时WONT使用cpu,这意味着你将使用更少的电池(或者你将CPU时间留给其他人的线程)!
available()给出了实际可用的数据,并且因为串行通信非常慢(11n00波特在8n1意味着11520字节/秒)并且你的循环运行速度至少快一到两个数量级,你会读到很多0,并且使用大量的cpu来要求零……这意味着你要使用大量的电池.
循环可用在arduino上不是问题,因为你只有一个线程/进程:你的代码.但是在多线程系统中循环检查数据(称为“轮询”)总是一个坏主意,并且只有在你没有其他选择时才应该完成,并且总是添加一点sleep()以便你的代码赢得’ t窃取CPU到系统和其他线程.好主意是使用阻塞调用(对于初学者来说很容易使用)或者像你对图形事件那样使用事件系统(并不总是被你使用的库支持,并且需要同步,所以它很棘手,但你不会产生其他线程你自己的代码,但请记住,串行和图形的数据和你的应用程序PROBABLY在不同的线程中,应该同步)
标签:java,android,bluetooth,arduino
来源: https://codeday.me/bug/20190612/1225850.html