Commit d7537066 authored by LIly's avatar LIly
Browse files

move simulator around

parent 80948d67
......@@ -95,11 +95,6 @@ public class EncounterBasedCommunication {
}
public interface ISDDRClient {
/**
* Begin the encounter formation service simulating encounters
*/
void startSimulatingEncounters();
/**
* Begin the encounter formation service, which emits BLE adverts and occasional BLE scans to
* detect and form encounters with nearby EbC devices
......
......@@ -34,14 +34,6 @@ public class SDDRClient implements EncounterBasedCommunication.ISDDRClient {
this.context = context;
}
@Override
public void startSimulatingEncounters() {
Intent serviceIntent = new Intent(context, EncounterFormationService.class);
serviceIntent.putExtra("start_simulated_sddr_service", 0);
context.startService(serviceIntent);
Log.d(TAG, "Started simulated encounters service");
}
@Override
public void startFormingEncounters() {
Intent serviceIntent = new Intent(context, EncounterFormationService.class);
......
......@@ -12,8 +12,6 @@ import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
import org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore;
/**
* Created by tslilyai on 10/27/17.
*/
......@@ -25,9 +23,7 @@ import org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterForm
*/
public class EncounterFormationService extends Service {
private static final String TAG = EncounterFormationService.class.getSimpleName();
private static boolean SIMULATE = false;
private EncounterFormationCore core;
private SimulatorEncounterFormationCore score;
private Thread thread;
public boolean was_destroyed = false;
......@@ -50,13 +46,6 @@ public class EncounterFormationService extends Service {
this.stopSelf();
}
Log.v(TAG, "Bluetooth and location permissions enabled");
if (SIMULATE && score==null) {
Log.v(TAG, "Starting SDDR_API Core from thread " + Thread.currentThread().getName());
Log.v(TAG, "Simulated? " + SIMULATE);
score = new SimulatorEncounterFormationCore(this);
thread = new Thread(score);
thread.start();
}
if (core == null) {
Log.v(TAG, "Starting SDDR_API Core from thread " + Thread.currentThread().getName());
core = new EncounterFormationCore(this);
......@@ -79,15 +68,8 @@ public class EncounterFormationService extends Service {
return START_STICKY;
}
if (intent.getExtras().containsKey("start_simulated_sddr_service"))
{
SIMULATE = true;
check_and_start_core();
}
if (intent.getExtras().containsKey("@string.start_sddr_service"))
{
SIMULATE = false;
check_and_start_core();
return START_STICKY;
}
......@@ -133,10 +115,6 @@ public class EncounterFormationService extends Service {
core.stop();
core = null;
}
if (score != null) {
score.stop();
score = null;
}
was_destroyed = true;
}
......
package org.mpisws.encounters.encounterformation.simulator;
/**
* Created by tslilyai on 10/18/17.
*/
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.os.ParcelUuid;
import android.util.Log;
import org.mpisws.helpers.Utils;
import java.nio.ByteBuffer;
import java.util.UUID;
import static android.bluetooth.le.AdvertiseSettings.ADVERTISE_MODE_LOW_POWER;
/**
* Manages BLE Advertising.
*/
public class SimulatorAdvertiser {
public static final int TOTAL_LENGTH = 31;
public static final int SHA1_LENGTH = 20;
public static final int PUUID_LENGTH = 16;
public static final int NONCE_LENGTH_IN_ADVERT = SHA1_LENGTH - PUUID_LENGTH ;
private static final String TAG = SimulatorAdvertiser.class.getSimpleName();
private BluetoothLeAdvertiser mBluetoothLeAdvertiser;
private AdvertiseCallback mAdvertiseCallback;
private AdvertiseSettings mAdvertiseSettings;
private UUID mUUID;
private boolean connectable;
public static byte[] mPUUID = new byte[PUUID_LENGTH];
public static byte[] mAdData = new byte[NONCE_LENGTH_IN_ADVERT];
public void initialize(BluetoothAdapter btAdapter) {
mBluetoothLeAdvertiser = btAdapter.getBluetoothLeAdvertiser();
connectable = false;
}
public void setConnectable(boolean connect) {
this.connectable = connect;
}
public void setAdData(byte[] newData) {
int amountToIncludeInPUUID = PUUID_LENGTH ;
Utils.myAssert(newData.length == SHA1_LENGTH);
// copy what data can fit into the puuid slot
System.arraycopy(newData, 0, mPUUID, 0, amountToIncludeInPUUID);
System.arraycopy(newData, amountToIncludeInPUUID, mAdData, 0, SHA1_LENGTH - amountToIncludeInPUUID);
ByteBuffer bb = ByteBuffer.wrap(mPUUID);
long high = bb.getLong();
long low = bb.getLong();
mUUID = new UUID(high, low);
Log.v(TAG, "New Advert " + Utils.getHexString(mPUUID) + Utils.getHexString(mAdData));
}
public void resetAdvertiser() {
if (mAdvertiseCallback != null)
mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
startAdvertising();
}
public void startAdvertising() {
if (mAdvertiseCallback == null) {
mAdvertiseCallback = new SDDRAdvertiseCallback();
mAdvertiseSettings = buildAdvertiseSettings();
}
if (mBluetoothLeAdvertiser != null) {
mBluetoothLeAdvertiser.startAdvertising(
mAdvertiseSettings,
buildAdvertiseData(),
mAdvertiseCallback
);
}
}
/**
* Stops BLE Advertising.
*/
public void stopAdvertising() {
if (mBluetoothLeAdvertiser != null) {
mBluetoothLeAdvertiser.stopAdvertising(mAdvertiseCallback);
mAdvertiseCallback = null;
}
}
/**
* Returns an AdvertiseData object which includes the Service UUID and Device Name.
*/
private AdvertiseData buildAdvertiseData() {
/**
* Note: There is a strict limit of 31 Bytes on packets sent over BLE Advertisements.
* This includes everything put into AdvertiseData including UUIDs, device info, &
* arbitrary service or manufacturer data.
* Attempting to send packets over this limit will result in a failure with error code
* AdvertiseCallback.ADVERTISE_FAILED_DATA_TOO_LARGE. Catch this error in the
* onStartFailure() method of an AdvertiseCallback implementation.
*/
AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
dataBuilder.setIncludeDeviceName(false);
dataBuilder.setIncludeTxPowerLevel(false);
dataBuilder.addServiceData(new ParcelUuid(mUUID), mAdData);
return dataBuilder.build();
}
/**
* Returns an AdvertiseSetParameters object
*/
private AdvertiseSettings buildAdvertiseSettings() {
AdvertiseSettings.Builder settingsBuilder = new AdvertiseSettings.Builder();
settingsBuilder.setConnectable(connectable);
settingsBuilder.setAdvertiseMode(ADVERTISE_MODE_LOW_POWER);//ADVERTISE_MODE_LOW_LATENCY);
settingsBuilder.setTimeout(0);
return settingsBuilder.build();
}
/**
* Custom callback after Advertising succeeds or fails to start.
*/
private class SDDRAdvertiseCallback extends AdvertiseCallback {
@Override
public void onStartFailure(int errorCode) {
super.onStartFailure(errorCode);
if (errorCode == ADVERTISE_FAILED_DATA_TOO_LARGE) {
Log.v(TAG, "Advertising failed: Data too large!");
}
else Log.v(TAG, "Advertising failed: Unknown " + errorCode);
}
@Override
public void onStartSuccess(AdvertiseSettings settingsInEffect) {
super.onStartSuccess(settingsInEffect);
Log.v(TAG, "Advertising successfully started");
}
}
}
......@@ -11,7 +11,6 @@ import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
......@@ -21,17 +20,12 @@ import android.widget.Toast;
import org.mpisws.embeddedsocial.ESClient;
import org.mpisws.encounters.EncounterBasedCommunication;
import org.mpisws.encounters.encounterformation.simulator.SimulatorAdvertiser;
import org.mpisws.messaging.ReceivedMessageWrapper;
import org.mpisws.testapp.googleauth.GoogleNativeAuthenticator;
import org.mpisws.testapp.googleauth.GoogleToken;
import org.mpisws.testapp.tests.ESBatchTester;
import org.mpisws.testapp.tests.SimulatorTestServer;
import org.mpisws.testapp.simulator.SimulationClient;
import org.mpisws.testapp.simulator.SimulationServer;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
import static org.mpisws.encounters.EncounterBasedCommunication.REQUEST_ACCESS_FINE_LOCATION;
......@@ -63,6 +57,8 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
findViewById(R.id.testESFunctions).setOnClickListener(this);
findViewById(R.id.testSendMessages).setOnClickListener(this);
findViewById(R.id.testReceiveMessages).setOnClickListener(this);
findViewById(R.id.simulateEncounterFormationAndConfirmationClient).setOnClickListener(this);
findViewById(R.id.simulateEncounterFormationAndConfirmationServer).setOnClickListener(this);
findViewById(R.id.testEndToEndES).setOnClickListener(this);
findViewById(R.id.testEndToEndBLE).setOnClickListener(this);
findViewById(R.id.testWithoutConfirmation).setOnClickListener(this);
......@@ -98,12 +94,12 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
/***************************** ES AND SDDR TESTS **********************/
case R.id.simulateEncounterFormationAndConfirmationClient:
ebc.getSDDRClient().startSimulatingEncounters();
if (!isSignedIn()) throw new SecurityException("Not signed in");
new SimulationClient(this).sendDataToSimulationServerAndStartCore();
break;
case R.id.simulateEncounterFormationAndConfirmationServer:
SimulatorTestServer simulator = new SimulatorTestServer(this);
simulator.registerService();
simulator.startServer();
if (!isSignedIn()) throw new SecurityException("Not signed in");
new SimulationServer(this).startServer();
break;
case R.id.testSendMessages:
ebc.getSDDRClient().updateDatabaseOnAgent();
......
package org.mpisws.testapp;
package org.mpisws.testapp.simulator;
import android.content.Context;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdServiceInfo;
import android.util.Log;
import org.mpisws.encounters.encounterformation.SDDR_Native;
import org.mpisws.helpers.Identifier;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
......@@ -14,13 +17,24 @@ import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.mSharedSecrets;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.otherDHNonces;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.otherDHPubKeys;
import java.util.ArrayList;
import java.util.List;
public class SimulationClient {
static private String TAG = SimulationClient.class.getSimpleName();
static private SimulatorEncounterFormationCore core;
protected static final int NUM_SIMULATED_DEVICES = 10;
protected static final int NUM_SIMULATED_EPOCHS = 10;
protected static List<Identifier> mDHPubKeys = new ArrayList<>(NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mDHNonces = new ArrayList<>(NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mDHFullKeys = new ArrayList<>(NUM_SIMULATED_EPOCHS);
protected static List<Identifier> otherDHPubKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static List<Identifier> otherDHNonces = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static List<Identifier> otherDHFullKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mSharedSecrets = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static int CURRENT_EPOCH = 0;
static private String mServiceName = "EbCSimulator";
static private String mServiceType = "_ebcsimulator._tcp";
......@@ -32,17 +46,42 @@ public class SimulationClient {
private int mPort;
private Socket sock = null;
SimulationClient(Context context) {
public SimulationClient(Context context) {
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}
public void sendDataToSimulationServer() {
initializeSimulatedAdverts();
initializeDiscoveryListener();
initializeResolveListener();
core = new SimulatorEncounterFormationCore(context);
}
public void sendDataToSimulationServerAndStartCore() {
mNsdManager.discoverServices(mServiceType, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
public void initializeDiscoveryListener() {
private void initializeSimulatedAdverts() {
for (int i = 0; i < NUM_SIMULATED_EPOCHS*NUM_SIMULATED_DEVICES; i++) {
SDDR_Native.c_changeEpoch();
otherDHPubKeys.add(new Identifier(SDDR_Native.c_getAdvertDHPubKey()));
otherDHFullKeys.add(new Identifier(SDDR_Native.c_getAdvertDHKey()));
otherDHNonces.add(new Identifier(SDDR_Native.c_getMyAdvert()));
}
for (int i = 0; i < NUM_SIMULATED_EPOCHS; i++) {
SDDR_Native.c_changeEpoch();
mDHPubKeys.add(new Identifier(SDDR_Native.c_getAdvertDHPubKey()));
mDHFullKeys.add(new Identifier(SDDR_Native.c_getAdvertDHKey()));
mDHNonces.add(new Identifier(SDDR_Native.c_getMyAdvert()));
for (int j = 0; j < NUM_SIMULATED_DEVICES; j++) {
Identifier sharedSecret = new Identifier(SDDR_Native.c_computeSecretKeyWithSHA(
otherDHFullKeys.get(j+(NUM_SIMULATED_DEVICES*i)).getBytes(),
mDHNonces.get(i).getBytes(),
mDHPubKeys.get(i).getBytes()));
mSharedSecrets.add(sharedSecret);
}
}
}
private void initializeDiscoveryListener() {
// Instantiate a new DiscoveryListener
mDiscoveryListener = new NsdManager.DiscoveryListener() {
......@@ -91,7 +130,7 @@ public class SimulationClient {
};
}
public void initializeResolveListener() {
private void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
@Override
......@@ -118,7 +157,7 @@ public class SimulationClient {
};
}
public void sendDHKeysOverSocket() {
private void sendDHKeysOverSocket() {
new Thread(() -> {
try {
sock = new Socket(mHost, mPort);
......@@ -156,12 +195,16 @@ public class SimulationClient {
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
Log.d(TAG, line);
Log.d(TAG, "Got response: " + line);
}
in.close();
pw.close();
sock.close();
// run the simulator core
Log.d(TAG, "Running simulator core!");
core.run();
} catch (IOException e) {
e.printStackTrace();
}
......
package org.mpisws.testapp;
package org.mpisws.testapp.simulator;
import android.content.Context;
import android.net.nsd.NsdManager;
......@@ -26,9 +26,9 @@ import java.util.ArrayList;
import java.util.List;
import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIME;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.NUM_SIMULATED_DEVICES;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.NUM_SIMULATED_EPOCHS;
import static org.mpisws.helpers.Utils.SHA1;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_DEVICES;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_EPOCHS;
public class SimulationServer {
private static final String TAG = SimulationServer.class.getSimpleName();
......@@ -44,7 +44,7 @@ public class SimulationServer {
private List<Identifier> sharedSecrets;
private List<Identifier> pubKeys;
SimulationServer(Context context) {
public SimulationServer(Context context) {
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}
......@@ -73,7 +73,7 @@ public class SimulationServer {
sharedSecrets = deserializeIDList(lines.get(0));
nonces = deserializeIDList(lines.get(1));
pubKeys = deserializeIDList(lines.get(2));
if (sharedSecrets == null || nonces == null) {
if (sharedSecrets == null || nonces == null || pubKeys == null) {
return;
}
output.close();
......@@ -96,6 +96,7 @@ public class SimulationServer {
for (Identifier ss : sharedSecrets) {
topicsToCreate.add(new ImmutablePair<>(ss, ss));
}
Log.d(TAG, "Creating topics: " + topicsToCreate.size());
ESClient.getInstance().createTopics(topicsToCreate);
// Every "epoch" or so try to post link messages to the prior "epoch" ss for each "device"
......@@ -138,7 +139,7 @@ public class SimulationServer {
return obj;
}
public void registerService(int port) {
private void registerService(int port) {
// Create the NsdServiceInfo object, and populate it.
NsdServiceInfo serviceInfo = new NsdServiceInfo();
......@@ -152,7 +153,7 @@ public class SimulationServer {
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
public void initializeRegistrationListener() {
private void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
@Override
......
package org.mpisws.encounters.encounterformation.simulator;
package org.mpisws.testapp.simulator;
import android.content.Context;
import android.util.Log;
......@@ -28,10 +28,10 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.getOngoingEncounters;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.mDHFullKey;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.mDHPubKey;
import static org.mpisws.encounters.encounterformation.simulator.SimulatorEncounterFormationCore.mNonce;
import static org.mpisws.testapp.simulator.SimulatorEncounterFormationCore.getOngoingEncounters;
import static org.mpisws.testapp.simulator.SimulatorEncounterFormationCore.mDHFullKey;
import static org.mpisws.testapp.simulator.SimulatorEncounterFormationCore.mDHPubKey;
import static org.mpisws.testapp.simulator.SimulatorEncounterFormationCore.mNonce;
import static org.mpisws.messaging.ReceivedMessageWrapper.MsgTyp.EPOCH_LINK;
/**
......
package org.mpisws.encounters.encounterformation.simulator;
package org.mpisws.testapp.simulator;
/**
* Created by tslilyai on 10/16/17.
......@@ -10,26 +10,19 @@ import android.content.Context;
import android.os.Looper;
import android.util.Log;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.mpisws.embeddedsocial.ESClient;
import org.mpisws.encounters.encounterformation.EncounterFormationService;
import org.mpisws.encounters.encounterformation.SDDR_Native;
import org.mpisws.encounters.encounterhistory.bridges.EncounterEntriesBridge;
import org.mpisws.encounters.encounterformation.Advertiser;
import org.mpisws.helpers.Identifier;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIME;
import static org.mpisws.testapp.simulator.SimulationClient.NUM_SIMULATED_EPOCHS;
import static org.mpisws.testapp.simulator.SimulationClient.CURRENT_EPOCH;
import static org.mpisws.testapp.simulator.SimulationClient.mDHFullKeys;
import static org.mpisws.testapp.simulator.SimulationClient.mDHNonces;
import static org.mpisws.testapp.simulator.SimulationClient.mDHPubKeys;
/**
* SDDR_Core implements the core functionality of the SDDR protocol. It is started and called by the
......@@ -40,17 +33,6 @@ import static org.mpisws.encounters.EncounterBasedCommunication.CHANGE_EPOCH_TIM
*/
public class SimulatorEncounterFormationCore implements Runnable {
private static final String TAG = SimulatorEncounterFormationCore.class.getSimpleName();
public static final int NUM_SIMULATED_DEVICES = 10;
public static final int NUM_SIMULATED_EPOCHS = 20;
protected static List<Identifier> mDHPubKeys = new ArrayList<>(NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mDHNonces = new ArrayList<>(NUM_SIMULATED_EPOCHS);
protected static List<Identifier> mDHFullKeys = new ArrayList<>(NUM_SIMULATED_EPOCHS);
public static List<Identifier> otherDHPubKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
public static List<Identifier> otherDHNonces = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static List<Identifier> otherDHFullKeys = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
public static List<Identifier> mSharedSecrets = new ArrayList<>(NUM_SIMULATED_DEVICES*NUM_SIMULATED_EPOCHS);
protected static int CURRENT_EPOCH = 0;
protected static Identifier mDHPubKey;
protected static Identifier mNonce;
protected static Identifier mDHFullKey;
......@@ -59,13 +41,13 @@ public class SimulatorEncounterFormationCore implements Runnable {
private BluetoothManager bluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private SimulatorAdvertiser mAdvertiser;
private Advertiser mAdvertiser;
private SimulatorScannerProcessor mScannerProcessor;
private long changeEpochTime;
protected Context mService;
public SimulatorEncounterFormationCore(EncounterFormationService service) {
this.mService = service;
public SimulatorEncounterFormationCore(Context context) {
this.mService = context;
}
private void initialize() {
......@@ -73,7 +55,7 @@ public class SimulatorEncounterFormationCore implements Runnable {
Log.v(TAG, "Initialize SDDRCore on thread " + Thread.currentThread().getName());
this.bluetoothManager = (BluetoothManager) mService.getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
mAdvertiser = new SimulatorAdvertiser();
mAdvertiser = new Advertiser();
mScannerProcessor = new SimulatorScannerProcessor();