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
| import javax.comm.*;
import com.sun.comm.Win32Driver;
import java.io.*;
public class PortCom {
private BufferedReader bufRead; //flux de lecture du port
private OutputStream outStream; //flux d'écriture du port
private CommPortIdentifier portId; //identifiant du port
private SerialPort sPort; //le port série
String port = null;
public PortCom(String com){
//initialisation du driver
Win32Driver w32Driver = new Win32Driver();
w32Driver.initialize();
//récupération de l'identifiant du port
try {
portId = CommPortIdentifier.getPortIdentifier(port);
} catch (NoSuchPortException e) {
}
//ouverture du port
try {
sPort = (SerialPort) portId.open("PortCom", 30000);
} catch (PortInUseException e) {}
//règle les paramètres de la connexion
try {
sPort.setSerialPortParams(
9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
//récupération du flux de lecture et écriture du port
try {
outStream = sPort.getOutputStream();
bufRead =
new BufferedReader(
new InputStreamReader(sPort.getInputStream()));
} catch (IOException e) {}
}
/**
* Méthode de communication.
*/
public String communique(char envoie) {
String temp = null;
try {
outStream.write((int) envoie);
temp = bufRead.readLine().trim();
} catch (IOException e) {}
return temp;
}
/**
* Méthode de fermeture des flux et port.
*/
public void close(){
try {
bufRead.close();
outStream.close();
} catch (IOException e) {
}
sPort.close();
}
} |