| public synchronized String GetMsg(int Length) |
| public synchronized void PutChar(int c) |
| package serial; /** * * This class implements the buffer area to store incoming data from the serial * port. * */ public class SerialBuffer { private String Content = ""; private String CurrentMsg, TempContent; private boolean available = false; private int LengthNeeded = 1; /** * * This function returns a string with a certain length from the incoming * messages. * * @param Length The length of the string to be returned. * */ public synchronized String GetMsg(int Length) { LengthNeeded = Length; notifyAll(); if (LengthNeeded > Content.length()) { available = false; while (available == false) { try { wait(); } catch (InterruptedException e) { } } } CurrentMsg = Content.substring(0, LengthNeeded); TempContent = Content.substring(LengthNeeded); Content = TempContent; LengthNeeded = 1; notifyAll(); return CurrentMsg; } /** * * This function stores a character captured from the serial port to the * buffer area. * * @param t The char value of the character to be stored. * */ public synchronized void PutChar(int c) { Character d = new Character((char) c); Content = Content.concat(d.toString()); if (LengthNeeded < Content.length()) { available = true; } notifyAll(); } } |
| public ReadSerial(SerialBuffer SB, InputStream Port) |
| public void run() |
| package serial; import java.io.*; /** * * This class reads message from the specific serial port and save * the message to the serial buffer. * */ public class ReadSerial extends Thread { private SerialBuffer ComBuffer; private InputStream ComPort; /** * * Constructor * * @param SB The buffer to save the incoming messages. * @param Port The InputStream from the specific serial port. * */ public ReadSerial(SerialBuffer SB, InputStream Port) { ComBuffer = SB; ComPort = Port; } public void run() { int c; try { while (true) { c = ComPort.read(); ComBuffer.PutChar(c); } } catch (IOException e) {} } } |
| import serial.*; import java.io.*; /** * * This is an example of how to use the SerialBean. It opens COM1 and reads * six messages with different length form the serial port. * */ class SerialExample { public static void main(String[] args) { //TO DO: Add your JAVA codes here SerialBean SB = new SerialBean(1); String Msg; SB.Initialize(); for (int i = 5; i <= 10; i++) { Msg = SB.ReadPort(i); SB.WritePort("Reply: " + Msg); } SB.ClosePort(); } } |
关注此文的读者还看过: