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


package util;

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

/**
*	Buffered serial line in it's own thread with maximum priority.
*/

public class Serial extends RtThread {

	private static final int IO_STATUS = 1;
	private static final int IO_UART = 2;

	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;

	private static final int HW_FIFO = 20;
	private static final int PERIOD = 2;

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

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

	private static Serial ser;

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

	public static void init() {

		if (ser!=null) return;

		txBuf = 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 Serial(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(txBuf[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;
		txBuf[i] = c;
	}
}