如何将数据传输到串口?

时间:2011-11-15 10:58:04

标签: java eclipse java-me serial-port

我知道在J2ME中CommConnection是使用serial port时要使用的连接。我知道有openInputStreamopenOutputStream方法,但事实上我不知道如何将数据从我的MIDLet传输到COM端口(插入手机电缆的USB端口,手机是阿尔卡特OT-806D)。例如,我想发送文本“Hello world”。如何实现?

以下是代码:

J2ME:

import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.CommConnection;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;

public class SerialPortMidlet extends MIDlet implements CommandListener, Runnable {
    private Command upload = new Command("upload", Command.SCREEN, 0);
    private Command exit = new Command("exit", Command.SCREEN, 1);
    private Form f = new Form("test serial port");
    private Thread uploadThread;
    private CommConnection com;
    private OutputStream os;
    public SerialPortMidlet()
    {
        f.addCommand(upload);
        f.addCommand(exit);
        f.setCommandListener(this);
        uploadThread = new Thread(this);
    }
    public void startApp() {
        Display.getDisplay(this).setCurrent(f);
    }
    public void pauseApp() {
    }
    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }
    public void commandAction(Command c, Displayable d) {
        if (c == upload)
        {
            uploadThread.start();
            f.removeCommand(upload);
        }
        else if (c == exit)
        {
            if (uploadThread.isAlive())
            {
                uploadThread.interrupt();
                try {
                    uploadThread.join();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            destroyApp(true);
        }
    }
    public void run() {
        try
        {
            String s = new String("andrana mandefa lavaka");
            com = (CommConnection) Connector.open("comm:COM4");
            os = com.openOutputStream();
            os.write(s.getBytes());
            os.close();
        } 
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }
}

J2SE:(Eclipse)

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TwoWaySerialComm 
{
    public TwoWaySerialComm()
    {
        super();
    }
    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialWriter(out))).start();

                serialPort.addEventListener(new SerialReader(in));
                serialPort.notifyOnDataAvailable(true);

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }     
    }
    public static class SerialReader implements SerialPortEventListener 
    {
        private InputStream in;
        private byte[] buffer = new byte[1024];

        public SerialReader ( InputStream in )
        {
            this.in = in;
        }

        public void serialEvent(SerialPortEvent arg0) {
            int data;

            try
            {
                int len = 0;
                while ( ( data = in.read()) > -1 )
                {
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                System.out.print(new String(buffer,0,len));
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }             
        }

    }
    public static class SerialWriter implements Runnable 
    {
        OutputStream out;

        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }

        public void run ()
        {
            try
            {                
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }                
            }
            catch ( IOException e )
            {
                e.printStackTrace();
                System.exit(-1);
            }            
        }
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try
        {
            (new TwoWaySerialComm()).connect("COM1");
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我运行J2SE程序,我将手机线插入计算机(在USB插槽中),我点击了J2ME应用程序中的upload命令,但是在eclipse的输出屏幕中没有任何内容!

那么问题是什么?

我运行此J2SE代码来检测手机电缆所在的端口:

import gnu.io.*;
public class SerialPortLister {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        listPorts();
    }
    private static void listPorts()
    {
        @SuppressWarnings("unchecked")
        java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
        while ( portEnum.hasMoreElements() ) 
        {
            CommPortIdentifier portIdentifier = portEnum.nextElement();
            System.out.println(portIdentifier.getName()  +  " - " +  getPortTypeName(portIdentifier.getPortType()) );
        }        
    }
    private static String getPortTypeName ( int portType )
    {
        switch ( portType )
        {
            case CommPortIdentifier.PORT_I2C:
                return "I2C";
            case CommPortIdentifier.PORT_PARALLEL:
                return "Parallel";
            case CommPortIdentifier.PORT_RAW:
                return "Raw";
            case CommPortIdentifier.PORT_RS485:
                return "RS485";
            case CommPortIdentifier.PORT_SERIAL:
                return "Serial";
            default:
                return "unknown type";
        }
    }
}

它显示COM4,因为当我拆下电缆时,只显示COM1和LPT1。

那么问题是什么?

1 个答案:

答案 0 :(得分:1)

计算机可以很好地检测到您的手机连接在虚拟COM端口4上。但是,我不清楚您应该使用手机端的COM端口协议与计算机进行通信。完全可能的是,手机上只有一个缓冲区,一旦填充就会在USB端口上传送。

我不知道你的手机,但我已经编程了一个微控制器。在那里,我从未使用COM端口协议,并设法与具有虚拟COM端口驱动程序的计算机进行通信。

为了更好地理解我的观点,您可以参考手机上存在的微控制器的文档。