/** * This creates an mbed object for an mbed connected over Serial. <br> * Using this class requires the Sun Communications API to be installed * * @param PortName The Serial Port mbed is connected to eg "COM5" on Windows. * @param Baud The baud rate */ public SerialRPC(String PortName, int Baud) { // open serial port try { mbedPortID = CommPortIdentifier.getPortIdentifier(PortName); mbedPort = mbedPortID.open("mbed", 100000); mbedSerialPort = (SerialPort) mbedPort; mbedSerialPort.setSerialPortParams( Baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); inputStream = new DataInputStream(mbedPort.getInputStream()); outputStream = new PrintStream(mbedPort.getOutputStream(), true); reader = new BufferedReader(new InputStreamReader(inputStream)); to_mbed = new PrintWriter(outputStream, true); mbedSerialPort.addEventListener(this); // Important to set this regardless of whether interrupts are in use to keep the buffer clear mbedSerialPort.notifyOnDataAvailable(true); } catch (TooManyListenersException e) { // Error adding event listener System.out.println("Too many Event Listeners"); } catch (NoSuchPortException e) { System.out.println("No Such Port"); } catch (PortInUseException e) { System.out.println("Port Already In Use"); } catch (UnsupportedCommOperationException e) { System.out.println("Unsupported Comm Operation"); } catch (IOException e) { System.out.println("Serial Port IOException"); } }
/** Opens the Serial port with the baud and port_name given */ public boolean OpenSerial(int baud, String port) { CommPortIdentifier portId = null; Enumeration portEnum = CommPortIdentifier.getPortIdentifiers(); while (portEnum.hasMoreElements()) { CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement(); if (currPortId.getName().equals(port)) { portId = currPortId; break; } } if (portId == null) { System.err.println("Can not open serial port"); return false; } try { serialPort = (SerialPort) portId.open(this.getClass().getName(), 2000); serialPort.setSerialPortParams( baud, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); input = serialPort.getInputStream(); output = serialPort.getOutputStream(); serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); Thread.sleep(1500); } catch (Exception e) { return false; } return true; }
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(); } }
// 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"); } }
/** * 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
// 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; }