Almost got Bluetooth syncing working, still have crash att app exit

This commit is contained in:
Ziver Koc 2015-01-30 17:16:31 +01:00
parent bb24b03557
commit 84b679a7cc
7 changed files with 92 additions and 51 deletions

View file

@ -92,6 +92,7 @@ public class UeControlExecutor implements Runnable{
}
public void terminateNonBlock(){
log.info("Terminating executor...");
terminate = true;
handler.removeCallbacks(throughputUpdateRunnable);
if(currentlyActive != null)
@ -113,6 +114,7 @@ public class UeControlExecutor implements Runnable{
}
public synchronized void reset(){
log.info("Resetting executor and all behaviours...");
currentlyActive = null;
for(int i=0; i<behaviours.size(); i++){
behaviours.get(i).reset();
@ -126,7 +128,7 @@ public class UeControlExecutor implements Runnable{
}
public void run(){
log.info("Starting execution");
log.info("Starting execution...");
if(execListener != null)
execListener.executionStarted();
if(csvPath != null)
@ -168,7 +170,7 @@ public class UeControlExecutor implements Runnable{
csvLogger = null;
}
}
log.info("Execution completed");
log.info("Execution completed.");
if(execListener != null)
execListener.executionStopped();
synchronized (thread){thread.notifyAll();}

View file

@ -18,7 +18,6 @@ public class UeBehaviourStop extends UeBehaviour {
Thread.sleep(VISUAL_SLEEP_PERIOD); // Sleep as a visual queue
if(!super.stopExecution()) {
log.debug("Terminating executor");
executor.terminateNonBlock();
executor.setNextBehaviour(0);
}

View file

@ -7,6 +7,7 @@ import com.ericsson.uecontrol.core.util.BluetoothServer;
import com.ericsson.uecontrol.core.util.BluetoothUtil;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.List;
/**
@ -14,80 +15,97 @@ import java.util.List;
*/
public class UeBehaviourSynchronize extends UeBehaviour implements BluetoothClient.MessageHandler{
private static final Logger log = Logger.getLogger(UeBehaviourSynchronize.class);
private static final int SLEEP_PERIOD = 100;
private final String SERVICE_UUID = "5ef27dac-a003-11e4-89d3-123b93f75cba";
private static final int SYNC_TIMEOUT = 100; // milliseconds
private static final int SLEEP_PERIOD = 20;
private static final int BROADCAST_PERIOD = 100;
private static final int SYNC_TIMEOUT = 20; // milliseconds
private static final String SYNC_REQ_MSG = "SYNC REQ";
private static final String SYNC_ACK_MSG = "SYNC ACK";
private static BluetoothServer server;
private static BluetoothClient client;
private long syncTimeoutStamp;
private long syncTimestamp;
@Override
protected void execute() throws Exception {
if(server == null && client == null) {
if(client == null && server == null){
log.debug("Searching paired devices...");
super.setProgress(0.2f);
List<BluetoothDevice> devices = BluetoothUtil.filterWithService(BluetoothUtil.getPairedDevices(), SERVICE_UUID);
if (!devices.isEmpty()) {
log.debug("Found paired device("+devices.get(0).getAddress()+"), connecting...");
log.debug("Found paired device(" + devices.get(0).getAddress() + "), connecting...");
client = new BluetoothClient(devices.get(0), SERVICE_UUID, this);
client.start();
}
else {
log.debug("No paired devices found, starting discovery...");
super.setProgress(0.4f);
/*log.debug("No paired devices found, starting discovery...");
super.setProgress(0.3f);
devices = BluetoothUtil.filterWithService(BluetoothUtil.discover(), SERVICE_UUID);
if (!devices.isEmpty()) {
log.debug("Found device("+devices.get(0).getAddress()+"), connecting...");
client = new BluetoothClient(devices.get(0), SERVICE_UUID, this);
client.start();
}
else{
log.debug("No discoverable devices, setting up server...");
super.setProgress(0.6f);
server = new BluetoothServer("uecontrol_sync", SERVICE_UUID, this);
server.start();
}
}
}
// Wait for sync message
else{*/
log.debug("No discoverable devices found. Starting up server...");
super.setProgress(0.7f);
while(!super.stopExecution()){
if(super.stopExecution()) break;
Thread.sleep(SLEEP_PERIOD);
server = new BluetoothServer("uecontrol", SERVICE_UUID, this);
server.start();
//BluetoothUtil.setDiscoverable();
//}
}
}
if(client != null){ // CLIENT
if(syncTimeoutStamp > System.currentTimeMillis()){
client.sendMessage(SYNC_ACK_MSG);
log.debug("Sending SYNC ACK, syncing done");
terminate();
}
log.debug("Running in client mode.");
super.setProgress(0.3f);
}
else if(server != null){ // SERVER
server.sendMessage(SYNC_REQ_MSG);
log.debug("Running in server mode.");
super.setProgress(0.7f);
}
try {
// Wait for sync message
while (!super.stopExecution()) {
Thread.sleep(SLEEP_PERIOD);
long syncDiff = System.currentTimeMillis() - syncTimestamp;
if (client != null) { // CLIENT
if (syncDiff < SYNC_TIMEOUT) {
client.sendMessage(SYNC_ACK_MSG);
log.debug("Sending SYNC ACK, syncing done (time diff: "+syncDiff+"ms)");
terminate();
}
} else if (server != null && syncDiff > BROADCAST_PERIOD) { // SERVER
server.sendMessage(SYNC_REQ_MSG);
syncTimestamp = System.currentTimeMillis();
}
}
} catch(IOException e){
log.error("Unable to connect to remote device, resetting connections...");
close();
throw e;
}
}
@Override
public void messageReceived(String msg) {
if(SYNC_REQ_MSG.equals(msg)){ // CLIENT
syncTimeoutStamp = System.currentTimeMillis() + SYNC_TIMEOUT;
syncTimestamp = System.currentTimeMillis();
log.debug("Received SYNC REQ");
}
else if(SYNC_ACK_MSG.equals(msg)){ // SERVER
log.debug("Received SYNC ACK, syncing done");
long syncDiff = System.currentTimeMillis() - syncTimestamp;
log.debug("Received SYNC ACK, syncing done (round trip time: "+syncDiff+"ms)");
terminate();
}
}
@Override
public void reset(){
public void close(){
if(client != null){
client.close();
client = null;
@ -96,16 +114,21 @@ public class UeBehaviourSynchronize extends UeBehaviour implements BluetoothClie
server.close();
server = null;
}
}
@Override
public void reset(){
close();
super.reset();
}
@Override
public String getName() {
return "Synchronize";
return "Synchronize (Beta)";
}
@Override
public String toString() {
return "Will synchronize with another remote device";
return "Will synchronize with a Paired Bluetooth device";
}
}

View file

@ -22,9 +22,19 @@ public class BluetoothClient extends Thread {
// Get a BluetoothSocket to connect with the given BluetoothDevice
socket = device.createRfcommSocketToServiceRecord(UUID.fromString(service_uuid));
// Fallback
//socket = (BluetoothSocket)device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
try {
socket.connect();
} catch (IOException e){
// Reset UUID cache for device, as it might be out of date
log.error("Unable to connect to device(" + device.getAddress() + "), resetting UUID cache for the device.");
device.fetchUuidsWithSdp();
throw e;
}
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
@ -48,24 +58,26 @@ public class BluetoothClient extends Thread {
}
}
try {
if (socket != null)
socket.close();
} catch (IOException e) {
log.trace(null, e);
}
close();
}
public void sendMessage(String msg) throws IOException {
if(socket != null)
out.write(msg);
if(socket != null) {
out.write(msg + "\n");
out.flush();
}
}
/**
* Will terminate an in-progress connection, and close the socket
*/
public void close() {
if(socket == null)
return;
try {
log.debug("Closing connection.");
socket.close();
socket = null;
} catch (IOException e) {

View file

@ -26,7 +26,6 @@ public class BluetoothServer extends Thread {
// MY_UUID is the app's UUID string, also used by the client code
BluetoothAdapter adapter = BluetoothUtil.getAdapter();
serverSocket = adapter.listenUsingRfcommWithServiceRecord(service, UUID.fromString(service_uuid));
//BluetoothUtil.setDiscoverable();
}
public void run() {
@ -68,6 +67,8 @@ public class BluetoothServer extends Thread {
* Will cancel the listening socket, and cause the thread to finish
*/
public void close() {
if(serverSocket == null)
return;
try {
serverSocket.close();
serverSocket = null;

View file

@ -116,7 +116,7 @@ public class BluetoothUtil {
public static void setDiscoverable() {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 60);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
MainActivity.getContext().startActivity(discoverableIntent);
}
}

View file

@ -287,11 +287,7 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
@Override
public void onBackPressed() {
if (backButtonPressed) {
if(executor != null){
log.info("Terminating executor");
executor.terminate();
executor.reset();
}
// Close the App
super.onBackPressed();
return;
}
@ -306,7 +302,15 @@ public class MainActivity extends FragmentActivity implements OnSharedPreference
}
}, 2000);
}
@Override
protected void onDestroy() {
if(executor != null){
executor.terminate();
executor.reset();
executor = null;
}
super.onDestroy();
}
public static UeControlExecutor getExecutor() {
return executor;