Example #1
0
  private void write(byte[] data) {
    try {
      if (m_out == null) {
        m_PortIdPrinter =
            CommPortIdentifier.getPortIdentifier(
                m_sPortScale); // Tomamos el puerto
        m_CommPortPrinter =
            (SerialPort) m_PortIdPrinter.open("PORTID", 2000); // Abrimos el puerto

        m_out = m_CommPortPrinter.getOutputStream(); // Tomamos el chorro de escritura
        m_in = m_CommPortPrinter.getInputStream();

        m_CommPortPrinter.addEventListener(this);
        m_CommPortPrinter.notifyOnDataAvailable(true);

        m_CommPortPrinter.setSerialPortParams(
            4800,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_ODD); // Configuramos el puerto
      }
      m_out.write(data);
    } catch (NoSuchPortException e) {
      e.printStackTrace();
    } catch (PortInUseException e) {
      e.printStackTrace();
    } catch (UnsupportedCommOperationException e) {
      e.printStackTrace();
    } catch (TooManyListenersException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #2
0
  public void init() {
    getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) getCellRenderer();
    setCellRenderer(new BrowserTreeCellRenderer());

    //
    // Keep up to date with whats clicked when....

    getSelectionModel().addTreeSelectionListener(this);

    addMouseListener(
        new MouseAdapter() {
          public void mouseClicked(MouseEvent e) {
            maybeDoBrowse(e);
          }

          public void mousePressed(MouseEvent e) {
            maybeDoPopup(e);
          }

          public void mouseReleased(MouseEvent e) {
            maybeDoPopup(e);
          }
        });

    DataTipManager.get().register(this);

    try {
      getDropTarget().addDropTargetListener(this);
    } catch (TooManyListenersException e1) {
      log.error(e1.getMessage(), e1);
    }

    popupMenu = PopupMenuFactory.createBrowserTreePopup(this);
  }
Example #3
0
 // starts the event listener that knows whenever data is available to be read
 // pre: an open serial port
 // post: an event listener for the serial port that knows when data is recieved
 public void initListener() {
   try {
     serialPort.addEventListener(this);
     serialPort.notifyOnDataAvailable(true);
   } catch (TooManyListenersException e) {
     logText = "Too many listeners. (" + e.toString() + ")";
     System.out.println(logText + "\n");
   }
 }
  private void initEventListenersAndIO() {
    try {
      input = serialPort.getInputStream();
      output = serialPort.getOutputStream();
      serialPort.addEventListener(new SerialRxEvent(input, deviceRx));
      serialPort.notifyOnDataAvailable(true);

    } catch (TooManyListenersException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #5
0
  private void makeDropTarget(
      final java.io.PrintStream out, final java.awt.Component c, boolean recursive) {
    // Make drop target
    final java.awt.dnd.DropTarget dt = new java.awt.dnd.DropTarget();
    try {
      dt.addDropTargetListener(dropListener);
    } // end try
    catch (java.util.TooManyListenersException e) {
      e.printStackTrace();
      log(
          out,
          "FileDrop: Drop will not work due to previous error. Do you have another listener attached?");
    } // end catch

    // Listen for hierarchy changes and remove the drop target when the parent gets cleared out.
    c.addHierarchyListener(
        new java.awt.event.HierarchyListener() {

          public void hierarchyChanged(java.awt.event.HierarchyEvent evt) {
            log(out, "FileDrop: Hierarchy changed.");
            java.awt.Component parent = c.getParent();
            if (parent == null) {
              c.setDropTarget(null);
              log(out, "FileDrop: Drop target cleared from component.");
            } // end if: null parent
            else {
              new java.awt.dnd.DropTarget(c, dropListener);
              log(out, "FileDrop: Drop target added to component.");
            } // end else: parent not null
          } // end hierarchyChanged
        }); // end hierarchy listener
    if (c.getParent() != null) {
      new java.awt.dnd.DropTarget(c, dropListener);
    }

    if (recursive && (c instanceof java.awt.Container)) {
      // Get the container
      java.awt.Container cont = (java.awt.Container) c;

      // Get it's components
      java.awt.Component[] comps = cont.getComponents();

      // Set it's components as listeners also
      for (int i = 0; i < comps.length; i++) {
        makeDropTarget(out, comps[i], recursive);
      }
    } // end if: recursively set components as listener
  } // end dropListener
 /**
  * Send a simple invite request from the RI and check whether it is properly delivered by the TI
  * SipProvider
  */
 public void testReceiveRequest() {
   try {
     // create an empty invite request.
     Request invite = createRiInviteRequest(null, null, null);
     RequestEvent receivedRequestEvent = null;
     try {
       // Send using RI and collect using TI
       eventCollector.collectRequestEvent(tiSipProvider);
       riSipProvider.sendRequest(invite);
       waitForMessage();
       receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
       assertNotNull("The sent request was not received at the other end!", receivedRequestEvent);
       assertNotNull(
           "The sent request was not received at the other end!",
           receivedRequestEvent.getRequest());
     } catch (TooManyListenersException ex) {
       // This time adding the listener is (sort of) part of the test
       // so we fail instead of just "throwing on" the exc
       ex.printStackTrace();
       fail(
           "A TooManyListenersException was thrown while trying to add "
               + "a SipListener to a TI SipProvider.");
     } catch (SipException ex) {
       throw new TckInternalError("The RI failed to send the request!", ex);
     }
     // question: should we compare sent and received request?
     // my opinion: finding a discrepancy while comparing requests
     // would most probably mean a parse error and parsing is not what
     // we are currently testing
     // Transaction initiating requests should not have a server transaction
     // associated with them as the application might decide to handle the
     // request statelessly
     assertNull(
         "The Tested Implementation has implicitly created a ServerTransaction "
             + "for the received request. Transactions should only be created "
             + "explicitly using the SipProvider.getNewXxxTransaction() method.",
         receivedRequestEvent.getServerTransaction());
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
  /** @return */
  private static Component getActiveArea() {
    if (activeArea == null) {
      activeArea =
          new BufferedImagePanel() {
            public void paintComponent(Graphics g) {
              super.paintComponent(g);
              if (onlyPDFs == null) {
                return;
              }

              // draw list of file names
              final Graphics2D g2d = (Graphics2D) g;
              g2d.setRenderingHints(GraphicsUtils.getBestRenderingHints());
              g2d.setColor(TRANSLUCENT_GRAY);
              g2d.setFont(FONT);
              int stringY = (int) ((activeArea.getHeight() - onlyPDFs.size() * 40) / 2.0);
              for (File f : onlyPDFs) {
                g2d.drawString(f.getName(), 50, stringY);
                stringY += 50;
              }
            }
          };
      activeArea.setBorder(BorderFactory.createMatteBorder(10, 10, 10, 10, Color.LIGHT_GRAY));
      activeArea.setBackground(Color.DARK_GRAY);
      fileTransferHandler = new FileTransferHandler();
      activeArea.setTransferHandler(fileTransferHandler);

      try {
        dropTarget = new DropTarget();
        dropTarget.setComponent(activeArea);
        dropTarget.addDropTargetListener(getDropTargetAdapter());
      } catch (TooManyListenersException e) {
        e.printStackTrace();
      }

      pdfLogo = ImageCache.loadBufferedImage(PaperToolkit.getDataFile("icons/pdfIcon.png"));
    }
    return activeArea;
  }
Example #8
0
  /** Creates a new {@link TreeDragDemo} object. */
  public TreeDragDemo() {
    super("TreeDragDemo");
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    TreeTransferHandler transferHandler = new TreeTransferHandler();

    this.treeLeft = new ExtTree();
    this.treeLeft.setDragEnabled(true);
    this.treeLeft.setTransferHandler(transferHandler);

    try {
      this.treeLeft.getDropTarget().addDropTargetListener(new TreeDropTargetListener());
    } catch (TooManyListenersException ex) {
      ex.printStackTrace();
    }

    JScrollPane spLeft = new JScrollPane(this.treeLeft);
    spLeft.setPreferredSize(new Dimension(200, 400));

    this.treeRight = new ExtTree();
    this.treeRight.setDragEnabled(true);
    this.treeRight.setTransferHandler(transferHandler);

    JScrollPane spRight = new JScrollPane(this.treeRight);
    spRight.setPreferredSize(new Dimension(200, 400));

    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(spLeft);
    getContentPane().add(spRight);

    pack();
    setResizable(false);
    setVisible(true);

    setLocationRelativeTo(null);
  }
Example #9
0
  @Override
  protected void init() {
    getTreeTable().initTreeTable();
    // Create the root node
    initRootNode();

    getTreeTable()
        .getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        .put(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.ALT_DOWN_MASK), "cutTask");
    getTreeTable()
        .getTree()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              @Override
              public void valueChanged(TreeSelectionEvent e) {}
            });

    getTreeTable().getTree().addTreeExpansionListener(new GanttTreeExpansionListener());

    ToolTipManager.sharedInstance().registerComponent(getTreeTable());

    getTreeTable().insertWithLeftyScrollBar(this);
    mySelectionManager.addSelectionListener(
        new Listener() {
          @Override
          public void selectionChanged(List<Task> currentSelection) {}

          @Override
          public void userInputConsumerChanged(Object newConsumer) {
            if (getTreeTable().getTable().isEditing()) {
              getTreeTable()
                  .getTable()
                  .editingStopped(new ChangeEvent(getTreeTable().getTreeTable()));
            }
          }
        });
    getTreeTable()
        .getTree()
        .addFocusListener(
            new FocusAdapter() {
              @Override
              public void focusGained(FocusEvent e) {
                super.focusGained(e);
                mySelectionManager.setUserInputConsumer(this);
              }
            });
    try {
      GanttTreeDropListener dropListener = new GanttTreeDropListener();
      getTreeTable().getDropTarget().addDropTargetListener(dropListener);
      Color selectionBackground = UIManager.getColor("Table.selectionBackground");
      Color dropBackground =
          new Color(
              selectionBackground.getRed(),
              selectionBackground.getGreen(),
              selectionBackground.getBlue(),
              64);
      Color foreground = UIManager.getColor("Table.selectionForeground");
      myDragHighlighter = new ColorHighlighter(dropListener, dropBackground, foreground);
    } catch (TooManyListenersException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
  }
Example #10
0
  private void initialize() {

    // ==========================================
    /*
     * get System porperties:
     */
    String operatingSystem = null;
    Properties p = System.getProperties();
    Enumeration e = p.elements();
    while (e.hasMoreElements()) {
      operatingSystem = e.nextElement().toString();
      //				System.out.println(operatingSystem);
      if (operatingSystem.equals("Linux")) {
        logger.debug("found " + operatingSystem + " Operating System");
        comPort = "/dev/ttyS0";
        break;
      }
      if (operatingSystem.equals("Windows XP")) {
        logger.debug("found " + operatingSystem + " Operating System");
        comPort = "COM1";
        break;
      }

      //				if(operatingSystem.equals("Linux") || operatingSystem.equals("Windows")) {
      //					logger.debug("found "+operatingSystem+" Operating System");
      //					break;
      //				}
    }
    //	===============end===========================

    Enumeration pList = CommPortIdentifier.getPortIdentifiers();
    //		logger.debug("(Khepera) initializeeeee()...");

    while (pList.hasMoreElements()) {
      CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();

      if (cpi.getName().equals(comPort)) {
        try {
          com = null;
          com = (SerialPort) cpi.open("KHEPERA_" + comPort, 1000);
          try {

            //	========================================
            /* under Linux this block is crucial to setSerialPortParams()
             * - i have no idea why...
             */
            String s =
                "default settings: "
                    + com.getBaudRate()
                    + " "
                    + com.getDataBits()
                    + " "
                    + com.getParity()
                    + " "
                    + com.getStopBits();
            System.out.println(s);
            //	===============end=========================

            com.setSerialPortParams(
                57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);
            System.out.println(
                "Current settings: "
                    + com.getBaudRate()
                    + " "
                    + com.getDataBits()
                    + " "
                    + com.getParity()
                    + " "
                    + com.getStopBits());
          } catch (UnsupportedCommOperationException e1) {
            logger.debug("(Khepera) UnsupportedCommOperation: " + e1);
            e1.printStackTrace();
          }
          //					try {
          //						com.setSerialPortParams(BAUDRATE,
          //								com.DATABITS_8,
          //								com.STOPBITS_2,
          //								com.PARITY_NONE);
          //						com.setFlowControlMode(com.FLOWCONTROL_NONE);
          //					} catch (UnsupportedCommOperationException e1) {
          //						logger.debug("(Khepera) UnsupportedCommOperation: "+e1);
          //						e1.printStackTrace();
          //					}
          logger.debug("[Khepera.initialize()] established " + comPort);

          out = null;
          out = com.getOutputStream();
          inStream = null;
          inStream = com.getInputStream();

          byte[] readBuffer2 = new byte[1000];
          if (inStream.available() > 0) {
            int numBytes2 = inStream.read(readBuffer2);
            String result2 = new String(readBuffer2, 0, numBytes2);
            logger.debug("result2: " + result2);
          }

          //					in = null;
          in = new BufferedReader(new InputStreamReader(inStream));

          bufferedKheperaAnswer =
              new BufferedKheperaAnswer(logger, inStream, this, writelock, debug, operatingSystem);
          try {
            com.addEventListener(bufferedKheperaAnswer);

            com.notifyOnOutputEmpty(true);
            com.notifyOnDataAvailable(true);
            com.notifyOnOverrunError(true);
            com.notifyOnBreakInterrupt(true);
            com.notifyOnCarrierDetect(true);
            com.notifyOnCTS(true);
            com.notifyOnDSR(true);
            com.notifyOnFramingError(true);
            com.notifyOnParityError(true);
            com.notifyOnRingIndicator(false);
          } catch (TooManyListenersException e1) {
            logger.debug(
                "[Khepera.initialize()] can not add further eventListeners to serialPort object"
                    + e);
            e1.printStackTrace();
          }
        } catch (PortInUseException e2) {
          logger.debug("[Khepera.initialize()] Port in use: " + e2);
          e2.printStackTrace();
        } catch (IOException e3) {
          logger.debug(
              "[Khepera.initialize()] IOException while initialising COMport: <"
                  + comPort
                  + ">"
                  + e);
          e3.printStackTrace();
        }
        break;
      }
    }
    if (com == null)
      logger.error(
          "[Khepera.initialize()] unable to find specified COMport "
              + comPort
              + ". giving up! (the robot is not connected yet.)");
    else {
      logger.debug("[Khepera.initialize()] starting bufferedKheperaAnswer.start()");
      bufferedKheperaAnswer.start();

      if (debug) logger.debug("[Khepera.initialize()] initialize() finished");

      update = new KheperaUpdateManager(this, logger, debug);
      logger.debug("[Khepera.initialize()] starting KheperaUpdateManager update.start()");
      update.start();
    }
  }
Example #11
0
  public String openPort(String portName, String appName) {
    // open the port in XPressNet mode, check ability to set moderators
    try {
      // get and open the primary port
      CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
      try {
        activeSerialPort = (SerialPort) portID.open(appName, 2000); // name of program, msec to wait
      } catch (PortInUseException p) {
        return handlePortBusy(p, portName, log);
      }
      // try to set it for XNet
      try {
        setSerialPort();
      } catch (gnu.io.UnsupportedCommOperationException e) {
        log.error("Cannot set serial parameters on port " + portName + ": " + e.getMessage());
        return "Cannot set serial parameters on port " + portName + ": " + e.getMessage();
      }

      // set timeout
      try {
        activeSerialPort.enableReceiveTimeout(10);
        log.debug(
            "Serial timeout was observed as: "
                + activeSerialPort.getReceiveTimeout()
                + " "
                + activeSerialPort.isReceiveTimeoutEnabled());
      } catch (Exception et) {
        log.info("failed to set serial timeout: " + et);
      }

      // get and save stream
      serialStream = activeSerialPort.getInputStream();

      // purge contents, if any
      purgeStream(serialStream);

      // report status?
      if (log.isInfoEnabled()) {
        // report now
        log.info(
            portName
                + " port opened at "
                + activeSerialPort.getBaudRate()
                + " baud with"
                + " DTR: "
                + activeSerialPort.isDTR()
                + " RTS: "
                + activeSerialPort.isRTS()
                + " DSR: "
                + activeSerialPort.isDSR()
                + " CTS: "
                + activeSerialPort.isCTS()
                + "  CD: "
                + activeSerialPort.isCD());
      }
      if (log.isDebugEnabled()) {
        // report additional status
        log.debug(
            " port flow control shows "
                + (activeSerialPort.getFlowControlMode() == SerialPort.FLOWCONTROL_RTSCTS_OUT
                    ? "hardware flow control"
                    : "no flow control"));
      }
      // arrange to notify later
      activeSerialPort.addEventListener(
          new SerialPortEventListener() {
            public void serialEvent(SerialPortEvent e) {
              int type = e.getEventType();
              switch (type) {
                case SerialPortEvent.DATA_AVAILABLE:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: DATA_AVAILABLE is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: OUTPUT_BUFFER_EMPTY is " + e.getNewValue());
                  }
                  setOutputBufferEmpty(true);
                  return;
                case SerialPortEvent.CTS:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: CTS is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.DSR:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: DSR is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.RI:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: RI is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.CD:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: CD is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.OE:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: OE (overrun error) is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.PE:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: PE (parity error) is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.FE:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: FE (framing error) is " + e.getNewValue());
                  }
                  return;
                case SerialPortEvent.BI:
                  if (log.isDebugEnabled()) {
                    log.debug("SerialEvent: BI (break interrupt) is " + e.getNewValue());
                  }
                  return;
                default:
                  if (log.isDebugEnabled()) {
                    log.debug(
                        "SerialEvent of unknown type: " + type + " value: " + e.getNewValue());
                  }
                  return;
              }
            }
          });
      try {
        activeSerialPort.notifyOnFramingError(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnFramingError: " + e);
        }
      }

      try {
        activeSerialPort.notifyOnBreakInterrupt(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnBreakInterrupt: " + e);
        }
      }

      try {
        activeSerialPort.notifyOnParityError(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnParityError: " + e);
        }
      }

      try {
        activeSerialPort.notifyOnOutputEmpty(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnOutputEmpty: " + e);
        }
      }

      try {
        activeSerialPort.notifyOnOverrunError(true);
      } catch (Exception e) {
        if (log.isDebugEnabled()) {
          log.debug("Could not notifyOnOverrunError: " + e);
        }
      }

      opened = true;

    } catch (gnu.io.NoSuchPortException p) {
      return handlePortNotFound(p, portName, log);
    } catch (IOException ioe) {
      log.error("IOException exception while opening port " + portName + " trace follows: " + ioe);
      ioe.printStackTrace();
      return "IO exception while opening port " + portName + ": " + ioe;
    } catch (java.util.TooManyListenersException tmle) {
      log.error(
          "TooManyListenersException while opening port " + portName + " trace follows: " + tmle);
      tmle.printStackTrace();
      return "Too Many Listeners exception while opening port " + portName + ": " + tmle;
    }

    return null; // normal operation
  }
Example #12
0
  /**
   * Opens the communication port.
   *
   * @throws Exception if an error occurs.
   */
  public void open() throws Exception {

    // If this is Linux then first of all we need to check that
    // device file exists. Otherwise call to m_PortIdentifyer.open()
    // method will crash JVM.
    // It is ugly patch but it is too late...
    if (SystemUtils.IS_OS_LINUX) {
      File portDevFile = new File(m_Parameters.getPortName());

      if (!portDevFile.exists()) {
        throw new Exception(
            "Modbus serial device " + m_Parameters.getPortName() + " doesn't exist!");
      }
    }

    // 1. obtain a CommPortIdentifier instance
    try {
      m_PortIdentifyer = CommPortIdentifier.getPortIdentifier(m_Parameters.getPortName());
    } catch (NoSuchPortException e) {
      final String errMsg =
          "Could not get port identifier, maybe insufficient permissions. " + e.getMessage();
      logger.debug(errMsg);
      throw new Exception(errMsg);
    }
    logger.trace("Got Port Identifier");

    // 2. open the port, wait for given timeout
    try {
      m_SerialPort = (SerialPort) m_PortIdentifyer.open("Modbus Serial Master", 30000);
    } catch (PortInUseException e) {
      logger.debug("open port failed: " + e.getMessage());

      throw new Exception(e.getMessage());
    }
    logger.trace("Got Serial Port");

    // 3. set the parameters
    try {
      setConnectionParameters();
    } catch (Exception e) {
      // ensure it is closed
      m_SerialPort.close();
      logger.debug("parameter setup failed: " + e.getMessage());
      throw e;
    }

    if (Modbus.SERIAL_ENCODING_ASCII.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusASCIITransport();
    } else if (Modbus.SERIAL_ENCODING_RTU.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusRTUTransport();
      setReceiveTimeout(m_Parameters.getReceiveTimeout()); // just here for the moment.
    } else if (Modbus.SERIAL_ENCODING_BIN.equals(m_Parameters.getEncoding())) {
      m_Transport = new ModbusBINTransport();
    }
    m_Transport.setEcho(m_Parameters.isEcho());

    // Open the input and output streams for the connection. If they won't
    // open, close the port before throwing an exception.
    try {
      m_SerialIn = m_SerialPort.getInputStream();
      m_Transport.setCommPort(m_SerialPort);
      //       m_Transport.prepareStreams(m_SerialIn,
      //                                  m_SerialPort.getOutputStream());
    } catch (IOException e) {
      m_SerialPort.close();
      logger.debug(e.getMessage());

      throw new Exception("Error opening i/o streams");
    }
    logger.trace("i/o Streams prepared");

    // Add this object as an event listener for the serial port.
    try {
      m_SerialPort.addEventListener(this);
    } catch (TooManyListenersException e) {
      m_SerialPort.close();
      final String errMsg = "too many listeners added";
      logger.debug("{}: {}", errMsg, e.getMessage());
      throw new Exception(errMsg);
    }

    // Set notifyOnBreakInterrup to allow event driven break handling.
    m_SerialPort.notifyOnBreakInterrupt(true);

    m_Open = true;
  } // open
Example #13
0
  // open a serial connection to a device.  We won't know it's the robot until
  public int OpenPort(String portName) {
    if (portOpened && portName.equals(recentPort)) return 0;

    ClosePort();

    Log("<font color='green'>Connecting to " + portName + "...</font>\n");

    // find the port
    try {
      portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
    } catch (Exception e) {
      Log("<span style='color:red'>Ports could not be identified:" + e.getMessage() + "</span>\n");
      e.printStackTrace();
      return 1;
    }

    if (portIdentifier.isCurrentlyOwned()) {
      Log(
          "<span style='color:red'>Error: Another program is currently using this port."
              + "</span>\n");
      return 2;
    }

    // open the port
    try {
      commPort = portIdentifier.open("DrawbotGUI", 2000);
    } catch (Exception e) {
      Log("Port could not be opened:" + e.getMessage() + NL);
      e.printStackTrace();
      return 3;
    }

    if ((commPort instanceof SerialPort) == false) {
      Log("<span style='color:red'>Only serial ports are handled by this example." + "</span>\n");
      return 4;
    }

    // set the port parameters (like baud rate)
    serialPort = (SerialPort) commPort;
    try {
      serialPort.setSerialPortParams(
          BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    } catch (Exception e) {
      Log("<span style='color:red'>Port could not be configured:" + e.getMessage() + "</span>\n");
      return 5;
    }

    try {
      in = serialPort.getInputStream();
      out = serialPort.getOutputStream();
    } catch (Exception e) {
      Log("<span style='color:red'>Streams could not be opened:" + e.getMessage() + "</span>\n");
      return 6;
    }

    try {
      serialPort.addEventListener(this);
      serialPort.notifyOnDataAvailable(true);
    } catch (TooManyListenersException e) {
      Log("<span style='color:red'>Streams could not be opened:" + e.getMessage() + "</span>\n");
      return 7;
    }

    Log("<span style='green'>Opened.</span>\n");
    SetRecentPort(portName);
    portOpened = true;
    UpdateMenuBar();

    return 0;
  }