Java串口通信-2

发现果然是串口线的问题啊。。。
哎,用两台pc来调试程序麻烦,用虚拟串口吧。
下载了VSPM,虚拟出4个串口。
COM3和COM4运行在server模式,COM5和COM6运行在client模式。
嗯,用COM3和COM5来通信。
测试代码如下:
//SwitchBoard.java . 模拟了一个电话交换机,呵呵
package simulateCTI;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;

public class SwitchBoard extends JFrame implements Runnable, ActionListener,
        SerialPortEventListener {

    static final String PORT_TO_USE = "COM3";// virtual port for simulation.

    char ACK = (byte) 0x06;

    char STX = (byte) 0x02;

    char ETX = (byte) 0x03;

    String MSG1 = STX + "20070801HphoneNumIs0507289960" + ETX;

    boolean endKeepCallFlag = false;

    static CommPortIdentifier PortId;// used to check the port.

    static Enumeration portList;// list all the availble ports.

    SerialPort serialPort;

    OutputStream outputStream = null;

    InputStream inputStream = null;

    String Msg;

    // GUI
    JButton simulateOneCall = new JButton("Simulate One Call");
    JRadioButton ACKed = new JRadioButton("Got ACK");



    SwitchBoard() {
        // Set GUI
        super("Simulate the SwitchBoard. Will send Msg to Computer.");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(300, 300);
        this.setVisible(true);
        this.setLayout(new FlowLayout());
        this.add(simulateOneCall);
        this.add(ACKed);
        this.pack();
        simulateOneCall.addActionListener(this);
       
        // Build serial port connection.
        openSerialPort();
    }

    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                Thread.sleep(500);
                // readTheBuffer();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public void openSerialPort() {
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            PortId = (CommPortIdentifier) portList.nextElement();
            if (PortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (PortId.getName().equals(PORT_TO_USE)) {
                    try {
                        serialPort = (SerialPort) PortId.open(
                                "SwitchBoard_Simulation", 2000);
                        try {
                            serialPort.setSerialPortParams(9600,
                                    SerialPort.DATABITS_8,
                                    SerialPort.STOPBITS_1,
                                    SerialPort.PARITY_NONE);
                        } catch (UnsupportedCommOperationException e) {
                            e.printStackTrace();
                        }
                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        System.out.println("the port is already in use!");
                    }
                }
            }
        }
        // open the io channel of the serial port.
        try {
            outputStream = serialPort.getOutputStream();
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // to listen the serial port.
        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException tle) {
            tle.printStackTrace();
        }
        serialPort.notifyOnDataAvailable(true);
    }

    public void sendToComputer() {
        try {
            // outputStream = serialPort.getOutputStream();
            // Msg = simulate_Msg_inputBox.getText();
            Msg = MSG1;
            outputStream.write(Msg.getBytes());
            outputStream.flush();
            ACKed.setSelected(false);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            outputStream.close();
            serialPort.close();
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        new SwitchBoard();
    }

    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if (e.getSource() == simulateOneCall) {
            sendToComputer();
        }
    }
   
    public void parseInMsg(String message){
        if(message.trim().length() == 0){//it is ACK
        }
        if(message.trim().length() == 23||message.trim().length() == 3){//package of one call.
            JOptionPane.showMessageDialog(this,"Computer got this:/n"+message);
        }
    }

    public void serialEvent(SerialPortEvent event) {       
        switch(event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
        case SerialPortEvent.DATA_AVAILABLE:
            byte[] readBuffer = new byte[50];

            try {
                while (inputStream.available() > 0) {
                    int numBytes = inputStream.read(readBuffer);
                    if(numBytes == 1){//is ACK
                        ACKed.setSelected(true);
                    }
                }
                String receivedMsg = new String(readBuffer);
                System.out.println("SwitchBoard got this: "+receivedMsg);
                //JOptionPane.showMessageDialog(this,"Aroha got this:/n"+receivedMsg);
                parseInMsg(receivedMsg);
            } catch (IOException e) {}
            break;
        }
    }

}
///
//Computer.java, 就是和交换机通信的PC了萨。
package simulateCTI;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class Computer extends JFrame implements Runnable, ActionListener,
        SerialPortEventListener {
    static final String PORT_TO_USE = "COM5";// virtual port for simulation.

    char ACK = (byte) 0x06;

    char STX = (byte) 0x02;

    char ETX = (byte) 0x03;
   
    String callOutStr = STX + "DphoneNumIs0507289000" + ETX;
    String readMemStr = STX + "M01" + ETX;

    boolean flag = false;

    static CommPortIdentifier PortId;// used to check the port.

    static Enumeration portList;// list all the availble ports.

    SerialPort serialPort;

    InputStream inputStream = null;

    OutputStream outputStream = null;

    String inMsg;

    Thread listener;

    // GUI
//    JButton startListen = new JButton("Start Listen");
//
//    JTextArea showSomething = new JTextArea();
//
//    JButton endListen = new JButton("End Listen");

    JLabel callTimeLb = new JLabel("Called Time: ");

    JLabel phoneNumLb = new JLabel("Phone Number: ");

    JButton callFromComputerBtn = new JButton("Call out");

    JButton readMemoryOfArohaBtn = new JButton("Read history record");

    Computer() {
        // set GUI
        super("Simulate the Computer side.");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(new GridLayout(4, 1));
        this.add(callTimeLb);
        this.add(phoneNumLb);
        this.add(callFromComputerBtn);
        this.add(readMemoryOfArohaBtn);

        this.setVisible(true);
        this.setSize(300, 500);
        pack();
        callFromComputerBtn.addActionListener(this);
        readMemoryOfArohaBtn.addActionListener(this);
        // Build serial port connection.
        openSerialPort();
    }

    public void run() {
        while (true) {
            try {
                Thread.sleep(500);// the CTI equipment will send ack in 100ms.
                if (flag) {
                    return;
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public void close() {
        try {
            inputStream.close();
            outputStream.close();
            serialPort.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == callFromComputerBtn) {
            try {
                outputStream.write(callOutStr.getBytes());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        if (e.getSource() == readMemoryOfArohaBtn) {
            try {
                outputStream.write(readMemStr.getBytes());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    public void openSerialPort() {
        portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            PortId = (CommPortIdentifier) portList.nextElement();
            if (PortId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                if (PortId.getName().equals(PORT_TO_USE)) {
                    try {
                        serialPort = (SerialPort) PortId.open(
                                "SwitchBoard_Simulation", 2000);
                        try {
                            serialPort.setSerialPortParams(9600,
                                    SerialPort.DATABITS_8,
                                    SerialPort.STOPBITS_1,
                                    SerialPort.PARITY_NONE);
                        } catch (UnsupportedCommOperationException e) {
                            e.printStackTrace();
                        }
                    } catch (PortInUseException e) {
                        e.printStackTrace();
                        System.out.println("the port is already in use!");
                    }
                }
            }
        }
        // open the io channel of the serial port.
        try {
            outputStream = serialPort.getOutputStream();
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // to listen the serial port.
        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException tle) {
            tle.printStackTrace();
        }
        serialPort.notifyOnDataAvailable(true);
    }

    public static void main(String args[]) {
        new Computer();
    }
   
    public void parseInMsg(String message){
        if(message.trim().length() == 0){//it is ACK
        }
        if(message.trim().length() == 29){//package of one call.
            JOptionPane.showMessageDialog(this,"Computer got this:/n"+message);
            callTimeLb.setText("Called Time: "+message.substring(0, 9));
            phoneNumLb.setText("Phone Number: "+message.substring(9, 29));
        }
    }

    public void serialEvent(SerialPortEvent event) {       
        switch (event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
        case SerialPortEvent.DATA_AVAILABLE:
            byte[] readBuffer = new byte[31];//max length is 31 bytes.

            try {
                while (inputStream.available() > 0) {
                    int numBytes = inputStream.read(readBuffer);
                }
                inMsg = new String(readBuffer);
                System.out.print("computer got: "+inMsg);
                parseInMsg(inMsg.trim());
                // send ACK to Aroha.
                outputStream.write((byte) 0x06);
            } catch (IOException e) {
            }
            break;
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值