我写一个与猫通讯的简单程序,就是给猫发送“AT” ,然后期望接收猫的回应“OK”,但为什么我接收到的却还是“AT”呢?
附源程序:
主程序 S.java
import java.io.*;
class S
{
public static void main(String[] args)
{
SerialBean SB = new SerialBean(3); //打开COM3
System.out.println(SB.Initialize());//是否初始化端口
{
SB.write("AT");
SB.readOne();
SB.write("at");
SB.readOne();
}
SB.ClosePort(); //关闭端口
}
}SerialBean.javaimport java.io.*;
import java.util.*;
import javax.comm.*;
public class SerialBean
{
static String PortName;
CommPortIdentifier portId;
SerialPort serialPort;
static OutputStream outputStream;
static InputStream inputStream;
/**
* @param PortID the ID of the serial to be used. 1 for COM1,
* 2 for COM2, etc.
*/ public SerialBean(int PortID)
{
PortName = "COM" + PortID;
System.out.println("准备要打开:"+PortName+"端口");
}/*初始化端口*/
public int Initialize()
{
int InitSuccess = 1;
int InitFail = -1;
try
{
System.out.println("启动端口");
portId = CommPortIdentifier.getPortIdentifier(PortName); //创建一个端口对象
try
{
serialPort = (SerialPort) portId.open("Serial_Communication", 2000); //参数为相关的文件名和一些整数
} catch (PortInUseException e)
{
return InitFail;
}
try
{
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e)
{
return InitFail;
}
//Initialize the communication parameters to 9600, 8, 1, none.
try
{
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e)
{
return InitFail;
}
} catch (NoSuchPortException e)
{
return InitFail;
}
return InitSuccess;
} /*读取指定的端口的信息*/
public synchronized void readOne()
{
//读取串口的信息
serialPort.notifyOnDataAvailable(true);
byte[] readBuffer = new byte[40];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.println(numBytes);
}
System.out.println(new String(readBuffer,"ASCII"));
} catch (IOException e) {}
}
/*往端口写字符串 */
public synchronized void write(String Msg)
{
try {
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
}
System.out.println(
"Writing \""+Msg+"\" to "
+serialPort.getName()); try {
byte a[]=Msg.getBytes();
outputStream.write(a);
}
catch (IOException e) {} try {
Thread.sleep(2000); // Be sure data is xferred before closing
} catch (Exception e) {}
};/***关闭端口.*/ public void ClosePort()
{
serialPort.close();
}
}为什么我的输出为:
AT
at
呢?
本应输出两个"ok"啊!
感谢高人指点!
附源程序:
主程序 S.java
import java.io.*;
class S
{
public static void main(String[] args)
{
SerialBean SB = new SerialBean(3); //打开COM3
System.out.println(SB.Initialize());//是否初始化端口
{
SB.write("AT");
SB.readOne();
SB.write("at");
SB.readOne();
}
SB.ClosePort(); //关闭端口
}
}SerialBean.javaimport java.io.*;
import java.util.*;
import javax.comm.*;
public class SerialBean
{
static String PortName;
CommPortIdentifier portId;
SerialPort serialPort;
static OutputStream outputStream;
static InputStream inputStream;
/**
* @param PortID the ID of the serial to be used. 1 for COM1,
* 2 for COM2, etc.
*/ public SerialBean(int PortID)
{
PortName = "COM" + PortID;
System.out.println("准备要打开:"+PortName+"端口");
}/*初始化端口*/
public int Initialize()
{
int InitSuccess = 1;
int InitFail = -1;
try
{
System.out.println("启动端口");
portId = CommPortIdentifier.getPortIdentifier(PortName); //创建一个端口对象
try
{
serialPort = (SerialPort) portId.open("Serial_Communication", 2000); //参数为相关的文件名和一些整数
} catch (PortInUseException e)
{
return InitFail;
}
try
{
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e)
{
return InitFail;
}
//Initialize the communication parameters to 9600, 8, 1, none.
try
{
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e)
{
return InitFail;
}
} catch (NoSuchPortException e)
{
return InitFail;
}
return InitSuccess;
} /*读取指定的端口的信息*/
public synchronized void readOne()
{
//读取串口的信息
serialPort.notifyOnDataAvailable(true);
byte[] readBuffer = new byte[40];
try {
while (inputStream.available() > 0)
{
int numBytes = inputStream.read(readBuffer);
System.out.println(numBytes);
}
System.out.println(new String(readBuffer,"ASCII"));
} catch (IOException e) {}
}
/*往端口写字符串 */
public synchronized void write(String Msg)
{
try {
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
}
System.out.println(
"Writing \""+Msg+"\" to "
+serialPort.getName()); try {
byte a[]=Msg.getBytes();
outputStream.write(a);
}
catch (IOException e) {} try {
Thread.sleep(2000); // Be sure data is xferred before closing
} catch (Exception e) {}
};/***关闭端口.*/ public void ClosePort()
{
serialPort.close();
}
}为什么我的输出为:
AT
at
呢?
本应输出两个"ok"啊!
感谢高人指点!
莫非是你的COM3具有人工智能,自己会回复?!
莫非是你的COM3具有人工智能,自己会回复?!"com3 是猫啊!
你向猫发出了at指令,它会返回结果啊! (即“ok”)!
SB.readOne();
SB.write("at");
SB.readOne();
....
SB.readOne(); //从串口中读取一次, 因为我还有其他连续读串口方法,所以这里用readOne() ,定义为读一次!
package com.test;import javax.comm.CommPortIdentifier;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;public class Test implements javax.comm.SerialPortEventListener { private String portName = "COM4"; private javax.comm.SerialPort port = null; private java.io.InputStream in; private java.io.OutputStream out; private boolean debug = true; public Test() throws Exception {
init();
write("AT+CGMI"); //厂商
readWait();
write("AT+CGMM"); //型号
readWait();
// 从控制台输入指令, 回车结束, exit退出
java.io.BufferedReader r = new java.io.BufferedReader(
new java.io.InputStreamReader(System.in));
String input;
do {
input = r.readLine();
if (input.equalsIgnoreCase("exit"))
break;
write(input);
readWait();
} while (true);
close();
} public String read() throws Exception {
int size = in.available();
if (size < 1)
return null;
byte[] input = new byte[size];
in.read(input, 0, size);
String ret = new String(input);
System.out.print("read: \t" + byte2hex(input) + "\n" + ret);
System.out.println("=================================");
return ret;
} public String readWait() throws Exception {
while (in.available() < 1)
Thread.sleep(20);
String input = read();
return input;
} public void write(String cmd) throws Exception {
cmd += "\r";
out.write((cmd).getBytes());
System.out.println("write: " + byte2hex(cmd.getBytes()) + "\t" + cmd);
} private void init() throws Exception {
javax.comm.CommPortIdentifier portId = CommPortIdentifier
.getPortIdentifier(portName);
port = (SerialPort) portId.open(this.getClass().getName(), 2000);
in = port.getInputStream();
out = port.getOutputStream();
port.setSerialPortParams(115200, port.DATABITS_8, port.STOPBITS_1,
port.PARITY_NONE);
// port.enableReceiveFraming(10);
port.enableReceiveTimeout(2000);
// port.addEventListener(this);
mobileInit();
} private void mobileInit() throws Exception {
write("AT");
String output;
do {
Thread.sleep(2000);
output = read();
if (output != null) {
System.out.println("Output:" + output);
break;
}
write("AT");
} while (true);
} public void close() throws java.io.IOException {
in.close();
out.close();
port.close();
} public static void showPorts() {
java.util.Enumeration all = javax.comm.CommPortIdentifier
.getPortIdentifiers();
while (all.hasMoreElements()) {
javax.comm.CommPortIdentifier com = (javax.comm.CommPortIdentifier) all
.nextElement();
System.out.println(com.getName() + "\t" + com.isCurrentlyOwned()
+ "\t" + com.getCurrentOwner());
}
} // 字节码转换成16进制字符串
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
if (n < b.length - 1)
hs = hs + ":";
}
return hs.toUpperCase();
} public void serialEvent(SerialPortEvent event) {
System.out.println("Event:" + event.getEventType());
try {
if (event.getEventType() == event.DATA_AVAILABLE) {
System.out.println("Read String:" + read());
}
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws Exception {
new Test();
}
}
这个我测试过了。我现在也在做短信猫开发。
MSN:[email protected]
北京中关村