⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 comoperation.java

📁 用java编写的与单片机的串口通讯程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package myprojects.monitor;

import java.io.*;
import java.util.*;
import javax.comm.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import jxl.write.WritableWorkbook;
import jxl.write.WritableSheet;

public class ComOperation implements Runnable,SerialPortEventListener,ActionListener
{
	private CommPortIdentifier portId;
    private Enumeration portList;
	private SerialPort serialPort;
	
   	private OutputStream outputStream;
   	private String instruction = "";
   	private String stopMark = "!!";
    private InputStream inputStream;
    private InputStreamReader isr;
    
    private Thread readThread;
    
	private Monitor monitor;
	
	private String comName;
	
	static int speed = 9600;
	static int databit = 8;
	static int stopbit = 1;
	static int parity = 0; 
	 
	int rows = 0; 
    static Jexcel Excel = null;
	
	public String getComName()
	{
		return comName;
	}
	
	public Panel bag = new Panel();
    public TextField showMessageString = new TextField(60);
  	public Button runComBtn = new Button("接收数据");
  	public Button runBtn = new Button("全部接收");
  	private boolean runFlag = false;
  	
  	private ComParaDlg comParaDlg = new ComParaDlg();
  	private AlarmDlg alarmDlg = new AlarmDlg();
  	private AlarmDlg2 alarmDlg2 = new AlarmDlg2();
  	
    private String messageString = "";
	private String subString = "";    
	private String raughCast = "";   
	private int flag =0;
	
    public ComOperation(String comName, Monitor monitor) 
    {  
    	runComBtn.addActionListener(this);
    	runBtn.addActionListener(this);
    	showMessageString.setText(comName + " selected");
    	
    	bag.setSize(900,20);
    	
		bag.setLayout(new FlowLayout(0,5,0));
		bag.setBackground(Color.cyan);
		
		bag.add(showMessageString);
		bag.add(runComBtn);
		bag.add(runBtn);
    	
        portList = CommPortIdentifier.getPortIdentifiers();
        
		this.monitor = monitor;
		this.comName = comName;
		
		boolean findPort = false;
		//print the selected com name:
		System.out.println (comName);
        while (portList.hasMoreElements()) 
        {
            portId = (CommPortIdentifier) portList.nextElement();
            
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) 
            {
                if (portId.getName().equals(comName)) 
                {
                 	findPort = true;
                	break;
                }
            } 
        }
        if(findPort)
        {
        	this.comParaDlg.show();
        	try 
			{
				serialPort = (SerialPort) portId.open("ComOperation", 2000);
			} catch (PortInUseException e) {this.alarmDlg2.show();}
			
			try 
			{
				outputStream = serialPort.getOutputStream();
	            inputStream = serialPort.getInputStream();           
	            isr = new InputStreamReader(inputStream);//?
			} catch (IOException e) {}
			
			try 
			{
				serialPort.addEventListener(this);
			} catch (TooManyListenersException e) {}
			serialPort.notifyOnDataAvailable(true);
			try 
			{
			    serialPort.setSerialPortParams(this.speed, this.databit, this.stopbit, this.parity);
			} catch (UnsupportedCommOperationException e) {}
			
			readThread = new Thread(this);
			readThread.start();
    	}   
    }

    public void run() //
    {
        try 
        {
            Thread.sleep(1000);
        } catch (InterruptedException e) {}
    }

    public void serialEvent(SerialPortEvent event) 
    {
        //System.out.println("in");
        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[5000];
	            if(Excel!=null)
	            {      			
      			try 
	            {                            
 	                		            
 	                while (inputStream.available() > 0||raughCast.length()>=38) 
	                {                                         
	                    int numBytes = inputStream.read(readBuffer);	           
	                    //diaplay how many bytes in the readBuffer
	                    System.out.println ("OK:"+numBytes+" entered");
	      
	                    subString = new String(readBuffer,0,numBytes);
	                    //System.out.println (subString);
	                    
	                    raughCast += subString;
	                    System.out.println ("ROUGH:"+raughCast);
	                    
	                    String mark = "&&";
	                    
	                    int i = raughCast.indexOf(mark);                   
	                              
	                    //System.out.println("i:"+i);
	                    try
						{ 
							raughCast = raughCast.substring(i);
						}catch(IndexOutOfBoundsException esub){System.out.println("IndexOutOfBoundsException");}
	                    
	                    
	                   if(i!=-1&&raughCast.length() >= 38)
	                    {
	                    	try
	                    	{ 
	                    	    rows++;  // count the number of the rows
	                    		messageString = raughCast.substring(0,38);
	                    		System.out.println ("DATA:"+messageString);
	                    		raughCast = raughCast.substring(38);
	                    		
	                    		showMessageString.setText("Data from "+comName+": "+messageString);
	                    		monitor.saveData(messageString);
	                    		Excel.save(monitor.timeSave,monitor.temperatureSave,monitor.H2SSave,
	                    		           monitor.SO4Save,monitor.PHSave,rows); 
	                    			                    	  
	                    	}catch(Exception e)
	                    	{
	                    		e.printStackTrace();
	                    		//this.alarmDlg.show();
	                    	}
	                    }	                    
	                  
	                   int j = raughCast.indexOf(stopMark);	                   
	                   if(j!=-1&&j<38)
	                    {                  	
	                        Excel.close();
	                        Excel = null;
	                        rows = 0;
	                    	showMessageString.setText("数据传输完毕");	                    	
	                    }
	                }               
	                
	             System.out.println("rest:"+raughCast);	                

	            } catch (Exception e) {e.printStackTrace();}
	         }
	            break;	            
        }
        
    }
    
    public void actionPerformed(ActionEvent e)
	{
		String excelName = monitor.showName.getText().trim();				
		
		if(e.getActionCommand()=="接收数据")
		      instruction = "1";
		else if(e.getActionCommand()=="全部接收")
		      instruction = "2";	     
		
			System.out.println ("pressed");		
			try
			{
			  if(excelName.length()==0) 	
			   	this.alarmDlg.show();		        
		      else
		      {			   	
		        Excel = new Jexcel(excelName);
		    	this.outputStream.write(this.instruction.getBytes());
		    	System.out.println ("sent");
		       }
		        	     			    	
		    }catch(Exception exc){exc.printStackTrace();}		
	}			
}

class ComParaDlg extends JDialog implements ActionListener
{	
	private Label speed = new Label("传输速率");
	private Choice speedChoice = new Choice();
	
	private Label databit = new Label("数据比特");
	private Choice databitChoice = new Choice();
	
	private Label stopbit = new Label("停止比特"); 
	private Choice stopbitChoice = new Choice();
	
	private Label parity = new Label("奇偶校验");
	private Choice parityChoice = new Choice();
	
	private Button ok = new Button("确认");
	private Button cancel = new Button("取消");
	private Button exit = new Button("退出");
	
	public ComParaDlg()
	{
		this.setTitle("串口参数配置窗口");
		this.setModal(true);
		
		Container cp = getContentPane();   
		
		GridBagLayout cpLayout = new GridBagLayout();
	    GridBagConstraints gbc = new GridBagConstraints();
		cp.setLayout(cpLayout);
		
		/**
		 * add speed label
		 */
		 gbc.gridx = 1;
		 gbc.gridy = 1;
		 gbc.gridwidth = 1;
		 gbc.gridheight = 1;
		 gbc.fill = GridBagConstraints.NONE;
		 gbc.anchor = GridBagConstraints.NORTHWEST;
		 gbc.weightx = 1;
		 gbc.weighty = 0;
		 gbc.insets = new Insets(10, 60, 10, 15);
		 cpLayout.setConstraints(speed,gbc);
		 this.getContentPane().add(speed);
		 
		 /**
		 * add speedChoice label
		 */
		 gbc.gridx = 3;
		 gbc.gridy = 1;
		 gbc.gridwidth = 1;
		 gbc.gridheight = 1;
		 gbc.fill = GridBagConstraints.NONE;
		 gbc.anchor = GridBagConstraints.NORTHWEST;
		 gbc.weightx = 1;
		 gbc.weighty = 0;
		 gbc.insets = new Insets(10, 15, 10, 60);
		 speedChoice.addItem("9600");
		 speedChoice.addItem("4800");
		 speedChoice.addItem("19200");
		 cpLayout.setConstraints(speedChoice,gbc);
		 this.getContentPane().add(speedChoice);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -