[求助]关于eclipse下开发串口操作插件的问题

在使用Eclipse开发一个读取串口信息的插件时,作者遇到了一个问题:当以插件形式运行时,点击按钮会触发Unhandled event loop exception,原因是javax/comm/NoSuchPortException异常。问题出在尝试打开并读取串口时,插件无法正确识别或访问串口。

请教一下,我用eclipse开发一个可以读取串口信息的插件,把它单独作为应用程序可以正常运行.但以插件形式运行时点击按钮就会出现

Unhandled event loop exception
Reason:
javax/comm/NoSuchPortException异常.不知道是什么问题?

插件窗口程序:

package com.plugin.Hello;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import com.leon.serial.*;

/**
 * This class demonstrates JFace's ErrorDialog class
 */
public class DialogSample extends ApplicationWindow {
  /**
   * ShowError constructor
   */
  public DialogSample() {
    super(null);
  }
  /**
   * Runs the application
   */
  public void run() {
    // Don't return from open() until window closes
    setBlockOnOpen(true);

    // Open the main window
    open();

    // Dispose the display
    Display.getCurrent().dispose();
  }

  /**
   * Configures the shell
   *
   * @param shell the shell
   */
  protected void configureShell(Shell shell) {
    super.configureShell(shell);

    // Set the title bar text and the size
    shell.setText("read com");
    shell.setSize(400, 400);
  }

  /**
   * Creates the main window's contents
   *
   * @param parent the main window
   * @return Control
   */
  protected Control createContents(Composite parent) {
    Composite composite = new Composite(parent, SWT.NONE);
    composite.setLayout(new GridLayout(1, false));

    // Create a big text box to accept error text
    final Text text = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    text.setLayoutData(new GridData(GridData.FILL_BOTH));

    // Create the button to launch the error dialog
    Button show = new Button(composite, SWT.PUSH);
    show.setText("open serial port");
    show.addSelectionListener(new SelectionAdapter() {
      public void widgetSelected(SelectionEvent event) {
        SerialBean SB = new SerialBean(2);
        String Msg = "";
        SB.Initialize();
    
       Msg = SB.ReadPort(10);
       SB.ClosePort();
        text.setText(Msg);
      }
    });

    return composite;
  }
  /**
   * The application entry point
   *
   * @param args the command line arguments
   */
/*  public static void main(String[] args) {
    new DialogSample().run();
  }
  */
}

插件是根据helloworld改过来的

package com.plugin.Hello;

import org.eclipse.ui.plugin.*;
import org.osgi.framework.BundleContext;
import java.util.*;

/**
 * The main plugin class to be used in the desktop.
 */
public class HelloPlugin extends AbstractUIPlugin {
 //The shared instance.
 private static HelloPlugin plugin;
 //Resource bundle.
 private ResourceBundle resourceBundle;
 
 /**
  * The constructor.
  */
 public HelloPlugin() {
  super();
  plugin = this;
  try {
   resourceBundle = ResourceBundle.getBundle("com.plugin.Hello.HelloPluginResources");
  } catch (MissingResourceException x) {
   resourceBundle = null;
  }
 }

 /**
  * This method is called upon plug-in activation
  */
 public void start(BundleContext context) throws Exception {
  super.start(context);
 }

 /**
  * This method is called when the plug-in is stopped
  */
 public void stop(BundleContext context) throws Exception {
  super.stop(context);
 }

 /**
  * Returns the shared instance.
  */
 public static HelloPlugin getDefault() {
  return plugin;
 }

 /**
  * Returns the string from the plugin's resource bundle,
  * or 'key' if not found.
  */
 public static String getResourceString(String key) {
  ResourceBundle bundle = HelloPlugin.getDefault().getResourceBundle();
  try {
   return (bundle != null) ? bundle.getString(key) : key;
  } catch (MissingResourceException e) {
   return key;
  }
 }

 /**
  * Returns the plugin's resource bundle,
  */
 public ResourceBundle getResourceBundle() {
  return resourceBundle;
 }
}

/****************************串口初始化的package*********************************************/

/*
 * Created on 2005-3-3
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.leon.serial;

/**
 * @author leon.guo
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.io.*;


/**
 *
 * This class reads message from the specific serial port and save
 * the message to the serial buffer.
 *
 */
public class ReadSerial extends Thread
{
    private SerialBuffer ComBuffer;
    private InputStream ComPort;
        /**
         *
         * Constructor
         *
         * @param SB The buffer to save the incoming messages.
         * @param Port The InputStream from the specific serial port.
         *
         */
    public ReadSerial(SerialBuffer SB, InputStream Port)
    {
        ComBuffer = SB;
        ComPort = Port;
    }
    public void run()
    {
        int c;
        try
        {
            while (true)
            {
                c = ComPort.read();
                ComBuffer.PutChar(c);
            }
        } catch (IOException e) {}
    }
}

/*************************************************************************************************/

/*
 * Created on 2005-3-3
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.leon.serial;

/**
 * @author leon.guo
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.comm.*;
/**
 *
 * This bean provides some basic functions to implement full dulplex
 * information exchange through the srial port.
 *
 */
public class SerialBean
{
    static String PortName;
    CommPortIdentifier portId;
    SerialPort serialPort;
    static OutputStream out;
    static InputStream  in;
    SerialBuffer SB;
    ReadSerial   RT;
        /**
         *
         * Constructor
         *
         * @param PortID the ID of the serial to be used. 1 for COM1,
         * 2 for COM2, etc.
         *
         */
        public SerialBean(int PortID)
        {
            PortName = "COM" + PortID;
        }
       
  /**
         *
         * This function initialize the serial port for communication. It startss a
         * thread which consistently monitors the serial port. Any signal capturred
         * from the serial port is stored into a buffer area.
         *
         */
        public int Initialize()
        {
            int InitSuccess = 1;
            int InitFail    = -1;
        try
        {
            portId = CommPortIdentifier.getPortIdentifier(PortName);
            try
            {
                serialPort = (SerialPort)
                portId.open("Serial_Communication", 2000);
            } catch (PortInUseException e)
            {
                return InitFail;
            }
            //Use InputStream in to read from the serial port, and OutputStream
            //out to write to the serial port.
            try
            {
                in  = serialPort.getInputStream();
                out = serialPort.getOutputStream();
            } catch (IOException e)
            {
                return InitFail;
            }
            //Initialize the communication parameters to 9600, 8, 1, none.
            try
            {
                 serialPort.setSerialPortParams(9600,
                            SerialPort.DATABITS_8,
                            SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException e)
            {
                return InitFail;
            }
        } catch (NoSuchPortException e)
        {
            return InitFail;
        }
        // when successfully open the serial port,  create a new serial buffer,
        // then create a thread that consistently accepts incoming signals from
        // the serial port. Incoming signals are stored in the serial buffer.
        SB = new SerialBuffer();
        RT = new ReadSerial(SB, in);
        RT.start();
        // return success information
        return InitSuccess;
        }
        /**
         *
         * This function returns a string with a certain length from the incomin
         * messages.
         *
         * @param Length The length of the string to be returned.
         *
         */
        public String ReadPort(int Length)
        {
            String Msg;
            Msg = SB.GetMsg(Length);
            return Msg;
        }
        /**
         *
         * This function sends a message through the serial port.
         *
         * @param Msg The string to be sent.
         *
         */
        public void WritePort(String Msg)
        {
            int c;
            try
            {
                for (int i = 0; i < Msg.length(); i++)
                    out.write(Msg.charAt(i));
            } catch (IOException e)  {}
        }
        /**
         *
         * This function closes the serial port in use.
         *
         */
        public void ClosePort()
        {
            RT.stop();
            serialPort.close();
        }
}

/*************************************************************************************************/

/*
 * Created on 2005-3-3
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.leon.serial;

/**
 * @author leon.guo
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
/**
*
* This class implements the buffer area to store incoming data from the serial
* port.
*
*/
public class SerialBuffer
{
   private String Content = "";
   private String CurrentMsg, TempContent;
   private boolean available = false;
   private int LengthNeeded = 1;
       /**
        *
        * This function returns a string with a certain length from the incomin
        * messages.
        *
        * @param Length The length of the string to be returned.
        *
        */
   public synchronized String GetMsg(int Length)
   {
       LengthNeeded = Length;
       notifyAll();
     
       if (LengthNeeded > Content.length())
       {
           available = false;
           while (available == false)
           {
               try
               {
                   wait();
               } catch (InterruptedException e) { }
           }
       }
       CurrentMsg  = Content.substring(0, LengthNeeded);
       TempContent = Content.substring(LengthNeeded);
       Content = TempContent;
       LengthNeeded = 1;
       notifyAll();
       return CurrentMsg;
   }
       /**
        *
        * This function stores a character captured from the serial port to the
        * buffer area.
        *
        * @param t The char value of the character to be stored.
        *
        */
   public synchronized void PutChar(int c)
   {
       Character d = new Character((char) c);
       Content = Content.concat(d.toString());
       if (LengthNeeded < Content.length())
       {
           available = true;
       }
       notifyAll();
   }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值