1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
|
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.*;
import com.sun.comm.Win32Driver;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
public class rs232 implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static CommPortIdentifier saveportId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
static OutputStream outputStream;
static boolean outputBufferEmptyFlag = false;
public static void main(String[] args) {
boolean portFound = false;
String defaultPort;
Win32Driver w32Driver= new Win32Driver();
w32Driver.initialize();
//déterminer le nom du port série sur plusieurs systèmes d'exploitation
String osname = System.getProperty("os.name","").toLowerCase();
if ( osname.startsWith("windows") ) {
// windows
defaultPort = "COM1";
} else {
System.out.println("Sorry, your operating system is not supported");
return;
}
if (args.length > 0) {
defaultPort = args[0];
}
System.out.println("Set default port to "+defaultPort);
//ports analyser et si le port par défaut est trouvé, initialisé le lecteur
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals(defaultPort)) {
System.out.println("Found port: "+defaultPort);
portFound = true;
// init reader thread
rs232 reader = new rs232();
}
}
}
if (!portFound) {
System.out.println("port " + defaultPort + " not found.");
}
}
public void initwritetoport() {
//initwritetoport () suppose que le port a déjà été ouvert et
//initialisé par "nulltest publique ()"
try {
// obtenir le flux sortant
outputStream = serialPort.getOutputStream();
} catch (IOException e) {}
try {
// activer le notifiant OUTPUT_BUFFER_EMPTY
serialPort.notifyOnOutputEmpty(true);
} catch (Exception e) {
System.out.println("Error setting event notification");
System.out.println(e.toString());
System.exit(-1);
}
}
public void writetoport(String s) {
System.out.println("Writing \""+s+"\" to "+serialPort.getName());
try {
// Donnez votre chaîne sur le port série
outputStream.write(s.getBytes());
} catch (IOException e) {}
}
public rs232() {
// initalize port série
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
// activate the DATA_AVAILABLE notifier
serialPort.notifyOnDataAvailable(true);
try {
// définir les paramètres de port
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
// commencer à lire le fil
readThread = new Thread(this);
readThread.start();
}
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
// nous obtenons ici si les données ont été reçues
byte[] readBuffer = new byte[20];
try {
// données lues
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
}
// données d'impression
String result = new String(readBuffer).trim();
System.out.println("Read: "+result);
} catch (IOException e) {}
break;
}
}
public void run() {
// première chose que dans le fil, on initialise l'opération d'écriture
initwritetoport();
// écrit une chaîne dans le port, le serialEvent vais le lire
writetoport("d");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(rs232.class.getName()).log(Level.SEVERE, null, ex);
}
}
} |
Partager