所以,我有一个通过RS-232 DB9串口连接的卡锁系统设备。这是我第一次使用它来处理外部设备。所以我阅读了手册,它说传输过程文本格式定义如下:
- 文本必须在 STX 和 ETC 之间最多包含 500 个字符
-LRC 计算区域范围从 STX 到 ETX 的第一个字符
还有一个控制字符列表(STX、ETX、ACK、NAK)及其十六进制代码。
我对此一无所知。请赐教。哦,还有,我可以检测设备是否连接到特定端口吗?
我已经设法使用下面的代码连接到通信端口:
public class TwoWaySerialComm
{
protected InputStream inputStream;
protected OutputStream outputStream;
public TwoWaySerialComm()
{
super();
}
void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_7,SerialPort.STOPBITS_1,SerialPort.PARITY_ODD);
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
(new Thread(new SerialReader(inputStream))).start();
(new Thread(new SerialWriter(outputStream))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public OutputStream getOutputStream() {
return outputStream;
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
/** */
public static class SerialReader implements Runnable
{
InputStream in;
public SerialReader ( InputStream in )
{
this.in = in;
}
public void run ()
{
byte[] buffer = new byte[1024];
int len = -1;
try
{
while ( ( len = this.in.read(buffer)) > -1 )
{
System.out.print(new String(buffer,0,len));
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
/** */
public static class SerialWriter implements Runnable
{
OutputStream out;
public SerialWriter ( OutputStream out )
{
this.out = out;
}
public void run ()
{
try
{
int c = 0;
while ( ( c = System.in.read()) > -1 )
{
this.out.write(c);
}
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
public static void main ( String[] args )
{
try
{
TwoWaySerialComm comm = new TwoWaySerialComm();
comm.connect("COM3");
}
catch ( Exception e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是我发现的用于从字节数组中获取 LRC 的代码:
public byte calculateLRC(byte[] data)
{
byte checksum = 0;
for (int i = 0; i <= data.length - 1; i++) {
checksum = (byte) ((checksum + data[i]) & 0xFF);
}
checksum = (byte) (((checksum ^ 0xFF) + 1) & 0xFF);
return checksum;
}
现在据说我必须正确地向设备发送文本“CES01”,我该怎么做?