SWT Serial Port Programming

Go down

SWT Serial Port Programming Empty SWT Serial Port Programming

ตั้งหัวข้อ by Admin on Thu Nov 19, 2015 3:01 am

This example will listen for the incoming data and retrieve from a serial port for the equipment that send data automatically, but some equipment need a request command from PC. This demo can support both type of communication protocol.

SWT Serial Port Programming Y9Jnfddv6StyBBJyJP_GC_MubSTpyuizoKpdGOlQvKRVc3w58KxAPvrI1wiOn3K2jqYmcUaEJv59gUt3kYhkJzOWD7yGu3blXNCl57VS0cMsyUF6bTR6MmR37fvFr0dCK32Qdyfa8tLha23cUkkk7d6meuZWOa6OVjTne4FrRhk6SnngCayEOv7FtzQHSwe4JjxS5jYEIPZ1S7HkWbFxgJHV3corS6kMS-cFONS2IyD_p_24RC6mowvN5t5eSSNJk1ngsR0TOB5H0gplSbtY0DH4wee1qxQixJgPropp0o434oxLF61bPSlaUeEURU2lZH3JsbaAhm5bG9h4OzOmlKJSBby2kQ7JkQdYlS6fAOixtI4UCNQ7tSejM-mnCfKA8paEwU2fPKf8LITJXefw1mm-yGyOhi_Fiwwd0_YamYlnGjRyQ6ZERXAq21yyFHF_J-DjEhHciUl0VPLo1znXUXOX4LB78pT_1EB1EVYmpa04eWsdL9xpvIN0G7bzETxtRdsrxrtyCtoc_xTWbQmjm8P_WWIiaFt9xC-eIPLizvw=w650-h400-no

Example code.

Code:
package com.java.app.rs232;

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.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/**
 * Example code for serial port event action using SWT component
 * @author psupawa@gmail.com
 */
public class SwtSerialPortDemo implements SerialPortEventListener {

 /**
 * To run the application
 * @param args
 */
 public static void main(String[] args) {
   new SwtSerialPortDemo();
 }
 
 // Declare variables
 private Display display;
 private Shell shell;
 private CommPortIdentifier portId;
 private SerialPort serialPort;
 private InputStream inputStream;
 private OutputStream outputStream;
 private Enumeration<?> portList;
 private Combo portChoice;
 private Combo baudRateList;
 private Combo dataBitList;
 private Combo stopBitList;
 private Combo parityChoice;
 private Label portConnectLabel;
 private Text textSend;
 private Text textData;
 private Text textArea;
 private Group testGroup;
 private Button connBtn;
 private Button sendBtn;
 private Button crSendCheck;
 private Button lfSendCheck;
 private Button crRcvCheck;
 private Button lfRcvCheck;
 private int portCounter = 0;
 private String textReceived;
 private Color initColor;
 private Color passColor;
 private Color failColor;
 private int[] STOP_BIT_INT = {1,3,2};

 /**
  * Constructor
  */
 public SwtSerialPortDemo() {
    display = new Display();
    shell = new Shell(display);
    shell.setText("SWT Serial Port Demo");
    shell.setSize(650, 400);
    Monitor primary = display.getPrimaryMonitor();
    Rectangle bounds = primary.getBounds();
    Rectangle rect = shell.getBounds();
    int x = bounds.x + (bounds.width - rect.width) / 2;
    int y = bounds.y + (bounds.height - rect.height) / 2;
    shell.setLocation(x, y);

    initColor = shell.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
    passColor = shell.getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN);
    failColor = shell.getDisplay().getSystemColor(SWT.COLOR_RED);
    initComponents();

    shell.open();
    textData.setText("");
    textSend.setText("");
    shell.addListener(SWT.Close, new Listener() {
       public void handleEvent(Event event) {
          if (serialPort != null) {
             MessageBox messageBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
             messageBox.setMessage("Please close COMM Port connection\nbefore closing application.");
             messageBox.setText("Warning");
             messageBox.open();
             event.doit = false;
          }
          else
             event.doit = true;
       }
    });
    while (!shell.isDisposed()) {
      if (!display.readAndDispatch()) {
        display.sleep();
      }
    }
    display.dispose();
    
 }
 
 /**
 * Initial the component
 */
 public void initComponents() {
    GridLayout gridLayout = new GridLayout(2, false);
    shell.setLayout(gridLayout);

    Group configGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
    configGroup.setText("Config:");
    configGroup.setLayout(new GridLayout(2, false));
    GridData gridData = new GridData(SWT.FILL, SWT.FILL, false, false);
    gridData.verticalSpan = 3;
    configGroup.setLayoutData(gridData);
    
    Label portLabel = new Label(configGroup, SWT.NONE);
    portLabel.setText("Port Name:");

    portList = CommPortIdentifier.getPortIdentifiers();

    portChoice = new Combo(configGroup, SWT.READ_ONLY);
    portChoice.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
               portChoice.add(portId.getName());
            }
    }
    portChoice.select(portChoice.getVisibleItemCount()-1);
    portChoice.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        portConnectLabel.setBackground(initColor);
        connBtn.setEnabled(true);
      }
    });

    Label baudrateLabel = new Label(configGroup, SWT.NULL);
    baudrateLabel.setText("Baud Rate:");

    baudRateList = new Combo(configGroup, SWT.READ_ONLY);
    baudRateList.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    baudRateList.add("300");
    baudRateList.add("2400");
    baudRateList.add("9600");
    baudRateList.add("14400");
    baudRateList.add("28800");
    baudRateList.add("38400");
    baudRateList.add("57600");
    baudRateList.add("152000");
    baudRateList.setText("9600");
    baudRateList.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
         // For your own action
      }
    });

    Label dataBitLabel = new Label(configGroup, SWT.NULL);
    dataBitLabel.setText("Data Bits:");

    dataBitList = new Combo(configGroup, SWT.READ_ONLY);
    dataBitList.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    dataBitList.add("5");
    dataBitList.add("6");
    dataBitList.add("7");
    dataBitList.add("8");
    dataBitList.setText("8");
    dataBitList.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
         // For your own action
      }
    });

    Label stopBitLabel = new Label(configGroup, SWT.NULL);
    stopBitLabel.setText("Stop Bits:");

    stopBitList = new Combo(configGroup, SWT.READ_ONLY);
    stopBitList.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    stopBitList.add("1");
    stopBitList.add("1.5");
    stopBitList.add("2");
    stopBitList.select(0);
    stopBitList.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        // For your own action
      }
    });
    
    Label parityLabel = new Label(configGroup, SWT.NULL);
    parityLabel.setText("Parity:");

    parityChoice = new Combo(configGroup, SWT.READ_ONLY);
    parityChoice.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
    parityChoice.add("None");
    parityChoice.add("Even");
    parityChoice.add("Mark");
    parityChoice.add("Odd");
    parityChoice.add("Space");
    parityChoice.select(0);
    parityChoice.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
        // For your own action
      }
    });
    
    // Create a horizontal separator
    Label separator = new Label(configGroup, SWT.HORIZONTAL | SWT.SEPARATOR);
    separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    gridData = new GridData(SWT.FILL, SWT.FILL, false, false);
    gridData.horizontalSpan = 2;
    separator.setLayoutData(gridData);
    
    // Dummy
    new Label(configGroup, SWT.NULL);
    new Label(configGroup, SWT.NULL);

    new Label(configGroup, SWT.NULL).setText("Action:");
    connBtn = new Button(configGroup, SWT.PUSH);
    connBtn.setText("Open");
    connBtn.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
         if (connBtn.getText().equals("Open")) {
           connect(portChoice.getText());
         }
         else {
           disconnect();
         }
      }
    });
    
    new Label(configGroup, SWT.NULL).setText("Status:");
    portConnectLabel = new Label(configGroup, SWT.BORDER);
    portConnectLabel.setText("     ");
    portConnectLabel.setBackground(initColor);
    portConnectLabel.setEnabled(false);
    
    testGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
    testGroup.setText("Send:");
    testGroup.setLayout(new GridLayout(6, false));
    GridData gridData2 = new GridData(SWT.FILL, SWT.FILL, true, false);
    testGroup.setLayoutData(gridData2);

    textSend = new Text(testGroup, SWT.BORDER);
    textSend.setText("AAAAAAAAAAAAAAAAAAAAAAAAAAA");
    textSend.setEnabled(false);
    textSend.addListener(SWT.Modify, new Listener() {
      public void handleEvent(Event e) {
        sendBtn.setEnabled(textSend.getText().trim().length() > 0);
      }
    });
    
    crSendCheck = new Button(testGroup, SWT.CHECK);
    crSendCheck.setText("CR");
    crSendCheck.setEnabled(false);
    lfSendCheck = new Button(testGroup, SWT.CHECK);
    lfSendCheck.setText("LF");
    lfSendCheck.setEnabled(false);

    sendBtn = new Button(testGroup, SWT.PUSH);
    sendBtn.setText("Send");
    sendBtn.addListener(SWT.Selection, new Listener() {
      public void handleEvent(Event event) {
         String outString = textSend.getText();
         if (crSendCheck.getSelection()) outString += String.valueOf((char)13);
         if (lfSendCheck.getSelection()) outString += String.valueOf((char)10);
         try {
            outputStream.write(outString.getBytes());
         }
         catch (IOException e) {
            textArea.append("Send error: "+e.getMessage()+"\n");
         }
      }
    });
    sendBtn.setEnabled(false);
    
    Group actionGroup = new Group(shell, SWT.SHADOW_ETCHED_IN);
    actionGroup.setText("Receive:");
    actionGroup.setLayout(new GridLayout(3, false));
    GridData gridData3 = new GridData(SWT.FILL, SWT.FILL, true, false);
    actionGroup.setLayoutData(gridData3);
    
    textData = new Text(actionGroup, SWT.BORDER);
    textData.setText("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    textData.setEnabled(false);
    textData.addListener(SWT.Modify, new Listener() {
       public void handleEvent(Event e) {
         // For your own action
       }
    });
    
    crRcvCheck = new Button(actionGroup, SWT.CHECK);
    crRcvCheck.setText("CR");
    crRcvCheck.setEnabled(false);
    lfRcvCheck = new Button(actionGroup, SWT.CHECK);
    lfRcvCheck.setText("LF");
    lfRcvCheck.setEnabled(false);
    
    textArea = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
    textArea.setLayoutData(new GridData(GridData.FILL_BOTH));
    textArea.setEnabled(false);
    
 }
 
 /**
 * Verify if port exist
 */
 public void verifyPort() {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
           portChoice.add(portId.getName());
           if (portId.getName().equals(portChoice.getText())) {
              connect(portId.getName());
           }
        }
    }
 }
 
    /**  
     * Sets the serial port parameters
     */  
    private void setSerialPortParameters() throws IOException {  
        try {  
            serialPort.setSerialPortParams(  
               Integer.valueOf(baudRateList.getText()),  
               Integer.valueOf(dataBitList.getText()),  
               STOP_BIT_INT[stopBitList.getSelectionIndex()],  
               parityChoice.getSelectionIndex()
            );  
        }
        catch (UnsupportedCommOperationException ex) {  
            throw new IOException("Unsupported serial port parameter");  
        }  
    }  
  
 /**
  * Open the connection
  * @param portName
  */
 public void connect(String portName) {
    boolean success = false;
    String statusMessage = "";
    portCounter++;
    try {
       CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(portName);
       serialPort = (SerialPort) portId.open("SerialCommunication"+String.valueOf(portCounter), 100);
       // Open the input and output streams for the connection.  
       inputStream = serialPort.getInputStream();
       outputStream = serialPort.getOutputStream();
       serialPort.addEventListener(this);
       serialPort.notifyOnDataAvailable(true);
       // Set the parameters of the connection.  
       setSerialPortParameters();
       readToClearBuffer();
       // Take control when success
       success = true;
       statusMessage = "Port open sucessful.";
    } catch (PortInUseException e) {
       statusMessage = "PortInUseException: "+e.getMessage();
    } catch (NoSuchPortException e) {
       statusMessage = "NoSuchPortException: "+e.getMessage();
    } catch (IOException e) {
       statusMessage = "IOException: "+e.getMessage();
    } catch (TooManyListenersException e) {
       statusMessage = "TooManyListenersException: "+e.getMessage();
    }
    portConnectLabel.setBackground(success ? passColor : failColor);
    textArea.setText(statusMessage + "\n");
    if (success) {
        connBtn.setText("Close");
        connBtn.pack();
        changeStatus(false);
        textArea.setEnabled(true);
    }
 }

 /**
 * Close the connection
 */
 public void disconnect() {
    try {
       if (inputStream != null) inputStream.close();
       if (outputStream != null) outputStream.close();
    } catch (IOException e) {
       // Leave as is
    }
    if (serialPort != null) {
       serialPort.close();
       serialPort = null;
    }
    textArea.append("Port closed."+"\n");
    connBtn.setText("Open");
    connBtn.pack();
    portConnectLabel.setBackground(initColor);
    changeStatus(true);
    sendBtn.setEnabled(false);
 }
    
 /**
  * Custom change control status
  * @param newState
  */
 private void changeStatus(boolean newState) {
    textData.setEnabled(!newState);
    crRcvCheck.setEnabled(!newState);
    lfRcvCheck.setEnabled(!newState);
    textSend.setEnabled(!newState);
    crSendCheck.setEnabled(!newState);
    lfSendCheck.setEnabled(!newState);
    portChoice.setEnabled(newState);
    baudRateList.setEnabled(newState);
    dataBitList.setEnabled(newState);
    stopBitList.setEnabled(newState);
    parityChoice.setEnabled(newState);
 }
    
 /**
  * Serial port event fired
  */
 @Override
 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:
         readPort();
            break;
        }
 }
    
 /**
  * Read data from serial port
  */
 public void readPort() {
     byte[] readBuffer = new byte[1024];
     int numBytes = 0;
     try {
         while (inputStream.available() > 0) {
             numBytes = inputStream.read(readBuffer);
         }
         textReceived = new String(readBuffer).substring(0, numBytes);
         displayResult();
     }
     catch (IOException e) {
         textArea.append("readPort(): "+e.getMessage()+"\n");
     }
 }
    
 /**
  * Read to clear buffer when start open the serial port
  */
 public void readToClearBuffer() {
     byte[] readBuffer = new byte[1024];
     try {
         while (inputStream.available() > 0) {
             inputStream.read(readBuffer);
         }
     }
     catch (IOException e) {
         // Leave as is
     }
 }
   
 /**
  * Display the result on SWT component
  */
 private void displayResult() {
     shell.getDisplay().asyncExec(new Runnable(){
         public void run() {
             crRcvCheck.setSelection(false);
             lfRcvCheck.setSelection(false);
             textData.setText(textReceived);
             for (int i=0; i<textReceived.length(); i++) {
                char c = textReceived.charAt(i);
                textArea.append("Data["+i+"], ascii = " + (int)c + ", char = " + (((int)c == 13)||((int)c == 10) ? "" : c) + "\n");
                if ((int)c == 13)
                   crRcvCheck.setSelection(true);
                if ((int)c == 10)
                   lfRcvCheck.setSelection(true);
             }
         }
     });
 }
    
}

Admin
Admin

จำนวนข้อความ : 13
Join date : 29/01/2014

http://maithai.thai-forum.net

ขึ้นไปข้างบน Go down

ขึ้นไปข้างบน


 
Permissions in this forum:
คุณไม่สามารถพิมพ์ตอบ