protected void flushSerialBuffer() throws RunnerException, SerialException { // Cleanup the serial buffer try { Serial serialPort = new Serial(); byte[] readBuffer; while (serialPort.available() > 0) { readBuffer = serialPort.readBytes(); try { Thread.sleep(100); } catch (InterruptedException e) { } } serialPort.setDTR(false); serialPort.setRTS(false); try { Thread.sleep(100); } catch (InterruptedException e) { } serialPort.setDTR(true); serialPort.setRTS(true); serialPort.dispose(); } catch (SerialNotFoundException e) { throw e; } catch (Exception e) { e.printStackTrace(); throw new RunnerException(e.getMessage()); } }
public TestSer(String port) { try { portId = CommPortIdentifier.getPortIdentifier(port); serialPort = (SerialPort) portId.open("TestSer", 2000); is = serialPort.getInputStream(); os = serialPort.getOutputStream(); /* serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); */ serialPort.setSerialPortParams( 115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); serialPort.setFlowControlMode( SerialPort.FLOWCONTROL_RTSCTS_OUT | SerialPort.FLOWCONTROL_RTSCTS_IN); serialPort.enableReceiveTimeout(TIMEOUT); // serialPort.enableReceiveThreshold(4); } catch (Exception e) { System.out.println(e.getMessage()); System.exit(-1); } }
/** * Main method. Checks to see if the command line agrument is requesting usage informaition (-h, * -help), if it is, display a usage message and exit, otherwise create a new <code>SerialDemo * </code> and set it visible. */ public static void main(String[] args) { try { serialDemo = new SerialManager(); ETerminalDataDto objETerminalDataDto = serialDemo.getDebitCmd( "DC7934737E93BE4F", "DC7934737E93BE4F", "FFFFFE", "0203000A820013881000130007177762B20D5307D50E3F3B24D01C4001FD1EFF75004E202556FBDA1E2088881C00A0FFFFFF2570016643544E3536323120550001000400005555000000000000000000000000000000000000000000000000AB273C2F13AFC9FB03F79059E20C3EC73BF7"); // Commet this after testing with main method; // serialDemo.initConfig(); // serialDemo.connection.sendMessage(ISOUtil.hex2byte("020079600037000002007024058000C10004164999770007848180000000000000011111011000100309020037003237303031393630313638313638313035323934202020000334343400063031313030320388")); /* byte [] debitCommand = serialDemo.connection.sendMessage(ISOUtil.hex2byte(HeaderUtil.getReqHeader("DC7934737E93BE4F","DC7934737E93BE4F","FFFFFE","0203000A820013881000130007177762B20D5307D50E3F3B24D01C4001FD1EFF75004E202556FBDA1E2088881C00A0FFFFFF2570016643544E3536323120550001000400005555000000000000000000000000000000000000000000000000AB273C2F13AFC9FB03F79059E20C3EC73BF7"))); System.out.println("Debit Command="+ ISOUtil.hexString(debitCommand)); String strResSplit[] = ISOUtil.hexString(debitCommand).split("1C"); for(int i=0;i<strResSplit.length;i++) { strResSplit[i] = strResSplit[i].substring(8); System.out.println(strResSplit[i]); }*/ System.out.println("strDebitCmd " + objETerminalDataDto.getDebitCmd()); } catch (Exception sExp) { System.out.println(sExp.getMessage()); } }
/** Set the parameters object to the settings in the properties object. */ private void loadParams() throws SerialConnectionException { try { PropertyResourceBundle props = (PropertyResourceBundle) PropertyResourceBundle.getBundle(CONFIG_BUNDLE_NAME); System.out.println("BaudRate=" + props.getString("baudRate")); ezlink.info("BaudRate= : " + props.getString("baudRate")); parameters.setBaudRate(props.getString("baudRate")); parameters.setFlowControlIn(props.getString("flowControlIn")); parameters.setFlowControlOut(props.getString("flowControlOut")); parameters.setParity(props.getString("parity")); parameters.setDatabits(props.getString("databits")); parameters.setStopbits(props.getString("stopbits")); parameters.setPIN(props.getString("pin")); parameters.setSMC(props.getString("smc")); parameters.setDriver(props.getString("driver")); parameters.setURL(props.getString("url")); parameters.setUserName(props.getString("username")); parameters.setPassword(props.getString("password")); parameters.setPortName(props.getString("portName")); } catch (Exception exp) { ezlink.info("+++Error While setting parameters : +++"); ezlink.error(new Object(), exp); throw new SerialConnectionException("Error While setting parameters=" + exp.getMessage()); } }
// connect to the selected port in the combo box // pre: ports are already found by using the searchForPorts method // post: the connected comm port is stored in commPort, otherwise, // an exception is generated public void connect() { // String selectedPort = (String)window.cboxPorts.getSelectedItem(); /** Setting 에서 Comport 불러오는 걸로 수정 * */ // String selectedPort = "COM4"; selectedPortIdentifier = (CommPortIdentifier) portMap.get(selectedPort); CommPort commPort = null; try { // the method below returns an object of type CommPort commPort = selectedPortIdentifier.open("TigerControlPanel", TIMEOUT); // the CommPort object can be casted to a SerialPort object serialPort = (SerialPort) commPort; // for controlling GUI elements setConnected(true); // logging logText = selectedPort + " opened successfully."; System.out.println(logText + "\n"); // CODE ON SETTING BAUD RATE ETC OMITTED // XBEE PAIR ASSUMED TO HAVE SAME SETTINGS ALREADY } catch (PortInUseException e) { logText = selectedPort + " is in use. (" + e.toString() + ")"; System.out.println(logText + "\n"); } catch (Exception e) { logText = "Failed to open " + selectedPort + "(" + e.toString() + ")"; System.out.println(logText + "\n"); } }
public static Serial open(String defaultPort) { boolean portFound = false; final int mComPortIdentifier = CommPortIdentifier.PORT_SERIAL; final Enumeration portList = CommPortIdentifier.getPortIdentifiers(); final int BAUD = 115200; while (portList.hasMoreElements()) { final CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement(); System.out.println("Found port id: " + portId); if (portId.getPortType() == mComPortIdentifier) { System.out.println("Found CommPortIdentifier."); if (portId.getName().equals(defaultPort)) { System.out.println("Found port " + defaultPort); SerialPort serialPort; OutputStream outputStream = null; try { serialPort = (SerialPort) portId.open("SimpleWrite", 2000); } catch (PortInUseException e) { System.out.println("Port in use."); continue; } try { outputStream = serialPort.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } try { serialPort.setSerialPortParams( BAUD, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) { e.printStackTrace(); } try { serialPort.notifyOnOutputEmpty(true); } catch (Exception e) { System.out.println("Error setting event notification"); System.out.println(e.toString()); System.exit(-1); } return new Serial(serialPort, outputStream); } } } if (!portFound) { System.out.println("port " + defaultPort + " not found."); } return null; }
public static void main(String[] args) { try { Schrittmotor motor = new Schrittmotor("COM1"); motor.oeffneSerialPort(); motor.schliesseSerialPort(); } catch (Exception ex) { System.out.println(ex.getMessage()); } }
// method that can be called to send data // pre: open serial port // post: data sent to the other device public void writeData(int code) { try { output.write(code); output.flush(); System.out.println("code : " + code); } catch (Exception e) { logText = "Failed to write data. (" + e.toString() + ")"; System.out.println(logText); } }
// what happens when data is received // pre: serial event is triggered // post: processing on the data it reads public void serialEvent(SerialPortEvent evt) { if (evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) { try { int readData = input.read(); System.out.println(readData + "@@@\n"); if (readData == 51) // 소변통 (Water Sensor) { Action.SendUrineMessage(); } } catch (Exception e) { logText = "Failed to read data. (" + e.toString() + ")"; System.out.println(logText + "\n"); } } }
// disconnect the serial port // pre: an open serial port // post: clsoed serial port public void disconnect() { // close the serial port try { // writeData(0, 0); serialPort.removeEventListener(); serialPort.close(); input.close(); output.close(); setConnected(false); logText = "Disconnected."; System.out.println(logText + "\n"); } catch (Exception e) { logText = "Failed to close " + serialPort.getName() + "(" + e.toString() + ")"; System.out.println(logText + "\n"); } }
/** * @return A HashSet containing the CommPortIdentifier for all serial ports that are not currently * being used. */ @SuppressWarnings({"rawtypes"}) private static HashSet<CommPortIdentifier> getAvailableSerialPorts() { HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>(); Enumeration thePorts = CommPortIdentifier.getPortIdentifiers(); while (thePorts.hasMoreElements()) { CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement(); switch (com.getPortType()) { case CommPortIdentifier.PORT_SERIAL: try { CommPort thePort = com.open("CommUtil", 50); thePort.close(); h.add(com); } catch (PortInUseException e) { System.out.println("Port, " + com.getName() + ", is in use."); } catch (Exception e) { System.err.println("Failed to open port " + com.getName()); e.printStackTrace(); } } } return h; }
/** Send data to Serial Port (e.g FTDI module) */ public void send(Data aData) throws IOException, BCDPrecisionException { try { /* Get frequency as BCD */ Long frequencyBCD = aData.getDataAsBCD(); /* Log */ System.out.println( "Sending: " + frequencyBCD + ". It is 0x" + Long.toHexString(frequencyBCD) + " in BCD."); /* Send frequency */ outputStream.write(Data.intToByteArray(frequencyBCD)); } catch (BCDPrecisionException e) { System.err.println( "Impossible to send: " + e.getValue() + " using current precision. Try to send: " + e.getPossibleValue()); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
protected boolean executeUploadCommand(Collection commandDownloader) throws RunnerException { firstErrorFound = false; // haven't found any errors yet secondErrorFound = false; notFoundError = false; int result = 0; // pre-initialized to quiet a bogus warning from jikes String userdir = System.getProperty("user.dir") + File.separator; try { String[] commandArray = new String[commandDownloader.size()]; commandDownloader.toArray(commandArray); String avrBasePath; if (Base.isLinux()) { avrBasePath = new String(Base.getHardwarePath() + "/tools/"); } else { avrBasePath = new String(Base.getHardwarePath() + "/tools/avr/bin/"); } commandArray[0] = avrBasePath + commandArray[0]; if (verbose || Preferences.getBoolean("upload.verbose")) { for (int i = 0; i < commandArray.length; i++) { System.out.print(commandArray[i] + " "); } System.out.println(); } Process process = Runtime.getRuntime().exec(commandArray); new MessageSiphon(process.getInputStream(), this); new MessageSiphon(process.getErrorStream(), this); // wait for the process to finish. if interrupted // before waitFor returns, continue waiting // boolean compiling = true; while (compiling) { try { result = process.waitFor(); compiling = false; } catch (InterruptedException intExc) { } } if (exception != null) { exception.hideStackTrace(); throw exception; } if (result != 0) return false; } catch (Exception e) { String msg = e.getMessage(); if ((msg != null) && (msg.indexOf("uisp: not found") != -1) && (msg.indexOf("avrdude: not found") != -1)) { // System.err.println("uisp is missing"); // JOptionPane.showMessageDialog(editor.base, // "Could not find the compiler.\n" + // "uisp is missing from your PATH,\n" + // "see readme.txt for help.", // "Compiler error", // JOptionPane.ERROR_MESSAGE); return false; } else { e.printStackTrace(); result = -1; } } // System.out.println("result2 is "+result); // if the result isn't a known, expected value it means that something // is fairly wrong, one possibility is that jikes has crashed. // if (exception != null) throw exception; if ((result != 0) && (result != 1)) { exception = new RunnerException(SUPER_BADNESS); // editor.error(exception); // PdeBase.openURL(BUGS_URL); // throw new PdeException(SUPER_BADNESS); } return (result == 0); // ? true : false; }
/** * 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; }
// --------------------------getDecryptedRecieptData------------------------------------------------------------- // public String getDebitCmd(String stCardRndNo, String stTerRndNo, String stAmt, String stPurse) // throws Exception { public String getDecryptedRecieptData(ETerminalDataDto objETerminalDataDto) throws Exception { // ETerminalDataDto objETerminalDataDto=new ETerminalDataDto(); String strDecryptedRecieptDataRefNo = ""; String strDecryptedRecieptData = ""; String strResHeader = ""; // String strDebitCmd=null; try { ezlink.info( "\n-------SerialManager--------------START----4 decrypting RecieptData-------------------"); ezlink.info("getDecryptedRecieptData Request received in " + SerialManager.class.getName()); // Commet this after testing with main method; // serialDemo.initConfig() // serialDemo.connection.sendMessage(ISOUtil.hex2byte("020079600037000002007024058000C10004164999770007848180000000000000011111011000100309020037003237303031393630313638313638313035323934202020000334343400063031313030320388")); // Debit command byte[] decRecieptData = null; try { decRecieptData = connection.sendMessage( ISOUtil.hex2byte( HeaderUtil.getReqRecieptData( objETerminalDataDto.getRecieptData(), objETerminalDataDto.getTerminalSessionKey(), objETerminalDataDto.getDebitSessionKey(), objETerminalDataDto.getCan(), objETerminalDataDto.getEzLinkString(), ""))); } catch (Exception e) { e.printStackTrace(); } System.out.println("Decrypted Reciept Data=" + ISOUtil.hexString(decRecieptData)); ezlink.info("Decrypted Reciept Data= : " + ISOUtil.hexString(decRecieptData)); String strResponse = ISOUtil.hexString(decRecieptData); ezlink.info("+++Decrypted Reciept Data strResponse Length : " + strResponse.length()); ezlink.info("+++Decrypted Reciept Data strResponse : " + strResponse); // if (strResponse.length() == 222) { // ezlink.info("+++Inside IF : // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" ); strResHeader = strResponse.substring(0, 34); strDecryptedRecieptDataRefNo = strResponse.substring(44, 68); // 24 strDecryptedRecieptData = strResponse.substring(78, strResponse.length() - 2); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println("Last two digits: " + strResponse.substring(strResponse.length() - 2)); System.out.println("Response length : " + strResponse.length()); System.out.println("Response from terminal DC : " + strResponse); System.out.println("Decrypted Ezlink String : " + strDecryptedRecieptData); System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); ezlink.info( "\n--------SERIAL MANAGER-------RESPONSE----4DecryptedRecieptData----------------"); ezlink.info("strResHeader : " + strResHeader); ezlink.info("strDecryptedRecieptDataRefNo : " + strDecryptedRecieptDataRefNo); ezlink.info("strDecryptedRecieptData : " + strDecryptedRecieptData); ezlink.info("\n--------SERIAL MANAGER-------RESPONSE--------------------"); // strDebitCmd = "250315021403" + stTerRndNo + strActDebitCmd + strUserData; // System.out.println("strDebitCmd= " + strDebitCmd + " Len " + strDebitCmd.length()); // ezlink.info("strDebitCmd= " + strDebitCmd + " Len : " + strDebitCmd.length()); /* } else { //ezlink.info("+++Inside IF : ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" ); System.out.println("Response from the Terminal not received fully..."); ezlink.info("Response from the Terminal not received fully...!!!!!!!"); } */ } catch (Exception exp) { System.out.println(exp); ezlink.error(new Object(), exp); throw exp; } return strDecryptedRecieptData; }