我对Java和Android知之甚少。我想要做的是在应该与串行线路通信的Android应用中打开/ dev / ttyS0,但是我迷路了。
我的设备已经扎根,并且可以从命令行“回显...> / dev / ttyS0”并从中读取信息,但是我迷失了在Java中尝试这样做的迷路。首先,我找不到在不应对缓冲区和其他复杂问题的情况下以简单的读写模式打开文件的方法(显然,我想要无缓冲的I / O)。
我搜索了Internet,但是所有示例都涉及我不可用的USB。然后我找到了UartDevice类,但这是一个从中派生适当实现的类。
我尝试使用File类,并将Reader类和Writer类都附加到该类上,但是编译器抱怨,并且坦率地说,我不确定这是否可行。我需要一个框架代码来开始;我想念一个简单的TextFile类,该类具有无缓冲的read()和write()方法,它们将在同一打开文件上同时使用!
有人可以指出我正确的方向吗?
最佳答案
经过多次尝试,并在SO站点提供的大量信息的帮助下,我终于成功完成了任务。这是代码:
public class MainActivity
extends AppCompatActivity {
File serport;
private FileInputStream mSerR;
private FileOutputStream mSerW;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// let this program to access the serial port, and
// turn off the local echo. sudo() is a routine found here on S.O.
sudo("chmod a+rw /dev/ttyS0");
sudo("stty -echo </dev/ttyS0");
// open the file for read and write
serport = new File("/dev/ttyS0");
try {
mSerR = new FileInputStream(serport);
mSerW = new FileOutputStream(serport);
} catch (FileNotFoundException e) {}
// edLine is a textbox where to write a string and send to the port
final EditText edLine = (EditText) findViewById(R.id.edLine);
// edTerm is a multiline text box to show the dialog
final TextView edTerm = findViewById(R.id.edTerm);
// pressing Enter, the content of edLine is echoed and sent to the port
edLine.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
String cmd = edLine.getText()+"\n";
edTerm.append(cmd);
byte[] obuf = cmd.getBytes();
try {
mSerW.write(obuf);
} catch (IOException e) {}
edLine.setText("");
// read the reply; some time must be granted to the server
// for replying
cmd = "";
int b=-1, tries=8;
while (tries>0) {
try {
b = mSerR.read();
} catch (IOException e) {}
if (b==-1) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {}
--tries;
} else {
tries=3; // allow more timeout (more brief)
if (b==10) break;
cmd = cmd + (char) b;
}
}
// append the received reply to the multiline control
edTerm.append(cmd+"\n");
return true;
}
return false;
}
});
}
}