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(){ public void terminateNonBlock(){
log.info("Terminating executor...");
terminate = true; terminate = true;
handler.removeCallbacks(throughputUpdateRunnable); handler.removeCallbacks(throughputUpdateRunnable);
if(currentlyActive != null) if(currentlyActive != null)
@ -113,6 +114,7 @@ public class UeControlExecutor implements Runnable{
} }
public synchronized void reset(){ public synchronized void reset(){
log.info("Resetting executor and all behaviours...");
currentlyActive = null; currentlyActive = null;
for(int i=0; i<behaviours.size(); i++){ for(int i=0; i<behaviours.size(); i++){
behaviours.get(i).reset(); behaviours.get(i).reset();
@ -126,7 +128,7 @@ public class UeControlExecutor implements Runnable{
} }
public void run(){ public void run(){
log.info("Starting execution"); log.info("Starting execution...");
if(execListener != null) if(execListener != null)
execListener.executionStarted(); execListener.executionStarted();
if(csvPath != null) if(csvPath != null)
@ -168,7 +170,7 @@ public class UeControlExecutor implements Runnable{
csvLogger = null; csvLogger = null;
} }
} }
log.info("Execution completed"); log.info("Execution completed.");
if(execListener != null) if(execListener != null)
execListener.executionStopped(); execListener.executionStopped();
synchronized (thread){thread.notifyAll();} 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 Thread.sleep(VISUAL_SLEEP_PERIOD); // Sleep as a visual queue
if(!super.stopExecution()) { if(!super.stopExecution()) {
log.debug("Terminating executor");
executor.terminateNonBlock(); executor.terminateNonBlock();
executor.setNextBehaviour(0); executor.setNextBehaviour(0);
} }

View file

@ -7,6 +7,7 @@ import com.ericsson.uecontrol.core.util.BluetoothServer;
import com.ericsson.uecontrol.core.util.BluetoothUtil; import com.ericsson.uecontrol.core.util.BluetoothUtil;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.IOException;
import java.util.List; import java.util.List;
/** /**
@ -14,80 +15,97 @@ import java.util.List;
*/ */
public class UeBehaviourSynchronize extends UeBehaviour implements BluetoothClient.MessageHandler{ public class UeBehaviourSynchronize extends UeBehaviour implements BluetoothClient.MessageHandler{
private static final Logger log = Logger.getLogger(UeBehaviourSynchronize.class); 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 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_REQ_MSG = "SYNC REQ";
private static final String SYNC_ACK_MSG = "SYNC ACK"; private static final String SYNC_ACK_MSG = "SYNC ACK";
private static BluetoothServer server; private static BluetoothServer server;
private static BluetoothClient client; private static BluetoothClient client;
private long syncTimeoutStamp; private long syncTimestamp;
@Override @Override
protected void execute() throws Exception { protected void execute() throws Exception {
if(server == null && client == null) { if(client == null && server == null){
log.debug("Searching paired devices..."); log.debug("Searching paired devices...");
super.setProgress(0.2f); super.setProgress(0.2f);
List<BluetoothDevice> devices = BluetoothUtil.filterWithService(BluetoothUtil.getPairedDevices(), SERVICE_UUID); List<BluetoothDevice> devices = BluetoothUtil.filterWithService(BluetoothUtil.getPairedDevices(), SERVICE_UUID);
if (!devices.isEmpty()) { 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 = new BluetoothClient(devices.get(0), SERVICE_UUID, this);
client.start(); client.start();
} }
else { else {
log.debug("No paired devices found, starting discovery..."); /*log.debug("No paired devices found, starting discovery...");
super.setProgress(0.4f); super.setProgress(0.3f);
devices = BluetoothUtil.filterWithService(BluetoothUtil.discover(), SERVICE_UUID); devices = BluetoothUtil.filterWithService(BluetoothUtil.discover(), SERVICE_UUID);
if (!devices.isEmpty()) { if (!devices.isEmpty()) {
log.debug("Found device("+devices.get(0).getAddress()+"), connecting..."); log.debug("Found device("+devices.get(0).getAddress()+"), connecting...");
client = new BluetoothClient(devices.get(0), SERVICE_UUID, this); client = new BluetoothClient(devices.get(0), SERVICE_UUID, this);
client.start(); client.start();
} }
else{ else{*/
log.debug("No discoverable devices, setting up server..."); log.debug("No discoverable devices found. Starting up server...");
super.setProgress(0.6f); super.setProgress(0.7f);
server = new BluetoothServer("uecontrol_sync", SERVICE_UUID, this); server = new BluetoothServer("uecontrol", SERVICE_UUID, this);
server.start(); server.start();
}
//BluetoothUtil.setDiscoverable();
//}
} }
} }
// Wait for sync message if(client != null){ // CLIENT
super.setProgress(0.7f); log.debug("Running in client mode.");
while(!super.stopExecution()){ super.setProgress(0.3f);
if(super.stopExecution()) break; }
Thread.sleep(SLEEP_PERIOD); else if(server != null){ // SERVER
log.debug("Running in server mode.");
super.setProgress(0.7f);
}
if(client != null){ // CLIENT try {
if(syncTimeoutStamp > System.currentTimeMillis()){ // Wait for sync message
client.sendMessage(SYNC_ACK_MSG); while (!super.stopExecution()) {
log.debug("Sending SYNC ACK, syncing done"); Thread.sleep(SLEEP_PERIOD);
terminate();
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();
} }
} }
else if(server != null){ // SERVER } catch(IOException e){
server.sendMessage(SYNC_REQ_MSG); log.error("Unable to connect to remote device, resetting connections...");
} close();
throw e;
} }
} }
@Override @Override
public void messageReceived(String msg) { public void messageReceived(String msg) {
if(SYNC_REQ_MSG.equals(msg)){ // CLIENT if(SYNC_REQ_MSG.equals(msg)){ // CLIENT
syncTimeoutStamp = System.currentTimeMillis() + SYNC_TIMEOUT; syncTimestamp = System.currentTimeMillis();
log.debug("Received SYNC REQ"); log.debug("Received SYNC REQ");
} }
else if(SYNC_ACK_MSG.equals(msg)){ // SERVER 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(); terminate();
} }
} }
@Override public void close(){
public void reset(){
if(client != null){ if(client != null){
client.close(); client.close();
client = null; client = null;
@ -96,16 +114,21 @@ public class UeBehaviourSynchronize extends UeBehaviour implements BluetoothClie
server.close(); server.close();
server = null; server = null;
} }
}
@Override
public void reset(){
close();
super.reset(); super.reset();
} }
@Override @Override
public String getName() { public String getName() {
return "Synchronize"; return "Synchronize (Beta)";
} }
@Override @Override
public String toString() { 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 // Get a BluetoothSocket to connect with the given BluetoothDevice
socket = device.createRfcommSocketToServiceRecord(UUID.fromString(service_uuid)); 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 // Connect the device through the socket. This will block
// until it succeeds or throws an exception // until it succeeds or throws an exception
socket.connect(); 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.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
@ -48,24 +58,26 @@ public class BluetoothClient extends Thread {
} }
} }
try { if (socket != null)
if (socket != null) close();
socket.close();
} catch (IOException e) {
log.trace(null, e);
}
} }
public void sendMessage(String msg) throws IOException { public void sendMessage(String msg) throws IOException {
if(socket != null) if(socket != null) {
out.write(msg); out.write(msg + "\n");
out.flush();
}
} }
/** /**
* Will terminate an in-progress connection, and close the socket * Will terminate an in-progress connection, and close the socket
*/ */
public void close() { public void close() {
if(socket == null)
return;
try { try {
log.debug("Closing connection.");
socket.close(); socket.close();
socket = null; socket = null;
} catch (IOException e) { } 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 // MY_UUID is the app's UUID string, also used by the client code
BluetoothAdapter adapter = BluetoothUtil.getAdapter(); BluetoothAdapter adapter = BluetoothUtil.getAdapter();
serverSocket = adapter.listenUsingRfcommWithServiceRecord(service, UUID.fromString(service_uuid)); serverSocket = adapter.listenUsingRfcommWithServiceRecord(service, UUID.fromString(service_uuid));
//BluetoothUtil.setDiscoverable();
} }
public void run() { public void run() {
@ -68,6 +67,8 @@ public class BluetoothServer extends Thread {
* Will cancel the listening socket, and cause the thread to finish * Will cancel the listening socket, and cause the thread to finish
*/ */
public void close() { public void close() {
if(serverSocket == null)
return;
try { try {
serverSocket.close(); serverSocket.close();
serverSocket = null; serverSocket = null;

View file

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

View file

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