Java上位机

来源:互联网 发布:悟空在线软件下载 编辑:程序博客网 时间:2024/06/05 17:46
Java串口上位机 
接收两个不同从机发来的传感器(加速度、温湿度)数据 
配置步骤: 
1)创建类S_Frame;
2) 在eclipse创建的项目中插入jxl.jar ; 
3)在请求命令输入口中发送1,请求从机1的传感器数据;发送2,请求从机2的传感器数据。
import gnu.io.CommPortIdentifier;import gnu.io.PortInUseException;import gnu.io.SerialPort;import gnu.io.SerialPortEvent;import gnu.io.SerialPortEventListener;import gnu.io.UnsupportedCommOperationException;import jxl.Workbook;import jxl.format.Alignment;import jxl.format.Border;import jxl.format.BorderLineStyle;import jxl.format.Colour;import jxl.format.UnderlineStyle;import jxl.write.Label;import jxl.write.WritableCellFormat;import jxl.write.WritableFont;import jxl.write.WritableSheet;import jxl.write.WritableWorkbook;import jxl.write.WriteException;import java.awt.Color;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.Graphics;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.lang.reflect.InvocationTargetException;import java.util.ArrayList;import java.util.Enumeration;import java.util.*;import java.util.TooManyListenersException;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.swing.BorderFactory;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;class S_Frame extends JFrame implements ActionListener,ItemListener,SerialPortEventListener {       //检测系统中可用的通讯端口类    static CommPortIdentifier portId;    //Enumeration 为枚举型类,在util中    static Enumeration portList;        //输入输出流    InputStream inputStream;    OutputStream outputStream;        //RS-232的串行口    SerialPort serialPort;        Thread readThread;    String str = "";    List list = new ArrayList();// 获取数据列表String[] titles = new String[] { "X轴","Y轴","Z轴","","湿度","温度"};// 设置列中文名int columnLength[] = { 15, 15, 15, 5, 12, 12 };// 设置列宽WritableWorkbook wwb;WritableSheet ws1;WritableSheet ws2;    String[] toBeStored=new String[20];    //设立一个标志位    String flag;    int bit1=0;    int bit2=0;    int baudFlag=0;            /*输入框(输入到上位机)*/    JTextArea ADXL_message1 = new JTextArea("",6,16);    JTextArea DHT_message1 = new JTextArea("",6,16);    JTextArea ADXL_message2 = new JTextArea("",6,16);    JTextArea DHT_message2 = new JTextArea("",6,16);    //TextArea in_message3 = new TextArea("输入3口.打开COM口,设置波特率,数据位8,停止位1.");    JTextArea out_message = new JTextArea("",7,16);    JButton btnOpen = new JButton("打开串口");    JButton sendData = new JButton("发送数据");     JButton stopSendData = new JButton("停止发送");    JButton btnClose = new JButton("关闭串口");    JComboBox btnChoice;    JComboBox baudChoice;    JComboBox stopbit;    JComboBox checkbit;    JLabel jb1,jb2,jb3,jb4=null;    JPanel jp1,jp2,jp3,jp4=null;    JScrollPane jpScrol11,jpScrol12,jpScrol21,jpScrol22,outScrol=null;    byte data[] = new byte[1024];        //设置判断要是否关闭串口的标志    boolean mark;    /*构造方法:安排窗体*/S_Frame(){        init();                     this.setVisible(true);        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.setResizable(false);    }/*初始化函数,安排窗体*/public void init(){  setLayout(new FlowLayout());           btnChoice=new JComboBox<>();        baudChoice=new JComboBox<>();        stopbit = new JComboBox<>();        checkbit =new JComboBox<>();        btnChoice.addItem("请选择端口    ");        String[] comName = new String[]{"COM0","COM1","COM2","COM3","COM4","COM5","COM6","COM7","COM8","COM9","COM10"};        for (String name : comName) { // 遍历返回的.java文件名            btnChoice.addItem(name); // 把文件名添加到下拉列表中        }        baudChoice.addItem("请选择波特率");        String[] baudName = new String[]{"4800","9600","19200","115200"};        for (String name : baudName) { // 遍历返回的.java文件名        baudChoice.addItem(name); // 把文件名添加到下拉列表中        }         String[] stopName = new String[]{"1                        ","2"};        for (String name : stopName) { // 遍历返回的.java文件名        stopbit.addItem(name); // 把文件名添加到下拉列表中        }         String[] checkName = new String[]{"NONE                ","ODD","EVEN"};        for (String name : checkName) { // 遍历返回的.java文件名        checkbit.addItem(name); // 把文件名添加到下拉列表中        }         jb1 = new JLabel("端    口:");        jb2 = new JLabel("波特率:");        jb3 = new JLabel("停止位:");        jb4 = new JLabel("校验位:");        jp1 = new JPanel();        jp2 = new JPanel();        jp3 = new JPanel();        jp1.setPreferredSize(new Dimension(20,15));        jp1.setBorder(BorderFactory.createEtchedBorder());/*设置JPanel边界*/        jp2.setBorder(BorderFactory.createEtchedBorder());        jp3.setBorder(BorderFactory.createEtchedBorder());        jp1.add(jb1);        jp1.add(btnChoice);        jp1.add(jb2);              jp1.add(baudChoice);         jp1.add(jb3);        jp1.add(stopbit);        jp1.add(jb4);        jp1.add(checkbit);                jp1.add(btnOpen);        jp1.add(sendData);        jp1.add(stopSendData);        jp1.add(btnClose);                ADXL_message1.setLineWrap(true);        DHT_message1.setLineWrap(true);        ADXL_message2.setLineWrap(true);        DHT_message2.setLineWrap(true);        ADXL_message1.setBorder(BorderFactory.createEtchedBorder());        DHT_message1.setBorder(BorderFactory.createEtchedBorder());        ADXL_message2.setBorder(BorderFactory.createEtchedBorder());        DHT_message2.setBorder(BorderFactory.createEtchedBorder());        outScrol = new JScrollPane(out_message);        jp1.add(new JLabel("请求命令输入口:"));        jp1.add(outScrol);        jp2.add(new JLabel("数据采集单元①:                              "));        jpScrol11 =new JScrollPane(ADXL_message1);        jpScrol12 =new JScrollPane(DHT_message1);        jp2.add(new JLabel("加速度传感器ADXL345:                "));        jp2.add(jpScrol11);        jp2.add(new JLabel("温湿度传感器DHT11:                       "));        jp2.add(jpScrol12);                jp3.add(new JLabel("数据采集单元②:                              "));        jpScrol21 =new JScrollPane(ADXL_message2);        jpScrol22 =new JScrollPane(DHT_message2);        jp3.add(new JLabel("加速度传感器ADXL345:                "));        jp3.add(jpScrol21);        jp3.add(new JLabel("温湿度传感器DHT11:                       "));        jp3.add(jpScrol22);        this.add(jp1);        this.add(jp2);        this.add(jp3);        //this.add(new DrawGraphics());        this.setLayout(new GridLayout(1,4));        btnChoice.addItemListener(this);        baudChoice.addItemListener(this);        btnOpen.addActionListener(this);        sendData.addActionListener(this);        stopSendData.addActionListener(this);        btnClose.addActionListener(this);    }    /**    * 将实体类的信息写入Excel文件    *     * @param wwb  ws    *            形成Excel文件必备WritableWorkbook变量    *            形成sheet表格WritableSheet     * @param list    *            实体类集合    * @param row column    *  Excel文件sheet表中的行 列    * @param titles    *            excel标题名称    * @param columnLength    *            标题名称宽度    * @param fileds    *            对应标题所填充的实体类信息(属性名)    * @throws IOException    * @throws WriteException    * @throws SecurityException    * @throws NoSuchMethodException    * @throws InvocationTargetException    * @throws IllegalArgumentException    * @throws IllegalAccessException    */    public static  void writeExcel(WritableWorkbook wwb,WritableSheet ws,int row,int column, List list,    String[] titles, int[] columnLength, String[] fileds)    throws IOException, WriteException, NoSuchMethodException,    SecurityException, IllegalAccessException,    IllegalArgumentException, InvocationTargetException {        if (wwb != null) {       /*    * 表头单元格样式的设定 WritableFont.createFont("宋体"):设置字体为宋体 12:设置字体大小    * WritableFont.BOLD:设置字体加粗(BOLD:加粗 NO_BOLD:不加粗) false:设置非斜体    * UnderlineStyle.NO_UNDERLINE:没有下划线 Colour.BLACK 字体颜色 黑色    */    WritableFont titleFont = new WritableFont(    WritableFont.createFont("宋体"), 12, WritableFont.BOLD,    false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);    WritableCellFormat titleCellFormat = new WritableCellFormat(    titleFont);    // 字休居中    titleCellFormat.setAlignment(Alignment.CENTRE);    // 设置单元格背景色:表体为白色    titleCellFormat.setBackground(Colour.WHITE);    // 整个表格线为细线、黑色    titleCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN,    Colour.BLACK);    WritableFont contentFont = new WritableFont(    WritableFont.createFont("宋体"), 10, WritableFont.NO_BOLD,    false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);    WritableCellFormat contentCellFormat = new WritableCellFormat(    contentFont);    // 字休居中    contentCellFormat.setAlignment(Alignment.CENTRE);    // 设置单元格背景色:表体为白色    contentCellFormat.setBackground(Colour.WHITE);    // 整个表格线为细线、黑色    contentCellFormat.setBorder(Border.ALL, BorderLineStyle.THIN,    Colour.BLACK);    for (int i = 0; i < titles.length; i++) {    ws.setColumnView(i, columnLength[i]); // 设置列的宽度    Label label = new Label(i, 0, titles[i], titleCellFormat);    ws.addCell(label);    }    // 填充实体类的基本信息                         for(int n=column;n digitList = new ArrayList();                Pattern p = Pattern.compile("[^0-9]");                Matcher m = p.matcher(str);                String result = m.replaceAll("");                int[] temp = new int[9];                int[] count = new int[5];                for (int i = 0; i < result.length(); i++) {                digitList.add(result.substring(i, i+1));                }                System.out.println(digitList);                String[] toBeStored = digitList.toArray(new String[digitList.size()]);                    for(String s : toBeStored) {                         System.out.print(s);                  }                for(int i=0;i digitList = new ArrayList();                Pattern p = Pattern.compile("[^0-9]");                Matcher m = p.matcher(str);                String result = m.replaceAll("");                int[] temp = new int[9];                int[] count = new int[5];                for (int i = 0; i < result.length(); i++) {                digitList.add(result.substring(i, i+1));                }                System.out.println(digitList);                String[] toBeStored = digitList.toArray(new String[digitList.size()]);                    for(String s : toBeStored) {                         System.out.print(s);                  }                for(int i=0;i=6 && bit2 >= 6)    {    bit1=0;    bit2=0;                // 从内存中写入文件中        this.wwb.write();        // 关闭资源,释放内存        this.wwb.close();    }            }        } catch (IOException e) {} catch (WriteException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}     }    public static void main(String args[]) throws WriteException,    NoSuchMethodException, SecurityException, IllegalAccessException,    IllegalArgumentException, InvocationTargetException, IOException{            S_Frame S_win = new S_Frame();        S_win.setBounds(200,200,600,360);        S_win.setTitle("Java串口上位机");     // 首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象        S_win.wwb = Workbook.createWorkbook(new File("D:\\ceshi.xls"));// 创建一个可写入的工作表// Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置        S_win.ws1 =S_win.wwb.createSheet("设备1", 0);        S_win.ws2 =S_win.wwb.createSheet("设备2", 0);                S_win.addWindowListener(new WindowAdapter() {                    public void windowClosing(WindowEvent e) {                System.exit(0);            }        });           //S_win.pack();    }}