Something went wrong on our end
-
Puissegur Alexis authoredPuissegur Alexis authored
BluetoothThread.java 2.33 KiB
package Bluetooth;
import Interfaces.Observable;
import Interfaces.Observer;
import Vue.FXMLVueController;
import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.misc.IOUtils;
public class BluetoothThread extends Thread implements Observable {
private static final int PACKET_SIZE = 18;
private BluetoothConnection connection;
private boolean keepGoing = true;
private String buffer;
private Observer observer;
public BluetoothThread(BluetoothConnection connection, Observer observer) {
this.connection = connection;
this.observer = observer;
}
public void notifyObserver(){
this.observer.update(this);
}
public String getBuffer(){
return this.buffer;
}
@Override
public void run() {
while (keepGoing) {
byte b;
try {
// Each packet must start with two SYNC bytes in a row
byte[] payload = new byte[PACKET_SIZE];
int nbRead = connection.getInputStream().read(payload);
System.out.println("payload : " + payload);
System.out.println("nbRead : " + nbRead);
this.buffer = new String(payload, StandardCharsets.UTF_8);
notifyObserver();
} catch (Exception e) {
System.out.println("Could not read stream + " + e);
}
}
// If we reach this point the thread is shutting down, so try to disconnect from the headset
}
public void stopThread() {
try {
keepGoing = false;
finalize();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
if(null != connection) {
if(null != connection.getInputStream()) {
connection.getInputStream().close();
}
if(null != connection.getOutputStream()) {
try {
connection.getOutputStream().flush();
} catch(Exception e) { e.printStackTrace(); }
connection.getOutputStream().close();
}
}
}
public void sendInstruction(String instruction)throws IOException {
connection.getOutputStream().write(instruction.getBytes());
}
}