我正在使用 android 中的库连接到终端仿真器,它连接到串行设备(开关)并显示发送/接收的数据。我使用另一个库通过串行发送数据。我通过终端下方的文本框或在终端本身输入并在两种情况下按键盘上的 Enter 键通过连接发送数据。我也可以通过按键发送命令。
在我的活动中,我有一个名为的方法sendOverSerial
,它只调用一个库方法来通过 USB 将数据发送到通过串行连接的设备。
public static void sendOverSerial(byte[] data) {
if(mSelectedAdapter !=null && data !=null){
mSelectedAdapter.sendData(data);
}}
该活动打开一个类的实例,该类用于向终端屏幕写入数据。通常,当我想通过串行发送数据时,editText
我会buttons
调用sendOverSerial
活动中的方法。但是当我将字符写入终端本身时,它们会在这个新的实例write
方法中被拾取。所以我必须sendOverSerial
从那个实例调用方法。我的问题是,如果我调用它在下面写“TEST”,那么 TEST 会以无限循环的形式写入终端,它只会继续写它。知道为什么吗?如果我像我评论的那样将它发送得更远,它只会按预期发送一次。
public void write(byte[] bytes, int offset, int count) {
int numCRs = 0;
for (int i = offset; i < offset + count; ++i) {
if (bytes[i] == '\r') {
++numCRs;
}
}
if (numCRs == 0) {
// No CRs -- just send data as-is
//infinite loop if I send from here
GraphicsTerminalActivity.sendOverSerial("TEST".getBytes());
super.write(bytes, offset, count);
if (isRunning()) {
doLocalEcho(bytes);
}
return;
}
Log.d(TAG, "CRs=== " + numCRs);
// Convert CRs into CRLFs
byte[] translated = new byte[count + numCRs];
int j = 0;
for (int i = offset; i < offset + count; ++i) {
if (bytes[i] == '\r') {
translated[j++] = '\r';
translated[j++] = '\n';
} else {
translated[j++] = bytes[i];
}
}
//fine if I send from here, sends once
GraphicsTerminalActivity.sendOverSerial("SECOND TEST".getBytes());
super.write(translated, 0, translated.length);
// If server echo is off, echo the entered characters locally
if (isRunning()) {
doLocalEcho(translated);
}
}
来自库的 Super.write:
public void write(byte[] data, int offset, int count) {
try {
mWriteQueue.write(data, offset, count);
} catch (InterruptedException e) {
}
notifyNewOutput();
}
然后在库中的另一个类 bytequeue 类中调用 write
public void write(byte[] buffer, int offset, int length)
throws InterruptedException {
if (length + offset > buffer.length) {
throw
new IllegalArgumentException("length + offset > buffer.length");
}
if (length < 0) {
throw
new IllegalArgumentException("length < 0");
}
if (length == 0) {
return;
}
synchronized(this) {
int bufferLength = mBuffer.length;
boolean wasEmpty = mStoredBytes == 0;
while (length > 0) {
while(bufferLength == mStoredBytes) {
wait();
}
int tail = mHead + mStoredBytes;
int oneRun;
if (tail >= bufferLength) {
tail = tail - bufferLength;
oneRun = mHead - tail;
} else {
oneRun = bufferLength - tail;
}
int bytesToCopy = Math.min(oneRun, length);
System.arraycopy(buffer, offset, mBuffer, tail, bytesToCopy);
offset += bytesToCopy;
mStoredBytes += bytesToCopy;
length -= bytesToCopy;
}
if (wasEmpty) {
notify();
}
}
}