Java上位机

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lantuxin/article/details/72934566

轮询方式获取从机传感器数据。


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 Runnable,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;    	
	int[] odd_Humi1 = new int[6]; 
	int[] odd_Temp1 = new int[6]; 
	int[] even_Humi1 = new int[6]; 
	int[] even_Temp1 = new int[6]; 
	int odd_humidity1=0,odd_temperature1=0,even_humidity1=0,even_temperature1=0;
	int even_flag1 = 0,odd_flag1=0,count_flag1=0;
	
	int[] odd_Humi2 = new int[6]; 
	int[] odd_Temp2 = new int[6]; 
	int[] even_Humi2 = new int[6]; 
	int[] even_Temp2 = new int[6]; 
	int odd_humidity2=0,odd_temperature2=0,even_humidity2=0,even_temperature2=0;
	int even_flag2 = 0,odd_flag2=0,count_flag2=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);
    }
public void run()
{
	System.out.println("A new thread!");
                 try {
                     serialPort = (SerialPort) portId.open("testSerialPort", 2000);
                 } catch (PortInUseException e) {}
                 //设置串口监听
                 try {
                     serialPort.addEventListener((SerialPortEventListener) this);
                 } catch (TooManyListenersException e) {}
                 
                 serialPort.notifyOnDataAvailable(true);
                 
                 /* 设置串口通讯参数 */
                 try {
                     serialPort.setSerialPortParams(baudFlag, SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                 } catch (UnsupportedCommOperationException e) {}
                 
                 try {
                     //打开输出流
                     outputStream = serialPort.getOutputStream();
                     //向设备发送数据
                     outputStream.write(data);
                     //获得输入流
                     inputStream = serialPort.getInputStream();
                 } catch (IOException e) {}                                                                       
}

    /**
    * 将实体类的信息写入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=6 && odd_flag1>=6)
                		{
                			count_flag1=0;
                			even_flag1=0;
                			odd_flag1=0;
                			odd_humidity1=(odd_Humi1[0]+odd_Humi1[1]+odd_Humi1[2]+odd_Humi1[3]+odd_Humi1[4]+odd_Humi1[5])/6;
                			odd_temperature1=(odd_Temp1[0]+odd_Temp1[1]+odd_Temp1[2]+odd_Temp1[3]+odd_Temp1[4]+odd_Temp1[5])/6;
                			even_humidity1=(even_Humi1[0]+even_Humi1[1]+even_Humi1[2]+even_Humi1[3]+even_Humi1[4]+even_Humi1[5])/6;
                			even_temperature1=(even_Temp1[0]+even_Temp1[1]+even_Temp1[2]+even_Temp1[3]+even_Temp1[4]+even_Temp1[5])/6;
                			System.out.println("odd_humidity1="+odd_humidity1);
                			if(odd_humidity1>700 && odd_temperature1>200)
                			{
                			DHT_message1.append("\r\nAVERAGE_odd_humidity1=" +odd_humidity1/10+"."+odd_humidity1%10+ "%\r\n");
                    		DHT_message1.append("\r\nAVERAGE_odd_temperature1=" +odd_temperature1/10+"."+odd_temperature1%10+ "℃\r\n");
                    		DHT_message1.append("\r\nAVERAGE_even_humidity1=" +even_humidity1/10+"."+even_humidity1%10+ "%\r\n");
                    		DHT_message1.append("\r\nAVERAGE_even_temperature1=" +even_temperature1/10+"."+even_temperature1%10+ "℃\r\n");
                			}
                		}
                		for(int i=0;i<3;i++)
                        {
                        	//System.out.print("count="+count[i]+'\t');  
                        	arr[i] = String.valueOf(count[i]/10); 
                        	//System.out.print("arr="+arr[i]+'\t');
                        }
                		System.out.println(bit1);
                		if(count[1]>200&& count[0]>70)
                		{
                		DHT_message1.append("humidity=" +arr[0]+".0%"+ "\r\n");
                		DHT_message1.append("temperature=" +arr[1]+".0℃"+ "\r\n");
                		}
                		S_Frame.writeExcel(this.wwb,this.ws1, bit1,4,this.list, this.titles, this.columnLength,arr);
                	}
            	}        		
            	str = null;
            	if(bit1>17 && bit2<1)
            	{
            		/*延时3秒*/
            		try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            		data[0]='2';
            		new Thread(this,"从机2线程").start();//开启一个线程
            		bit1=0;
            	}
            }
            if(mark != true && data[0]=='2')
            {           	                                             	                              
                if(this.toBeStored != null)
            	{
                	if((count[0]!=0)&&(count[1]!=0)&&(count[2]!=0))
                	{                		
                		System.out.println(bit2);
                		for(int i=0;i<3;i++)
                        {
                        	System.out.print("count="+count[i]+'\t');  
                        	arr[i] = String.valueOf(count[i]-100); 
                        	System.out.print("arr="+arr[i]+'\t');
                        }
                		//接收到的数据存放到文本区中 
                		ADXL_message2.append("X=" +arr[0]+ "\r\n");
                		ADXL_message2.append("Y=" +arr[1]+ "\r\n");
                		ADXL_message2.append("Z=" +arr[2]+ "\r\n");
                		S_Frame.writeExcel(this.wwb,this.ws2, bit2+1,0,this.list, this.titles, this.columnLength,arr);
                		bit2++;
                	}
                	if((count[2]==0)&&(count[1]!=0))
                	{
                		/*数据预处理,按奇偶分两批对传感器数据进行预处理*/
                		/*取出奇数组传感器数据*/
                		if(odd_flag2<6 && count_flag2%2!=0)
                		{
                			odd_Humi2[odd_flag2]=count[0];
                			odd_Temp2[odd_flag2]=count[1];
                			odd_flag2++;
                		}
                		/*取出偶数组传感器数据*/
                		if(even_flag2<6 && count_flag2%2==0)
                		{
                			System.out.println("\r\n count_flag2= "+count_flag2+"\r\n");
                			even_Humi2[even_flag2]=count[0];
                			even_Temp2[even_flag2]=count[1];
                			even_flag2++;
                		}
                		count_flag2++;   
                		if(even_flag2>=6 && odd_flag2>=6)
                		{
                			count_flag2=0;
                			even_flag2=0;
                			odd_flag2=0;
                			odd_humidity2=(odd_Humi2[0]+odd_Humi2[1]+odd_Humi2[2]+odd_Humi2[3]+odd_Humi2[4]+odd_Humi2[5])/6;
                			odd_temperature2=(odd_Temp2[0]+odd_Temp2[1]+odd_Temp2[2]+odd_Temp2[3]+odd_Temp2[4]+odd_Temp2[5])/6;
                			even_humidity2=(even_Humi2[0]+even_Humi2[1]+even_Humi2[2]+even_Humi2[3]+even_Humi2[4]+even_Humi2[5])/6;
                			even_temperature2=(even_Temp2[0]+even_Temp2[1]+even_Temp2[2]+even_Temp2[3]+even_Temp2[4]+even_Temp2[5])/6;
                			System.out.println("odd_humidity2="+odd_humidity2);
                			DHT_message2.append("\r\nAVERAGE_odd_humidity2=" +odd_humidity2/10+"."+odd_humidity2%10+ "%\r\n");
                    		DHT_message2.append("\r\nAVERAGE_odd_temperature2=" +odd_temperature2/10+"."+odd_temperature2%10+ "℃\r\n");
                    		DHT_message2.append("\r\nAVERAGE_even_humidity2=" +even_humidity2/10+"."+even_humidity2%10+ "%\r\n");
                    		DHT_message2.append("\r\nAVERAGE_even_temperature2=" +even_temperature2/10+"."+even_temperature2%10+ "℃\r\n");
                		}
                		for(int i=0;i<3;i++)
                        {
                        	System.out.print("count="+count[i]+'\t');  
                        	arr[i] = String.valueOf(count[i]/10); 
                        	System.out.print("arr="+arr[i]+'\t');
                        }
                		System.out.println("位置2="+bit2);
                		DHT_message2.append("humidity=" +arr[0]+".0%"+ "\r\n");
                		DHT_message2.append("temperature=" +arr[1]+".0℃"+ "\r\n");
                		S_Frame.writeExcel(this.wwb,this.ws2, bit2,4,this.list, this.titles, this.columnLength,arr);
                	}
            	} 
            	str = null;
            	if(bit2>13)
            	{
            		/*延时3秒*/
            		try {
                        Thread.sleep(8000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
            		data[0]='1';
            		new Thread(this,"从机2线程").start();//开启一个线程
            		bit2=0;
            	}
            }
            /*经验证,每一次收到数据,都会对Excel写一遍,但后续数据未写进去,猜测是writeExcel方法的问题*/
    		
    		if(bit1>=6 && bit2 >= 6)
    		{
    			bit1=0;
    			bit2=0;
                // 从内存中写入文件中
        		this.wwb.write();
        		// 关闭资源,释放内存
        		this.wwb.close();
    		}
            }
        } catch (IOException e) {} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.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();
    }
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页