import java.io.IOException; import java.nio.ByteBuffer; import jdk.dio.DeviceManager; import jdk.dio.uart.UART; import jdk.dio.uart.UARTEvent; import jdk.dio.uart.UARTEventListener; /** * * @author stanislav.smirnov@oracle.com */ public class UARTListenerTest implements UARTEventListener { volatile boolean result = true; UART uart = null; volatile int targetEventID; volatile boolean targetEventCaptured = false; /** * Standard command-line entry point. * * @param args command line args (ignored) */ public static void main(String[] args) { UARTListenerTest t = new UARTListenerTest(); t.test(); } private void test() { result = true; this.targetEventID = UARTEvent.OUTPUT_BUFFER_EMPTY; targetEventCaptured = false; try { uart = (UART)DeviceManager.open(40); uart.setEventListener(targetEventID, this); ByteBuffer bb = ByteBuffer.wrap(new byte[8]); bb.position(bb.limit()); try { uart.write(bb); System.out.println("Have written an \"empty\" ByteBuffer"); try { Thread.sleep(1000 * 2); } catch (InterruptedException ex) { } } catch (IOException ex) { result = false; System.out.println("Unexpected IOException: " + ex.getClass().getName() + ":" + ex.getMessage()); } if (!targetEventCaptured) { result = false; System.out.println("Expected " + targetEventID + " was NOT captured"); } else { System.out.println("Expected " + targetEventID + " WAS captured"); } } catch (UnsupportedOperationException e) { try { uart.close(); } catch (IOException ex) { System.out.println("Unexpected IOException: " + ex.getClass().getName() + ":" + ex.getMessage()); result = false; } uart = null; } catch (IOException ex) { System.out.println("Unexpected IOException: " + ex.getClass().getName() + ":" + ex.getMessage()); result = false; } flush(); } @Override public void eventDispatched(UARTEvent uarte) { if(targetEventID == uarte.getID()) { targetEventCaptured = true; System.out.println("EventListener captured event " + targetEventID); } } public void flush() { if(uart != null) { try { uart.setEventListener(targetEventID, null); System.out.println("Successfully removed the event listener for " + targetEventID + " from the UART"); } catch(IOException ex) { result = false; System.out.println("Unexcpected " + ex.getClass().getName() + " was thrown when trying to remove the event listener for " + targetEventID + " from the UART"); } try { uart.close(); } catch(IOException ex) { System.out.println("Unexpected IOException: " + ex.getClass().getName() + ":" + ex.getMessage()); } uart = null; } } class MyThread extends Thread { @Override public void run() { while(!targetEventCaptured) { try { uart.read(ByteBuffer.wrap(new byte[8])); } catch(IOException ex) { System.out.println("Unexpected IOException: " + ex.getClass().getName() + ":" + ex.getMessage()); } } } } }