Salut dinobogan, j'ai essayé de faire comme tu as dis c'est-à-dire d'exporter ma méthode d'écriture/lecture sur le port série dans un thread à part.
Voici comment j'ai fais :
Méthode pour envoyer un caractère :
1 2 3 4 5 6 7 8
| public String communique_char(char envoie) {
ThreadEnvoi t1 = new ThreadEnvoi(envoie, outStream, bufRead);
t1.start();
t1.interrupt();
while (t1.rReceived() == "" || !t1.getTimeOut()) {
}
return t1.rReceived();
} |
Classe ThreadEnvoi :
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
| public class ThreadEnvoi extends Thread {
private String caractere;
private OutputStream outputStream;
private String received = "";
private BufferedReader bufRead;
private Boolean timeOut;
public ThreadEnvoi(char caractere, OutputStream outputStream,
BufferedReader bufRead) {
this.caractere = "" + caractere;
this.outputStream = outputStream;
this.bufRead = bufRead;
this.timeOut = false;
}
public ThreadEnvoi(String caractere, OutputStream outputStream,
BufferedReader bufRead) {
this.caractere = caractere;
this.outputStream = outputStream;
this.bufRead = bufRead;
this.timeOut = false;
}
public void run() {
TimeOut threadTimeOut = new TimeOut(this);
threadTimeOut.start();
try {
for (int i = 0; i < this.caractere.length(); i++) {
outputStream.write(this.caractere.charAt(i));
}
outputStream.write('\n');
received = bufRead.readLine().trim();
} catch (IOException e) {
e.printStackTrace();
}
this.interrupt();
}
public String rReceived() {
return received;
}
public void timeElapsed() {
this.timeOut = true;
}
public boolean getTimeOut() {
return this.timeOut;
}
} |
Classe TimeOut :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public class TimeOut extends Thread {
ThreadEnvoi envoi;
public TimeOut(ThreadEnvoi envoi) {
this.envoi = envoi;
}
public void run() {
try {
sleep(200); // wait of 200 ms
} catch (InterruptedException e) {
e.printStackTrace();
}
this.envoi.timeElapsed();
}
} |
Mon problème reste le même car si je ne choisis pas de port série et que j'essaie d'envoyer un caractère alors j'obtiens une erreur qui vient d'une ligne dans le code de ma classe ThreadEnvoi :
outputStream.write(this.caractere.charAt(i));
Et si je choisis un port alors là j'ai une erreur à cette ligne :
received = bufRead.readLine().trim();
Je sais bien que c'est normal que je récupère ces erreurs mais par contre mon interface plante aussi lors d'une de ces erreurs...
Je ne sais pas pourquoi car là j'ai bien différencier les 2 parties dans des Threads différents...
Auriez-vous une idée ?
Merci d'avance pour votre aide !!
Partager