www.pudn.com > ejip.zip > Serial2.java


package util;

import com.jopdesign.sys.Native;
import javax.joprt.*;

/**
*	Buffered serial line in it's own thread with maximum priority.
*	Just a copy of Serial for second port (GPS on OEBB project).
*/

public class Serial2 extends RtThread {

	private static final int IO_STATUS = 8;
	private static final int IO_UART = 9;

	private static final int MSK_UA_TDRE = 1;
	private static final int MSK_UA_RDRF = 2;

	private static final int BUF_LEN = 128;
	private static final int BUF_MSK = 0x7f;

//
//	for GPS use: 4800 baud => 2.0833 ms per character
//	send fifo: 4, receive fifo: 5
//		8 ms should be ok, 5 ms for shure
//
	private static final int PERIOD = 5;

/**
*	Send buffer for serial line.
*/
	private static int[] serTxBuf;
/**
*	Receive buffer for serial line.
*/
	private static int[] rxBuf;

	private static int rdptTx, wrptTx;
	private static int rdptRx, wrptRx;

	private static Serial2 ser;

	Serial2(int ms) {
		super(ms);						// thats the period.
	}

	public static void init() {

		if (ser!=null) return;

		serTxBuf = new int[BUF_LEN];		// should be byte
		rxBuf = new int[BUF_LEN];
		rdptTx = wrptTx = 0;
		rdptRx = wrptRx = 0;

		//
		// minimum 1 ms, but performance degrades below 2/3 ms
		//
		ser = new Serial2(PERIOD);
		ser.setPriority(Thread.MAX_PRIORITY);
		ser.start();
	}

	public void run() {

		for (;;) {
			waitForNextPeriod();
			loop();
		}
	}

/**
*	read and write loop.
*	call it! (polling)
*/
	// public static void loop() {
	private static void loop() {

		int i, j;
//
//	read serial data
//
		i = wrptRx;
		j = rdptRx;
		// if (BUF_LEN - ((i-j) & BUF_MSK) >= HW_FIFO) {		// read only if complete fifo could be read out!
			while ((Native.rd(IO_STATUS) & MSK_UA_RDRF)!=0 && ((i+1)&BUF_MSK)!=j) {
				rxBuf[i] = Native.rd(IO_UART);
				i = (i+1)&BUF_MSK;
			}
			wrptRx = i;
		// }
//
//	write serial data
//
		i = rdptTx;
		j = wrptTx;
		while ((Native.rd(IO_STATUS) & MSK_UA_TDRE)!=0 && i!=j) {
			Native.wr(serTxBuf[i], IO_UART);
			i = (i+1) & BUF_MSK;
		}
		rdptTx = i;
	}

	public static int rxCnt() {

		return (wrptRx-rdptRx) & BUF_MSK;
	}

	public static int txFreeCnt() {

		return (rdptTx-1-wrptTx) & BUF_MSK;
	}

	public static int rd() {

		int i = rdptRx;
		rdptRx = (i+1) & BUF_MSK;
		return rxBuf[i];
	}

	public static void wr(int c) {

		int i = wrptTx;
		wrptTx = (i+1) & BUF_MSK;
		serTxBuf[i] = c;
	}
}