⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pmac.java

📁 j2me实现的移动机器人代码(Java实现)
💻 JAVA
字号:
/*
 * Created on 2004-12-2
 *
 * This class is a wrap class for PMAC connected with the PC
 * through the serial port.
 */
package cie.mobile.pmac;

import java.io.IOException;
import java.io.Reader;
import java.util.Vector;
import javax.comm.SerialPort;
import name.lxm.comm.*;

/**
 * The encapsulated class for the PMAC interface
 * 
 * @author Richard Lee (lxm_zju@yahoo.com.cn)
 */
public class Pmac {
    /**Serial Port Name, Such as COM1, COM2, etc */
    private String commName;
    /** Serial Communication Mode, Block or Use Event Handler */
    private int mode;
    /** the mode using blocking reading/writing method from/to the stream */
    public static final int BLOCKING_MODE = 1;
    /** the mode using the serial port event handler for recieving data, not implemented yet. */
    public static final int NON_BLOCKING_MODE = 2;
    /** State ready for command */
    public static final int STATE_READY = 1;
    /** State ready for power off */
    public static final int STATE_OFFLINE = 2;

    //listeners
    private Vector listeners = new Vector();
    //serial port
    private CommSerialPort comm;
    //state
    private int state = 0;
    //buffer to receive port response
    private byte[] buf = new byte[32];
    //regist itself
    private static Pmac thePmac = null;

    /**
     * Default Contructor. <BR>
     * The Card will be initialized and is ready for command. <BR>
     * 
     * @throws PMACException
     *  
     */
    private Pmac() throws PMACException {
        this(BLOCKING_MODE);
    }

    /**
     * Constructor The Card will be initialized and is ready for command.
     * 
     * @param mode
     *            there are two choice: blocking method or non-block method
     * @throws PMACException
     */
    private Pmac(int mode) throws PMACException {
        this.mode = mode;
        //init();
    }

    /**
     * Initialize the serial port connected with the PMAC Card. Initialize the
     * PMAC Card, to make it ready for motion control
     * 
     * @throws PMACException
     */
    public void init(String com) throws PMACException {
        try {
            //load requested serial port
	    commName = com;
            comm = CommPortFactory.getSerialPort(commName, "pmac");
            //set the default parameters
            comm.setBaudrate(9600);
            comm.setDataBits(SerialPort.DATABITS_8);
            comm.setParity(SerialPort.PARITY_NONE);
            comm.setStopBits(SerialPort.STOPBITS_1);
            //open the serial port
            comm.open();
        } catch (Exception e) {
            throw new PMACException("Communication With PMAC Error.");
        }
        //sending commands to initialize the PMAC Card
	try{
		initCard();
		System.out.println("Card has been initialized!");
	}
	catch(IOException e){
		throw new PMACException(e.getMessage());
	}
	catch(CommPortTimedOutException e)
	{
		throw new PMACException(e.getMessage());
	}
    }

    /**
     * Put the PMAC Code here, such as the program to be downloaded to the PMAC
     * Having not been implemented.
     */
    private void initCard() throws IOException, CommPortTimedOutException
    {
    	int t=0;
	while(t<3)
	{
		String resp = sendCommandLine("a");
		//comm.writeLine("a");
		//comm.wait4DataReady();
		//int i = comm.readBytes(buf);
		if(resp.length() == 0)
		{
			sendCommandLine("#1HMZ#2HMZ");
			break;	
		}
		t++;
	}
	if(t ==3)
		throw new IOException ("Initial Pmac Card Failed.");
    }

    /**
     * <p>Send a command to PMAC.</p>
     * <p>Attention!May Get Blocked!</p>
     * 
     * @param cmd
     * @return a string contains the return message
     * @throws IOException
     * @throws CommPortTimedOutException
     */
    public String sendCommandLine(String cmd) throws IOException, CommPortTimedOutException {
        comm.writeLine(cmd);
	comm.wait4DataReady();
	String msg = comm.readLine(6);
        dispatchLog(cmd, true);
	return msg;
    }

    /**
     * Read message from PMAC <br>
     * This is a blocking method <br>
     * 
     * @return A Line Message
     * @throws CommPortTimedOutException
     * @throws IOException
     */
    public String getResponseMessage() throws IOException,
            CommPortTimedOutException {
        int c;
	comm.wait4DataReady();
	String s = comm.readLine(6);
        dispatchLog(s, false);
        return s;
    }

    /**
     * Sending data to registered listeners
     * @param s
     */
    private void dispatchLog(String s, boolean b) {
        if (b)//send message to PMAC
        {
		//System.out.println("Sended: " + s);
            for (int i = 0; i < listeners.size(); i++) {
                ((PmacListener) listeners.get(i)).msgSend(s);
            }
        } else { //get message from PMAC
		//System.out.println("Recieved: " + s);
            for (int i = 0; i < listeners.size(); i++) {
                ((PmacListener) listeners.get(i)).msgRecieved(s);
            }
        }
    }

    /**
     * Add listener for communication data probe
     * @param l the listener
     */
    public void addPmacListener(PmacListener l) {
        listeners.addElement(l);
    }

    /**
     * remove listener for communication data probe
     * @param l 
     * 			the listener
     */
    public void removePmacListener(PmacListener l) {
        listeners.removeElement(l);
    }

    /**
     * PMAC is an multi-axis controller. This method is used to querry the
     * current position of the specified axis. Do NOT forget the returned value
     * are in the unit of PMAC. You should scale it very carefully. This is one
     * the of on-line command provided by PMAC.
     * 
     * @param axis
     *            which axis (motor) you want to querry
     * @return position of specified axis, in the unit of PMAC
     * @throws IOException
     * @throws CommPortTimedOutException
     */
    public double getAxisPosition(int axis) throws IOException {
        String s = "#" + axis + "P";
        String resp;
        try {
		resp = sendCommandLine(s);
        } catch (CommPortTimedOutException e) {
            throw new IOException("No response from PMAC.");
        }
	if(resp.length() > 0)
		return Double.parseDouble(resp);
	else 
		throw new IOException("Empty string responsed from pmac.");
    }

    /**
     * Drive Specified Axis move a specified distance. The distance can be
     * negtive. One of the online motor command.
     * 
     * @param axis
     *            which axis to drive
     * @param distance
     *            how long would you want to go
     * @throws IOException
     * @throws CommPortTimedOutException
     */
    public void moveRelative(int axis, long distance) throws IOException, CommPortTimedOutException
    {
        String s = "#" + Integer.toString(axis) + "J:"
                + Long.toString(distance);
        sendCommandLine(s);
    }

    /**
     * Drive Specified Axis to Specified Position One of the online motor
     * command.
     * 
     * @param axis
     *            which axis to drive
     * @param position
     *            Where do you want to go?
     * @throws IOException
     */
    public void moveToPos(int axis, long position) throws IOException, CommPortTimedOutException
   {
        String s = "#" + Integer.toString(axis) + "J="
                + Long.toString(position);
        sendCommandLine(s);
    }

    /**
     * Move back to last position (online command)
     * 
     * @param axis
     *            which axis do you want to drive
     * @throws IOException
     */
    public void moveToLastPos(int axis) throws IOException, CommPortTimedOutException
   {
        String s = "#" + Integer.toString(axis) + "J=";
        sendCommandLine(s);
    }

    /**
     * Drive specified axis move infinately.
     * 
     * @param axis
     *            which axis to drive
     * @param dir
     *            the direction, can be any value of positive or negtive
     * @throws IOException
     */
    public void move(int axis, int dir) throws IOException, CommPortTimedOutException {
        String s;
        if (dir > 0)
            s = "#" + Integer.toString(axis) + "J+";
        else
            s = "#" + Integer.toString(axis) + "J-";
        sendCommandLine(s);
    }

    /**
     * Download a program to PMAC and Run it
     * 
     * @param r
     *            the reader where script can be found
     * @param autoStart
     *            automatic run this program?
     */
    public void runProgram(Reader r, boolean autoStart) {

    }

    /** 
     * Get the communicating serial port for later reference
     * @return serial commnuication port object
     */
    public CommSerialPort getCommunicationPort() {
        return comm;
    }

    /**
     * Get the global unique PMAC object
     * @return pmac object
     * @throws PMACException
     */
    public static Pmac getTheMobilePmac() throws PMACException {
        if (thePmac == null) {
            thePmac = new Pmac();
        }
        return thePmac;
    }
    
    /**
     * Stop moving immediately
     * @param axis
     * @throws IOException
     */
    public void stop(int axis) throws IOException,CommPortTimedOutException
    {
        sendCommandLine("#" + Integer.toString(axis) + "j/");
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -