Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainActivity extends BleScannerActivity implements ServiceConnection {
- private BtleService.LocalBinder serviceBinder;
- private static final String LOG_TAG = "MainActivity";
- private MetaWearBoard board;
- private LoadDialog mLoadDialog;
- private Logging loggingModule;
- private SensorFusionBosch sensorFusionModule;
- private Led ledModule;
- private Switch switchModule;
- private FileOutputStream fosQuaternion;
- private FileOutputStream fosLinearAccelration;
- Route offlineLoggerRoute;
- private static final String LINEAR_ACC_FILENAME = "linear_acceleration.txt";
- private static final String QUATERNION_FILENAME = "quaternion.txt";
- private static Subscriber QUATERNION_SUBSCRIBER = new Subscriber() {
- @Override
- public void apply(Data data, Object... env) {
- try {
- Log.i(LOG_TAG, "STREAM Quaternion: {\"time\":\""+data.formattedTimestamp() + "\",\"quaternion\":" + data.value(Quaternion.class) + "}" ) ;
- FileOutputStream fos = (FileOutputStream) env[0];
- Quaternion casted = data.value(Quaternion.class);
- fos.write(String.format(Locale.US, "{\"time\":\"%s\",\"w\":%.3f,\"x\":%.3f,\"y\":%.3f,\"z\":%.3f}%n",
- data.formattedTimestamp(),
- casted.w(),casted.x(), casted.y(), casted.z()).getBytes());
- } catch (IOException ex) {
- Log.e("MainActivity", "Error writing to file", ex);
- }
- }
- };
- private static Subscriber LINEAR_ACCELERATION_SUBSCRIBER = new Subscriber() {
- @Override
- public void apply(Data data, Object... env) {
- try {
- Log.i(LOG_TAG, "LOG LinearAcceleration: {\"time\":\""+data.formattedTimestamp() + "\",\"linearAcc\":" + data.value(Acceleration.class) + "}" ) ;
- FileOutputStream fos = (FileOutputStream) env[0];
- Acceleration casted = data.value(Acceleration.class);
- fos.write(String.format(Locale.US, "{\"time\":\"%s\",\"x\":%.3f,\"y\":%.3f,\"z\":%.3f}%n",
- data.formattedTimestamp(),
- casted.x(), casted.y(), casted.z()).getBytes());
- } catch (IOException ex) {
- Log.e("MainActivity", "Error writing to file", ex);
- }
- }
- };
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // Bind the service when the activity is created
- getApplicationContext().bindService(new Intent(this, BtleService.class),
- this, Context.BIND_AUTO_CREATE);
- Button downloadBtn = findViewById(R.id.ble_button);
- downloadBtn.setText("Download");
- downloadBtn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- downloadLoggedData();
- }
- });
- mLoadDialog = new LoadDialog(this,1,"Trying to connect", new DialogListener () {
- @Override
- public void ready(int n) {
- // do your code here
- }
- @Override
- public void cancelled(int id) {
- cleanUp();
- if(board != null){
- board.disconnectAsync();
- }
- }
- });
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- cleanUp();
- // Unbind the service when the activity is destroyed
- getApplicationContext().unbindService(this);
- }
- private void cleanUp ( ) {
- if(offlineLoggerRoute != null ){
- offlineLoggerRoute.remove();
- }
- }
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- // Typecast the binder to the service's LocalBinder class
- serviceBinder = (BtleService.LocalBinder) service;
- }
- @Override
- public void onServiceDisconnected(ComponentName componentName) {
- }
- @Override
- public void onBleDeviceSelected(String deviceAddress){
- retrieveBoard(deviceAddress);
- mLoadDialog.show();
- connectBoard();
- }
- /**
- * Fetch the board based on the UUID
- * @param boardUuid
- */
- public void retrieveBoard(String boardUuid) {
- final BluetoothDevice remoteDevice = getBleAdapter().getRemoteDevice(boardUuid);
- // Create a MetaWear board object for the Bluetooth Device
- board = serviceBinder.getMetaWearBoard(remoteDevice);
- Log.d(LOG_TAG, "Board successfully fetched");
- board.onUnexpectedDisconnect(new MetaWearBoard.UnexpectedDisconnectHandler() {
- @Override
- public void disconnected(int status) {
- Log.i(LOG_TAG, "Unexpectedly lost connection: " + status);
- }
- });
- }
- public void connectBoard(){
- board.connectAsync().continueWith(new Continuation<Void, Void>() {
- @Override
- public Void then(Task<Void> task) throws Exception {
- if (task.isFaulted()) {
- Log.i(LOG_TAG, "Failed to connect");
- mLoadDialog.setTitle("Retrying connect");
- connectBoard();
- } else {
- Log.i(LOG_TAG, "Connected to a "+ board.getModelString());
- initModules();
- mLoadDialog.dismiss();
- setupRoutes();
- offlineLoggerRoute = addReactionOnClick().getResult();
- }
- return null;
- }
- });
- }
- public void initModules(){
- ledModule = board.getModule(Led.class);
- sensorFusionModule = board.getModule(SensorFusionBosch.class);
- loggingModule = board.getModule(Logging.class);
- switchModule = board.getModule(Switch.class);
- if(ledModule == null || sensorFusionModule == null || loggingModule == null || switchModule == null){
- Log.d(LOG_TAG, "One of the required modules are not supported");
- board.disconnectAsync();
- }
- }
- private void setupRoutes(){
- configureSensorFusion(SensorFusionBosch.Mode.IMU_PLUS, SensorFusionBosch.AccRange.AR_16G, SensorFusionBosch.GyroRange.GR_2000DPS );
- configureSensorFusionRoute(sensorFusionModule);
- configureLinearAccelerationRoute(sensorFusionModule);
- }
- public SensorFusionBosch configureSensorFusion(SensorFusionBosch.Mode mode, SensorFusionBosch.AccRange accRange, SensorFusionBosch.GyroRange gyroRange){
- sensorFusionModule.configure()
- .mode(mode)
- .accRange(accRange)
- .gyroRange(gyroRange)
- .commit();
- return sensorFusionModule;
- }
- public void configureSensorFusionRoute(SensorFusionBosch sensorFusionBosch) {
- sensorFusionBosch.quaternion().addRouteAsync(new RouteBuilder() {
- @Override
- public void configure(RouteComponent source) {
- source.log(QUATERNION_SUBSCRIBER);
- }
- }).continueWith(new Continuation<Route, Void>() {
- @Override
- public Void then(Task<Route> task) throws Exception {
- fosQuaternion = openFileOutput(QUATERNION_FILENAME, MODE_PRIVATE);
- // Pass the output stream to the first Subscriber (idx 0)
- // by setting its environment
- task.getResult().setEnvironment(0, fosQuaternion);
- return null;
- }
- });
- }
- public void configureLinearAccelerationRoute(SensorFusionBosch sensorFusionBosch){
- sensorFusionBosch.linearAcceleration().addRouteAsync(new RouteBuilder(){
- @Override
- public void configure(RouteComponent source) {
- source.log(LINEAR_ACCELERATION_SUBSCRIBER);
- }
- }).continueWith(new Continuation<Route, Void>() {
- @Override
- public Void then(Task<Route> task) throws Exception {
- fosLinearAccelration = openFileOutput(LINEAR_ACC_FILENAME, MODE_PRIVATE);
- // Pass the output stream to the first Subscriber (idx 0)
- // by seting its environment
- task.getResult().setEnvironment(0, fosLinearAccelration);
- return null;
- }
- });
- }
- /**
- * This should be used when
- *
- **/
- private Task<Route> addReactionOnClick() {
- setupRoutes();
- return switchModule.state().addRouteAsync(new RouteBuilder() {
- @Override
- public void configure(RouteComponent source) {
- source.accumulate()
- .map(Function2.MODULUS, 2)
- .multicast()
- .to().filter(Comparison.EQ, 1).react(new RouteComponent.Action() {
- @Override
- public void execute(DataToken token) {
- ledModule.editPattern(Led.Color.BLUE, Led.PatternPreset.BLINK)
- .repeatCount(Led.PATTERN_REPEAT_INDEFINITELY)
- .commit();
- ledModule.play();
- startLogging();
- }
- }).to().filter(Comparison.EQ, 0).react(new RouteComponent.Action() {
- @Override
- public void execute(DataToken token) {
- ledModule.stop(true);
- stopLogging();
- }
- }).end();
- }
- });
- }
- public void startLogging(){
- loggingModule.start(true);
- sensorFusionModule.quaternion().start();
- sensorFusionModule.linearAcceleration().start();
- sensorFusionModule.start();
- }
- public void stopLogging(){
- sensorFusionModule.quaternion().stop();
- sensorFusionModule.linearAcceleration().stop();
- sensorFusionModule.stop();
- loggingModule.stop();
- }
- public void downloadLoggedData() {
- // download log data and send 100 progress updates during the download
- if( board == null ){
- Log.d(LOG_TAG, "The board is not connected ....");
- return;
- }
- if(loggingModule == null){
- Log.d(LOG_TAG, "There logging module were not initiated");
- return;
- }
- loggingModule.downloadAsync(100, new Logging.LogDownloadUpdateHandler() {
- @Override
- public void receivedUpdate(long nEntriesLeft, long totalEntries) {
- Log.i("MainActivity", "Download progress Update = " + nEntriesLeft + "/" + totalEntries);
- }
- }).continueWithTask(new Continuation<Void, Task<Void>>() {
- @Override
- public Task<Void> then(Task<Void> task) throws Exception {
- Log.i("MainActivity", "Download completed " );
- loggingModule.clearEntries();
- openFile(QUATERNION_FILENAME);
- openFile(LINEAR_ACC_FILENAME);
- return null;
- }
- });
- }
- private void openFile(String filename){
- FileInputStream in = null;
- try {
- in = openFileInput(filename);
- InputStreamReader inputStreamReader = new InputStreamReader(in);
- BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- sb.append(line);
- Log.d(LOG_TAG,"Data: "+ line);
- }
- inputStreamReader.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement