📄 simpleserial.java
字号:
import java.io.*;
import java.util.*;
/*
Created on January 2, 2000
Ben Resner
benres@media.mit.edu
Very simple class for implementing serial port communcation on Windows platforms. It's intended for use
with PIC chips, but it should be useful for a variety of serial communications.
To use, you MUST have the file "SimpleSerial.dll" located somewhere in your dll search path. This means
it's in your "Windows\System32" directory, or in the same directory as this java file. If this isn't
done, you'll get an unsatisfied link error or some other cryptic error.
Look at the main() function in this file for a super simple example
*/
public class SimpleSerial
{
// #### CONSTANTS
// ####
// These are copied right out of WINBASE.H
// Most applications should be fine with the defaults.
public static final int NOPARITY = 0;
public static final int ODDPARITY = 1;
public static final int EVENPARITY = 2;
public static final int MARKPARITY = 3;
public static final int SPACEPARITY = 4;
public static final int ONESTOPBIT = 0;
public static final int ONE5STOPBITS = 1;
public static final int TWOSTOPBITS = 2;
// #### PUBLIC CONSTRUCTORS
// ####
// New a serial port. Pass in comm port number
SimpleSerial(int comPort) {
_initPort( convertToCommString(comPort), 9600, 8, ONESTOPBIT, NOPARITY);
}
// New a serial port. Similar to above, but allows greater user configuration
SimpleSerial(int comPort, int baud, int dataBits, int stopBits, int parity) {
_initPort( convertToCommString(comPort), baud, dataBits, stopBits, parity);
}
// #### PUBLIC MEMBER FUNCTIONS
// ####
// Checks to make sure serial port was initialized properly.
public boolean isValid() {
return (m_Port != 0);
}
/*
Writes a byte to the serial port
For example, to write the character 'b' to the serial port: serialPort.writeByte('b');
*/
public boolean writeByte(int val) {
try {
m_DataOutputStream.writeByte(val);
}
catch (IOException e) {
return false;
}
return true;
}
// Writes an entire string to the serial port
// For example, to write the string "hello world": serialPort.writeString("Hello World");
public boolean writeString(String string) {
try {
m_DataOutputStream.writeBytes(string);
}
catch (IOException e) {
return false;
}
return true;
}
// Waits here for data to arrive.
public void waitForData() {
waitForData(1);
}
// Waits here for 'minNumBytes' of data to arrive.
public void waitForData(int minNumBytes) {
try {
while (available() < minNumBytes) {
Thread.sleep(50);
}
}
catch (InterruptedException e) {
System.out.println("#### Thread interrupted -- could be big trouble");
}
}
// read a byte of data. If no data available, wait for data
// If an error occurs, returns -1. It's not a bad idea to check for this.
public int readByte() {
waitForData();
try {
return m_DataInputStream.readByte();
}
catch (IOException e) {
return -1;
}
}
// Read an entire string of data. If no data available, returns an empty string.
// This routine never waits for data.
public String readString() {
try {
int len = available();
if (len > 0) {
byte bytes[] = new byte[len];
m_DataInputStream.read(bytes);
return new String(bytes);
}
else {
return new String("");
}
}
catch (IOException e) {
return new String("");
}
}
// Returns how many bytes are available to be read.
// Note that by the time you actually do the reading, more could be available.
public int available() {
try {
return m_DataInputStream.available();
}
catch (IOException e) {
return -1;
}
}
// Close the serial port. The port is automatically closed on exit, and you shouldn't normally
// have to do this yourself. It's only necessary if you want to close one port and re-open
// another.
public void close() {
if (m_Port != 0) {
_closeSerialPort(m_Port);
m_Port = 0;
}
}
/*
The following two calls are for more advanced implementations. For instance, if you need to
peek at data without removing it from the queue, you'll want something like:
serialPort = new SimpleSerial(2);
DataInputStream dis = new DataInputStream(new BufferedInputStream(serialPort.getInputStream()));
// now you can do stuff like
dis.mark(512); // mark this position
String string = dis.readString(); // read a string (or anything)
try {
dis.reset(); // set back to location where mark() was called
}
catch (IOException e) {}
*/
// Gets the input stream for this port. Allows greater control over IO
// Most applications won't need these
public InputStream getInputStream()
{
if (m_Port != 0) {
return new SimpleSerialInputStream(this);
}
else {
System.out.println("###ERROR: You can't get input stream because serial port wasn't opened");
}
return null;
}
// Gets the output stream for this port. Allows greater control over IO.
// Most applications won't need these
public OutputStream getOutputStream()
{
if (m_Port != 0) {
return new SimpleSerialOutputStream(this);
}
else {
System.out.println("###ERROR: You can't get input stream because serial port wasn't opened");
}
return null;
}
// #### PUBLIC DATA MEMBERS
// ####
// You can use these directly if you seek more controll over IO. Most applications
// won't use these.
public DataInputStream m_DataInputStream;
public DataOutputStream m_DataOutputStream;
// #### Super Simple example code
static public void main(String args[])
{
// Opens port on Comm2. This will likely need to be changed for your computer
SimpleSerial sp = new SimpleSerial(2);
int letter;
int ii;
// Write a string to the serial port. Be sure to include carriage return and linefeed
sp.writeString("\n\r\n\rType in a few letters input\n\r");
// Read in five letters.
for (ii = 0; ii < 5; ii++) {
letter = sp.readByte(); // readByte waits for input before returning
sp.writeByte(letter); // echo the input character back to the console
System.out.println("You typed in a letter with ASCII value: '" + letter + "\"");
}
// Write another string
sp.writeString("\n\rThank you. Type in some more intput\n\r");
// Wait for ten bytes to accumulate
sp.waitForData(10);
// Read in our ten byte string
String input = sp.readString();
sp.writeString("You typed in: " + input);
System.out.println("You typed in: \"" + input + "\"");
System.exit(0);
}
/* ********************************** */
// non-public members
static
{
System.loadLibrary("simpleserial");
}
// Opens the serial port and returns the port handle. The port handle is stored for use in the _read/_write calls.
native int _openSerialPort(String comPort, int baud, int dataBits, int stopBits, int parity);
// Write the bytes in 'string'. Returns the number of bytes written
native int _writeSerialPort(int port, String string);
// Reads all available bytes in the serial port buffer. If nothing available, returns a zero-length array.
// Note this function never blocks -- it always returns immediately.
native byte[] _readSerialPort(int port);
native void _closeSerialPort(int port);
int m_Port = 0;
Stack m_ReadQueue = new Stack(); // we're actually using this as a queue, not a stack
protected void finalize() throws Throwable {
super.finalize();
close();
}
void updateInputBuffer()
{
int ii;
byte inputString[] = _readSerialPort(m_Port);
for (ii = 0; ii < inputString.length; ii++) {
m_ReadQueue.insertElementAt(new Byte(inputString[ii]), 0);
}
}
protected String convertToCommString (int comPort) {
return new String("\\\\.\\com") + (new Integer(comPort)).toString();
}
private void _initPort(String comPort, int baud, int dataBits, int stopBits, int parity)
{
// We need to be sure serial port is closed on program exit.
System.runFinalizersOnExit(true);
m_Port = _openSerialPort(comPort, baud, dataBits, stopBits, parity);
m_DataInputStream = new DataInputStream(getInputStream());
m_DataOutputStream = new DataOutputStream(getOutputStream());
if (m_Port == 0) {
System.out.println("###ERROR: Couldn't open requested port ");
}
}
}
/* ****************************************************************** */
/* ****************************************************************** */
/* ****************************************************************** */
/* ****************************************************************** */
class SimpleSerialInputStream extends InputStream {
SimpleSerial m_Parent;
SimpleSerialInputStream(SimpleSerial parent) {
m_Parent = parent;
}
public int available() throws IOException {
m_Parent.updateInputBuffer();
return m_Parent.m_ReadQueue.size();
}
public int read() throws IOException {
m_Parent.updateInputBuffer();
if (m_Parent.m_ReadQueue.size() == 0) {
return -1;
}
else {
Byte val = (Byte)(m_Parent.m_ReadQueue.pop());
return val.intValue();
}
}
public int read(byte[] b, int off, int len) throws IOException {
m_Parent.updateInputBuffer();
if (m_Parent.m_ReadQueue.size() == 0) {
return -1;
}
else {
int ii;
int max = Math.max(b.length, len);
for (ii = 0; ii < max && !m_Parent.m_ReadQueue.isEmpty(); ii++) {
Byte val = (Byte)(m_Parent.m_ReadQueue.pop());
b[ii + off] = val.byteValue();
}
return ii;
}
}
}
class SimpleSerialOutputStream extends OutputStream {
SimpleSerial m_Parent;
SimpleSerialOutputStream(SimpleSerial parent) {
m_Parent = parent;
}
public void write(int val) throws IOException {
byte tempByte[] = new byte[1];
tempByte[0] = (byte)val;
m_Parent._writeSerialPort(m_Parent.m_Port, new String(tempByte));
}
public void write(byte[] b, int off, int len) throws IOException {
m_Parent._writeSerialPort(m_Parent.m_Port, new String(b, off, len));
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -