Advertisement
Guest User

Untitled

a guest
Jul 24th, 2014
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. import javax.comm.*;
  4.  
  5. public class SimpleRead implements Runnable, SerialPortEventListener {
  6. static CommPortIdentifier portId;
  7. static Enumeration portList;
  8.  
  9. InputStream inputStream;
  10. SerialPort serialPort;
  11. Thread readThread;
  12.  
  13. public static void main(String[] args) {
  14. portList = CommPortIdentifier.getPortIdentifiers();
  15.  
  16. while (portList.hasMoreElements()) {
  17. portId = (CommPortIdentifier) portList.nextElement();
  18. if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
  19. if (portId.getName().equals("COM13")) {
  20. // if (portId.getName().equals("/dev/term/a")) {
  21. SimpleRead reader = new SimpleRead();
  22. }
  23. }
  24. }
  25. }
  26.  
  27. public SimpleRead() {
  28. try {
  29. serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
  30. } catch (PortInUseException e) {System.out.println(e);}
  31. try {
  32. inputStream = serialPort.getInputStream();
  33. } catch (IOException e) {System.out.println(e);}
  34. try {
  35. serialPort.addEventListener(this);
  36. } catch (TooManyListenersException e) {System.out.println(e);}
  37. serialPort.notifyOnDataAvailable(true);
  38. try {
  39. serialPort.setSerialPortParams(9600,
  40. SerialPort.DATABITS_8,
  41. SerialPort.STOPBITS_1,
  42. SerialPort.PARITY_NONE);
  43. } catch (UnsupportedCommOperationException e) {System.out.println(e);}
  44. readThread = new Thread(this);
  45. readThread.start();
  46. }
  47.  
  48. public void run() {
  49. try {
  50. Thread.sleep(20000);
  51. } catch (InterruptedException e) {System.out.println(e);}
  52. }
  53.  
  54. public void serialEvent(SerialPortEvent event) {
  55. switch(event.getEventType()) {
  56. case SerialPortEvent.BI:
  57. case SerialPortEvent.OE:
  58. case SerialPortEvent.FE:
  59. case SerialPortEvent.PE:
  60. case SerialPortEvent.CD:
  61. case SerialPortEvent.CTS:
  62. case SerialPortEvent.DSR:
  63. case SerialPortEvent.RI:
  64. case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
  65. break;
  66. case SerialPortEvent.DATA_AVAILABLE:
  67. byte[] readBuffer = new byte[20];
  68.  
  69. try {
  70. while (inputStream.available() > 0) {
  71. int numBytes = inputStream.read(readBuffer);
  72. }
  73. System.out.print(new String(readBuffer));
  74. } catch (IOException e) {System.out.println(e);}
  75. break;
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement