记录自己第一次用swing做的简易串口通信工具

一年级水平。可以控制继电器的开关和获取电流电压数据,要获取更多数据就复制那块代码修改命令就行了,当然,根据modbus报文的不同,也可以实现其他功能。要使用的话,图片自己去找,记得修改路径。

package main;

import gnu.io.PortInUseException;
import gnu.io.SerialPort;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.text.DefaultCaret;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import java.awt.SystemColor;
import java.awt.Font;

import javax.swing.JTextArea;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.UIManager;

import utils.ByteUtils;
import utils.ShowUtils;
import manager.SerialPortManager;

import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;

public class ClientPort extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private JPanel contentPane;

    // 程序界面宽度
    public final int WIDTH = 800;
    // 程序界面高度
    public final int HEIGHT = 600;
    // 设置window的icon(自定义Windows窗口的icon图标)
    Toolkit toolkit = getToolkit();
    Image icon = toolkit.getImage(ClientPort.class.getResource("computer.png"));
    private JTextField txtLog;

    // 串口列表
    private List<String> CommList = null;
    // 串口对象
    private SerialPort Serialport;

    private JComboBox<String> commChoice = new JComboBox<String>();

    private JButton openportButton = new JButton("打开串口");

    private JComboBox<String> baudChoice = new JComboBox<String>();

    private JButton sendData = new JButton("发送");

    private JTextArea textArea = new JTextArea();// 指令显示区
    private final JTextArea textArea_1 = new JTextArea();// 指令发送区

    private JRadioButton DataHexChoice = new JRadioButton("Hex", true);
    private JRadioButton DataASCIIChoice = new JRadioButton("ASCLL");

    private JLabel mA1 = new JLabel("", JLabel.CENTER);

    private JToggleButton renovate = new JToggleButton("");// 刷新

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ClientPort frame = new ClientPort();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     * 
     * @throws IOException
     */
    public ClientPort() throws IOException {

        initView();
        initData();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        contentPane = new JPanel();
        contentPane.setBackground(Color.LIGHT_GRAY);
        contentPane.setBorder(new EmptyBorder(5, 5, 12, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        // 上面部分
        JPanel panel = new JPanel();
        panel.setForeground(SystemColor.controlHighlight);
        panel.setBounds(0, 0, 794, 91);
        panel.setBorder(BorderFactory.createLineBorder(Color.gray));
        contentPane.add(panel);
        panel.setLayout(null);
        // 打开串口按钮
        openportButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if ("打开串口".equals(openportButton.getText())
                        && Serialport == null) {
                    openSerialPort(e);
                } else {
                    closeSerialPort(e);
                }

            }
        });
        openportButton.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        openportButton.setBounds(0, 0, 151, 91);
        panel.add(openportButton);
        // 查询参数按钮
        JButton btnNewButton_1 = new JButton("查询参数");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textArea.setText("型号:11 03 14 00 00 10 43 66" + "\r\n"
                        + "名称:11 03 10 88 00 10 C2 7C");
            }
        });
        btnNewButton_1.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        btnNewButton_1.setBounds(150, 0, 151, 91);
        panel.add(btnNewButton_1);

        JPanel panel_2 = new JPanel();
        panel_2.setBounds(643, 0, 151, 89);
        panel.add(panel_2);
        panel_2.setLayout(null);

        commChoice.setBounds(64, 10, 77, 26);
        commChoice.addPopupMenuListener(new PopupMenuListener() {

            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                CommList = SerialPortManager.findPorts();
                // 检查是否有可用串口,有则加入选项中
                if (CommList == null || CommList.size() < 1) {
                    ShowUtils.warningMessage("没有搜索到有效串口!");
                } else {
                    int index = commChoice.getSelectedIndex();
                    commChoice.removeAllItems();
                    for (String s : CommList) {
                        commChoice.addItem(s);
                    }
                    commChoice.setSelectedIndex(index);
                }
            }

            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                // NO OP
            }

            public void popupMenuCanceled(PopupMenuEvent e) {
                // NO OP
            }
        });
        panel_2.add(commChoice);

        baudChoice.setBounds(64, 46, 77, 26);
        panel_2.add(baudChoice);

        JLabel label = new JLabel("    串口");
        label.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        label.setBounds(10, 16, 54, 15);
        panel_2.add(label);

        JLabel label_1 = new JLabel("  波特率");
        label_1.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        label_1.setBounds(10, 52, 54, 15);
        panel_2.add(label_1);

        renovate.setToolTipText("刷新数据");
        renovate.setBackground(SystemColor.control);
        renovate.setBounds(300, 0, 151, 91);
        renovate.setContentAreaFilled(false);// 图片填充
        renovate.setSelectedIcon(new ImageIcon("src/Icon/renovate_on.png"));
        renovate.setIcon(new ImageIcon("src/Icon/renovate_off.png"));
        renovate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JToggleButton renovate = (JToggleButton) e.getSource();
                String s1 = "1103006000018684";// 检测电流
                if (Serialport == null) {
                    ShowUtils.warningMessage("请先打开串口再操作!");
                    return;
                }
                if (renovate.isSelected()) {// 检查是否选中该元素
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s1));

                } else {
                    ShowUtils.warningMessage("数据刷新已关闭!");
                    return;
                }
            }
        });
        panel.add(renovate);

        // 右部分
        JPanel panel_r = new JPanel();
        panel_r.setBackground(Color.WHITE);
        panel_r.setForeground(Color.BLACK);
        panel_r.setBounds(557, 91, 237, 345);
        panel_r.setBorder(BorderFactory.createLineBorder(Color.white));
        contentPane.add(panel_r);
        panel_r.setLayout(null);
        // Log区
        txtLog = new JTextField();
        txtLog.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        txtLog.setBackground(SystemColor.controlHighlight);
        txtLog.setText("Log");
        txtLog.setBounds(0, 0, 237, 21);
        txtLog.setEditable(false);// Log后面禁止输入字符
        panel_r.add(txtLog);
        txtLog.setColumns(10);
        textArea.setFont(new Font("微软雅黑", Font.PLAIN, 13));
        // 指令显示区
        textArea.setBounds(1, 1, 235, 344);
        textArea.setFocusable(false);
        textArea.setLineWrap(true);// 自动换行
        panel_r.add(textArea);
        // 滚动条
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setBounds(0, 21, 237, 324);
        scrollPane
                .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);// 垂直滚动条自动出现
        DefaultCaret caret = (DefaultCaret) textArea.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);// 滚动条随文字刷新在下方显示
        panel_r.add(scrollPane);

        // 左部分
        JPanel panel_l = new JPanel();
        panel_l.setBackground(SystemColor.control);
        panel_l.setBounds(0, 91, 554, 481);
        panel_l.setBorder(BorderFactory.createLineBorder(Color.white));
        contentPane.add(panel_l);
        panel_l.setLayout(null);

        JToggleButton DO_1 = new JToggleButton("");
        DO_1.setToolTipText("DO-1");
        DO_1.setBackground(SystemColor.control);
        DO_1.setBounds(39, 42, 75, 40);
        DO_1.setBorderPainted(false);// 取消边框
        DO_1.setContentAreaFilled(false);// 图片填充
        DO_1.setSelectedIcon(new ImageIcon("src/Icon/on.png"));
        DO_1.setIcon(new ImageIcon("src/Icon/off.png"));
        DO_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JToggleButton DO_1 = (JToggleButton) e.getSource();
                String s1 = "11050000FF008EAA";// DO-1开
                String s2 = "110500000000CF5A";// DO-1关
                // String data = textArea.getText().toString();
                /*
                 * if (toggleBtn.isSelected()) { textArea_1.setText(s1); }else {
                 * textArea_1.setText(s2); }
                 */
                if (Serialport == null) {
                    ShowUtils.warningMessage("请先打开串口再操作!");
                    return;
                }
                if (DO_1.isSelected()) {
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s1));
                } else {
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s2));
                }
            }
        });
        panel_l.add(DO_1);

        JToggleButton DO_2 = new JToggleButton("");
        DO_2.setToolTipText("DO-2");
        DO_2.setContentAreaFilled(false);
        DO_2.setBorderPainted(false);
        DO_2.setBackground(SystemColor.menu);
        DO_2.setBounds(166, 42, 75, 40);
        DO_2.setSelectedIcon(new ImageIcon("src/Icon/on.png"));
        DO_2.setIcon(new ImageIcon("src/Icon/off.png"));
        DO_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JToggleButton DO_2 = (JToggleButton) e.getSource();
                String s1 = "11050001FF00DF6A";// DO-2开
                String s2 = "1105000100009E9A";// DO-2关
                if (Serialport == null) {
                    ShowUtils.warningMessage("请先打开串口再操作!");
                    return;
                }
                if (DO_2.isSelected()) {
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s1));
                } else {
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s2));
                }
            }
        });
        panel_l.add(DO_2);

        JLabel lblNewLabel = new JLabel("DO-1");
        lblNewLabel.setBounds(65, 17, 30, 15);
        panel_l.add(lblNewLabel);

        JLabel lblDo = new JLabel("DO-2");
        lblDo.setBounds(192, 17, 30, 15);
        panel_l.add(lblDo);

        JToggleButton DO_3 = new JToggleButton("");
        DO_3.setToolTipText("DO-3");
        DO_3.setContentAreaFilled(false);
        DO_3.setBorderPainted(false);
        DO_3.setBackground(SystemColor.menu);
        DO_3.setBounds(302, 42, 75, 40);
        DO_3.setSelectedIcon(new ImageIcon("src/Icon/on.png"));
        DO_3.setIcon(new ImageIcon("src/Icon/off.png"));
        DO_3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JToggleButton DO_3 = (JToggleButton) e.getSource();
                String s1 = "11050002FF002F6A";// DO_3开
                String s2 = "1105000200006E9A";// DO_3关
                if (Serialport == null) {
                    ShowUtils.warningMessage("请先打开串口再操作!");
                    return;
                }
                if (DO_3.isSelected()) {
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s1));
                } else {
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s2));
                }
            }
        });
        panel_l.add(DO_3);

        JLabel lblDo_1 = new JLabel("DO-3");
        lblDo_1.setBounds(329, 17, 30, 15);
        panel_l.add(lblDo_1);

        JToggleButton DO_4 = new JToggleButton("");
        DO_4.setToolTipText("DO-4");
        DO_4.setContentAreaFilled(false);
        DO_4.setBorderPainted(false);
        DO_4.setBackground(SystemColor.menu);
        DO_4.setBounds(436, 42, 75, 40);
        DO_4.setSelectedIcon(new ImageIcon("src/Icon/on.png"));
        DO_4.setIcon(new ImageIcon("src/Icon/off.png"));
        DO_4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JToggleButton DO_4 = (JToggleButton) e.getSource();
                String s1 = "11050003FF007EAA";// DO_4开
                String s2 = "1105000300003F5A";// DO_4关
                if (Serialport == null) {
                    ShowUtils.warningMessage("请先打开串口再操作!");
                    return;
                }
                if (DO_4.isSelected()) {
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s1));
                } else {
                    SerialPortManager.sendToPort(Serialport,
                            ByteUtils.hexStr2Byte(s2));
                }
            }
        });
        panel_l.add(DO_4);

        JLabel lblDo_2 = new JLabel("DO-4");
        lblDo_2.setBounds(459, 17, 30, 15);
        panel_l.add(lblDo_2);

        JPanel dial_1 = new JPanel();
        dial_1.setBounds(39, 110, 180, 148);
        dial_1.setBorder(BorderFactory.createLoweredBevelBorder());
        panel_l.add(dial_1);
        dial_1.setLayout(null);

        mA1.setBounds(33, 111, 116, 27);
        dial_1.add(mA1);

        JLabel lblNewLabel_2 = new JLabel("电流(mA)", JLabel.CENTER);
        lblNewLabel_2.setBounds(62, 89, 60, 22);
        dial_1.add(lblNewLabel_2);

        JPanel dial_2 = new JPanel();
        dial_2.setBorder(BorderFactory.createLoweredBevelBorder());
        dial_2.setBounds(309, 110, 180, 148);
        panel_l.add(dial_2);
        dial_2.setLayout(null);

        JPanel dial_3 = new JPanel();
        dial_3.setBorder(BorderFactory.createLoweredBevelBorder());
        dial_3.setBounds(39, 303, 180, 148);
        panel_l.add(dial_3);
        dial_3.setLayout(null);

        JPanel dial_4 = new JPanel();
        dial_4.setBorder(BorderFactory.createLoweredBevelBorder());
        dial_4.setBounds(309, 303, 180, 148);
        panel_l.add(dial_4);
        dial_4.setLayout(null);

        JPanel panel_1 = new JPanel();
        panel_1.setBackground(UIManager.getColor("CheckBox.background"));
        panel_1.setBounds(557, 437, 237, 135);
        contentPane.add(panel_1);
        panel_1.setLayout(null);

        textArea_1.setBounds(0, 0, 237, 97);
        textArea_1.setLineWrap(true);// 自动换行
        panel_1.add(textArea_1);

        sendData.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                sendData(e);
            }
        });
        sendData.setBounds(0, 97, 84, 38);
        panel_1.add(sendData);

        JButton button_1 = new JButton("清空");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 清空文本输入区
                textArea_1.setText("");
            }
        });
        button_1.setBounds(153, 97, 84, 38);
        panel_1.add(button_1);

        DataHexChoice.setBounds(82, 97, 66, 17);
        panel_1.add(DataHexChoice);

        DataASCIIChoice.setBounds(82, 118, 66, 17);
        panel_1.add(DataASCIIChoice);

    }

    /**
     * 初始化窗口
     */
    private void initView() {
        // 禁止窗口最大化
        setResizable(false);
        // 设置icon
        setIconImage(icon);
        // 设置程序窗口居中显示
        Point p = GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getCenterPoint();
        setBounds(p.x - WIDTH / 2, p.y - HEIGHT / 2, WIDTH, HEIGHT);
        getContentPane().setLayout(null);
        setTitle("串口通信");

        addWindowListener(new WindowAdapter() {
            // 添加对窗口状态的监听
            public void windowClosing(WindowEvent arg0) {
                // 当窗口关闭时
                System.exit(0); // 退出程序
            }
        });

    }

    /**
     * 初始化数据
     */
    private void initData() {
        CommList = SerialPortManager.findPorts();
        // 检查是否有可用串口,有则加入选项中
        if (CommList == null || CommList.size() < 1) {
            ShowUtils.warningMessage("没有搜索到有效串口!");
        } else {
            for (String s : CommList) {
                commChoice.addItem(s);
            }
        }
        baudChoice.addItem("9600");
        baudChoice.addItem("19200");
        baudChoice.addItem("38400");
        baudChoice.addItem("57600");
        baudChoice.addItem("115200");
    }

    /**
     * 打开串口
     * 
     * @param evt
     *            点击事件
     */
    private void openSerialPort(java.awt.event.ActionEvent evt) {
        // 获取串口名称
        String commName = (String) commChoice.getSelectedItem();
        // 获取波特率,默认为9600
        int baudrate = 9600;
        String bps = (String) baudChoice.getSelectedItem();
        baudrate = Integer.parseInt(bps);
        // 检查串口名称是否获取正确
        if (commName == null || commName.equals("")) {
            ShowUtils.warningMessage("没有搜索到有效串口!");
        } else {
            try {
                Serialport = SerialPortManager
                        .openPort(commName, baudrate, bps);
                if (Serialport != null) {
                    textArea.setText("串口已打开" + "\r\n");
                    openportButton.setText("关闭串口");
                }
            } catch (PortInUseException e) {
                ShowUtils.warningMessage("串口已被占用!");
            }
        }

        // 添加串口监听
        SerialPortManager.addListener(Serialport,
                new SerialPortManager.DataAvailableListener() {

                    public void dataAvailable() {
                        byte[] data = null;
                        try {
                            if (Serialport == null) {
                                ShowUtils.errorMessage("串口对象为空,监听失败!");
                            } else {
                                // 读取串口数据
                                data = SerialPortManager.readFromPort(Serialport);
                                logFile();
                                // 以十六进制的形式接收数据
                                if (DataHexChoice.isSelected()) {
                                    textArea.append(ByteUtils
                                            .byteArrayToHexString(data)
                                            + "\r\n");
                                    electricity();
                                }
                                // 以字符串的形式接收数据
                                if (DataASCIIChoice.isSelected()) {
                                    textArea.append(new String(data) + "\r\n");
                                }
                            }

                        } catch (Exception e) {
                            ShowUtils.errorMessage(e.toString());
                            // 发生读取错误时显示错误信息后退出系统
                            System.exit(0);
                        }

                    }
                });

    }

    /**
     * 关闭串口
     * 
     * @param evt
     *            点击事件
     */
    private void closeSerialPort(java.awt.event.ActionEvent evt) {
        SerialPortManager.closePort(Serialport);
        textArea.setText("串口已关闭" + "\r\n");
        openportButton.setText("打开串口");
        Serialport = null;
    }

    /**
     * 发送数据
     * 
     * @param evt
     *            点击事件
     */
    private void sendData(java.awt.event.ActionEvent evt) {
        // 待发送数据
        String data = textArea_1.getText().toString();

        if (Serialport == null) {
            ShowUtils.warningMessage("请先打开串口!");
            return;
        }

        if ("".equals(data) || data == null) {
            ShowUtils.warningMessage("请输入要发送的数据!");
            return;
        }

        // 以十六进制的形式发送数据
        if (DataHexChoice.isSelected()) {
            SerialPortManager.sendToPort(Serialport,
                    ByteUtils.hexStr2Byte(data));
        }

        // 以字符串的形式发送数据
        if (DataASCIIChoice.isSelected()) {
            SerialPortManager.sendToPort(Serialport, data.getBytes());
        }

    }

    /**
     * 接收电流数据
     * 
     * @throws IOException
     * 
     */
    private void electricity() throws IOException {
        String s1 = "1103006000018684";// 检测电流

        if (renovate.isSelected()) {
            SerialPortManager.sendToPort(Serialport, ByteUtils.hexStr2Byte(s1));
            BufferedReader br = new BufferedReader(new StringReader(textArea
                    .getText().toString()));
            String result = null;
            String line = br.readLine();
            String mAdata;
            while ((line = br.readLine()) != null) {
                result = line;
            }
            br.close();
            mAdata = result.substring(6, 10);
            String str = Integer.valueOf(mAdata, 16).toString();
            double a = Integer.parseInt(str);
            double b = a / 1000;
            String s = String.valueOf(b);
            mA1.setText(s);
        }

    }

    /**
     * 写入Log
     */
    private void logFile() throws IOException {
        FileWriter fWriter = new FileWriter(
                "D:/workspace/SerialDemo/logFile.txt");
        BufferedWriter bWriter = new BufferedWriter(fWriter);
        String log = textArea.getText().toString();
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd hh:mm:ss");
        bWriter.write(ft.format(dNow) + log);
        bWriter.close();

    }

}
View Code
package manager;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import utils.ArrayUtils;
import utils.ShowUtils;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

/**
 * 串口管理
 * 
 * @author
 */
@SuppressWarnings("all")
public class SerialPortManager {

    /**
     * 查找所有可用端口
     * 
     * @return 可用端口名称列表
     */
    public static final ArrayList<String> findPorts() {
        // 获得当前所有可用串口
        Enumeration<CommPortIdentifier> portList = CommPortIdentifier
                .getPortIdentifiers();
        ArrayList<String> portNameList = new ArrayList<String>();
        // 将可用串口名添加到List并返回该List
        while (portList.hasMoreElements()) {
            String portName = portList.nextElement().getName();
            portNameList.add(portName);
        }
        return portNameList;
    }

    /**
     * 打开串口
     * 
     * @param portName
     *            端口名称
     * @param baudrate
     *            波特率
     * @return 串口对象
     * @throws PortInUseException
     *             串口已被占用
     */
    public static final SerialPort openPort(String portName, int baudrate,
            String data) throws PortInUseException {
        try {
            // 通过端口名识别端口
            CommPortIdentifier portIdentifier = CommPortIdentifier
                    .getPortIdentifier(portName);
            // 打开端口,并给端口名字和一个timeout(打开操作的超时时间)
            CommPort commPort = portIdentifier.open(portName, 2000);
            // 判断是不是串口
            if (commPort instanceof SerialPort) {
                SerialPort serialPort = (SerialPort) commPort;
                try {
                    byte[] arr_buff;

                    // 设置一下串口的波特率等参数
                    // 数据位:8
                    // 停止位:1
                    // 校验位:None
                    serialPort.setSerialPortParams(baudrate,
                            SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {
                    e.printStackTrace();
                }
                return serialPort;
            }
        } catch (NoSuchPortException e1) {
            e1.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭串口
     * 
     * @param serialport
     *            待关闭的串口对象
     */
    public static void closePort(SerialPort serialPort) {
        if (serialPort != null) {
            serialPort.close();
        }
    }

    /**
     * 往串口发送数据
     * 
     * @param serialPort
     *            串口对象
     * @param order
     *            待发送数据
     */
    public static void sendToPort(SerialPort serialPort, byte[] order) {
        OutputStream out = null;
        try {
            out = serialPort.getOutputStream();
            out.write(order);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从串口读取数据
     * 
     * @param serialPort
     *            当前已建立连接的SerialPort对象
     * @return 读取到的数据
     */
    public static byte[] readFromPort(SerialPort serialPort) {
        InputStream in = null;
        byte[] bytes = {};
        try {
            in = serialPort.getInputStream();
            // 缓冲区大小为一个字节
            byte[] readBuffer = new byte[1];
            int bytesNum = in.read(readBuffer);
            while (bytesNum > 0) {
                bytes = ArrayUtils.concat(bytes, readBuffer);
                bytesNum = in.read(readBuffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    /**
     * 添加监听器
     * 
     * @param port
     *            串口对象
     * @param listener
     *            串口存在有效数据监听
     */
    public static void addListener(SerialPort serialPort,
            DataAvailableListener listener) {
        try {
            // 给串口添加监听器
            serialPort.addEventListener(new SerialPortListener(listener));
            // 设置当有数据到达时唤醒监听接收线程
            serialPort.notifyOnDataAvailable(true);
            // 设置当通信中断时唤醒中断线程
            serialPort.notifyOnBreakInterrupt(true);
        } catch (TooManyListenersException e) {
            e.printStackTrace();
        }
    }

    /**
     * 串口监听
     */
    public static class SerialPortListener implements SerialPortEventListener {

        private DataAvailableListener mDataAvailableListener;

        public SerialPortListener(DataAvailableListener mDataAvailableListener) {
            this.mDataAvailableListener = mDataAvailableListener;
        }

        public void serialEvent(SerialPortEvent serialPortEvent) {
            switch (serialPortEvent.getEventType()) {
            case SerialPortEvent.DATA_AVAILABLE: // 1.串口存在有效数据
                if (mDataAvailableListener != null) {
                    mDataAvailableListener.dataAvailable();
                }
                break;

            case SerialPortEvent.OUTPUT_BUFFER_EMPTY: // 2.输出缓冲区已清空
                break;

            case SerialPortEvent.CTS: // 3.清除待发送数据
                break;

            case SerialPortEvent.DSR: // 4.待发送数据准备好了
                break;

            case SerialPortEvent.RI: // 5.振铃指示
                break;

            case SerialPortEvent.CD: // 6.载波检测
                break;

            case SerialPortEvent.OE: // 7.溢位(溢出)错误
                break;

            case SerialPortEvent.PE: // 8.奇偶校验错误
                break;

            case SerialPortEvent.FE: // 9.帧错误
                break;

            case SerialPortEvent.BI: // 10.通讯中断
                ShowUtils.errorMessage("与串口设备通讯中断");
                break;

            default:
                break;
            }
        }
    }

    /**
     * 串口存在有效数据监听
     */
    public interface DataAvailableListener {
        /**
         * 串口存在有效数据
         */
        void dataAvailable();
    }
}
View Code
package utils;

/**
 * 数组工具
 * 
 * @author 
 */
public class ArrayUtils {

    /**
     * 合并数组
     * 
     * @param firstArray
     *            第一个数组
     * @param secondArray
     *            第二个数组
     * @return 合并后的数组
     */
    public static byte[] concat(byte[] firstArray, byte[] secondArray) {
        if (firstArray == null || secondArray == null) {
            return null;
        }
        byte[] bytes = new byte[firstArray.length + secondArray.length];
        System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);
        System.arraycopy(secondArray, 0, bytes, firstArray.length, secondArray.length);
        return bytes;
    }
}
View Code
package utils;

import java.nio.ByteBuffer;
import java.util.Locale;

/**
 * Byte转换工具
 * 
 * @author 
 */
public class ByteUtils {

    /**
     * 十六进制字符串转byte[]
     * 
     * @param hex
     *            十六进制字符串
     * @return byte[]
     */
    public static byte[] hexStr2Byte(String hex) {
        if (hex == null) {
            return new byte[] {};
        }

        // 奇数位补0
        if (hex.length() % 2 != 0) {
            hex = "0" + hex;
        }

        int length = hex.length();
        ByteBuffer buffer = ByteBuffer.allocate(length / 2);
        for (int i = 0; i < length; i++) {
            String hexStr = hex.charAt(i) + "";
            i++;
            hexStr += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexStr, 16);
            buffer.put(b);
        }
        return buffer.array();
    }

    /**
     * byte[]转十六进制字符串
     * 
     * @param array
     *            byte[]
     * @return 十六进制字符串
     */
    public static String byteArrayToHexString(byte[] array) {
        if (array == null) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            buffer.append(byteToHex(array[i]));
        }
        return buffer.toString();
    }

    /**
     * byte转十六进制字符
     * 
     * @param b
     *            byte
     * @return 十六进制字符
     */
    public static String byteToHex(byte b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() == 1) {
            hex = '0' + hex;
        }
        return hex.toUpperCase(Locale.getDefault());
    }


}
View Code
package utils;

import javax.swing.JOptionPane;

/**
 * 提示框
 * 
 * @author 
 */
public class ShowUtils {

    /**
     * 消息提示
     * 
     * @param message
     *            消息内容
     */
    public static void message(String message) {
        JOptionPane.showMessageDialog(null, message);
    }

    /**
     * 警告消息提示
     * 
     * @param message
     *            消息内容
     */
    public static void warningMessage(String message) {
        JOptionPane.showMessageDialog(null, message, "警告",
                JOptionPane.WARNING_MESSAGE);
    }

    /**
     * 错误消息提示
     * 
     * @param message
     *            消息内容
     */
    public static void errorMessage(String message) {
        JOptionPane.showMessageDialog(null, message, "错误",
                JOptionPane.ERROR_MESSAGE);
    }

    /**
     * 自定义的消息提示
     * 
     * @param title
     *            标题
     * @param message
     *            消息内容
     */
    public static void plainMessage(String title, String message) {
        JOptionPane.showMessageDialog(null, message, title,
                JOptionPane.PLAIN_MESSAGE);
    }

    /**
     * 带有选择功能的提示
     * 
     * @param title
     *            标题
     * @param message
     *            消息内容
     * @return 是/否 0/1
     */
    public static boolean selectMessage(String title, String message) {
        int isConfirm = JOptionPane.showConfirmDialog(null, message, title,
                JOptionPane.YES_NO_OPTION);
        if (0 == isConfirm) {
            return true;
        }
        return false;
    }
}
View Code

 

posted @ 2020-05-28 16:49  阿飞滴滴滴  阅读(257)  评论(0)    收藏  举报