Advertisement
Guest User

Mbientlab connection

a guest
Oct 24th, 2017
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.98 KB | None | 0 0
  1. public class MainActivity extends BleScannerActivity implements ServiceConnection {
  2.  
  3.     private BtleService.LocalBinder serviceBinder;
  4.     private static final String LOG_TAG = "MainActivity";
  5.     private MetaWearBoard board;
  6.     private LoadDialog mLoadDialog;
  7.  
  8.     private Logging loggingModule;
  9.     private SensorFusionBosch sensorFusionModule;
  10.     private Led ledModule;
  11.     private Switch switchModule;
  12.  
  13.     private FileOutputStream fosQuaternion;
  14.     private FileOutputStream fosLinearAccelration;
  15.     Route offlineLoggerRoute;
  16.     private static final String LINEAR_ACC_FILENAME = "linear_acceleration.txt";
  17.     private static final String QUATERNION_FILENAME = "quaternion.txt";
  18.  
  19.     private static Subscriber QUATERNION_SUBSCRIBER = new Subscriber() {
  20.         @Override
  21.         public void apply(Data data, Object... env) {
  22.             try {
  23.                 Log.i(LOG_TAG, "STREAM Quaternion: {\"time\":\""+data.formattedTimestamp() + "\",\"quaternion\":" + data.value(Quaternion.class) + "}" ) ;
  24.  
  25.                 FileOutputStream fos = (FileOutputStream) env[0];
  26.                 Quaternion casted = data.value(Quaternion.class);
  27.                 fos.write(String.format(Locale.US, "{\"time\":\"%s\",\"w\":%.3f,\"x\":%.3f,\"y\":%.3f,\"z\":%.3f}%n",
  28.                         data.formattedTimestamp(),
  29.                         casted.w(),casted.x(), casted.y(), casted.z()).getBytes());
  30.             } catch (IOException ex) {
  31.                 Log.e("MainActivity", "Error writing to file", ex);
  32.             }
  33.         }
  34.     };
  35.  
  36.     private static Subscriber LINEAR_ACCELERATION_SUBSCRIBER = new Subscriber() {
  37.         @Override
  38.         public void apply(Data data, Object... env) {
  39.             try {
  40.                 Log.i(LOG_TAG, "LOG LinearAcceleration: {\"time\":\""+data.formattedTimestamp() + "\",\"linearAcc\":" + data.value(Acceleration.class) + "}" ) ;
  41.  
  42.                 FileOutputStream fos = (FileOutputStream) env[0];
  43.                 Acceleration casted = data.value(Acceleration.class);
  44.                 fos.write(String.format(Locale.US, "{\"time\":\"%s\",\"x\":%.3f,\"y\":%.3f,\"z\":%.3f}%n",
  45.                         data.formattedTimestamp(),
  46.                         casted.x(), casted.y(), casted.z()).getBytes());
  47.             } catch (IOException ex) {
  48.                 Log.e("MainActivity", "Error writing to file", ex);
  49.             }
  50.         }
  51.     };
  52.  
  53.     @Override
  54.     protected void onCreate(Bundle savedInstanceState) {
  55.         super.onCreate(savedInstanceState);
  56.  
  57.         // Bind the service when the activity is created
  58.         getApplicationContext().bindService(new Intent(this, BtleService.class),
  59.                 this, Context.BIND_AUTO_CREATE);
  60.  
  61.         Button downloadBtn = findViewById(R.id.ble_button);
  62.         downloadBtn.setText("Download");
  63.         downloadBtn.setOnClickListener(new View.OnClickListener() {
  64.             @Override
  65.             public void onClick(View view) {
  66.                 downloadLoggedData();
  67.             }
  68.         });
  69.  
  70.         mLoadDialog = new LoadDialog(this,1,"Trying to connect", new DialogListener () {
  71.             @Override
  72.             public void ready(int n) {
  73.                 // do your code here
  74.             }
  75.             @Override
  76.             public void cancelled(int id) {
  77.                 cleanUp();
  78.                 if(board != null){
  79.                    board.disconnectAsync();
  80.                 }
  81.             }
  82.         });
  83.     }
  84.  
  85.  
  86.     @Override
  87.     public void onDestroy() {
  88.         super.onDestroy();
  89.         cleanUp();
  90.         // Unbind the service when the activity is destroyed
  91.         getApplicationContext().unbindService(this);
  92.  
  93.     }
  94.  
  95.     private void cleanUp ( ) {
  96.         if(offlineLoggerRoute != null ){
  97.             offlineLoggerRoute.remove();
  98.         }
  99.     }
  100.     @Override
  101.     public void onServiceConnected(ComponentName name, IBinder service) {
  102.         // Typecast the binder to the service's LocalBinder class
  103.         serviceBinder = (BtleService.LocalBinder) service;
  104.     }
  105.  
  106.     @Override
  107.     public void onServiceDisconnected(ComponentName componentName) {
  108.  
  109.     }
  110.  
  111.     @Override
  112.     public void onBleDeviceSelected(String deviceAddress){
  113.         retrieveBoard(deviceAddress);
  114.         mLoadDialog.show();
  115.         connectBoard();
  116.     }
  117.  
  118.     /**
  119.      * Fetch the board based on the UUID
  120.      * @param boardUuid
  121.      */
  122.     public void retrieveBoard(String boardUuid) {
  123.  
  124.          final BluetoothDevice remoteDevice =  getBleAdapter().getRemoteDevice(boardUuid);
  125.  
  126.         // Create a MetaWear board object for the Bluetooth Device
  127.         board = serviceBinder.getMetaWearBoard(remoteDevice);
  128.  
  129.         Log.d(LOG_TAG, "Board successfully fetched");
  130.  
  131.         board.onUnexpectedDisconnect(new MetaWearBoard.UnexpectedDisconnectHandler() {
  132.             @Override
  133.             public void disconnected(int status) {
  134.                 Log.i(LOG_TAG, "Unexpectedly lost connection: " + status);
  135.             }
  136.         });
  137.     }
  138.  
  139.  
  140.     public void connectBoard(){
  141.         board.connectAsync().continueWith(new Continuation<Void, Void>() {
  142.             @Override
  143.             public Void then(Task<Void> task) throws Exception {
  144.                 if (task.isFaulted()) {
  145.                     Log.i(LOG_TAG, "Failed to connect");
  146.                     mLoadDialog.setTitle("Retrying connect");
  147.                     connectBoard();
  148.                 } else {
  149.                     Log.i(LOG_TAG, "Connected to a "+ board.getModelString());
  150.                     initModules();
  151.                     mLoadDialog.dismiss();
  152.                     setupRoutes();
  153.                     offlineLoggerRoute = addReactionOnClick().getResult();
  154.  
  155.  
  156.                 }
  157.                 return null;
  158.             }
  159.         });
  160.  
  161.     }
  162.  
  163.  
  164.     public void initModules(){
  165.         ledModule = board.getModule(Led.class);
  166.         sensorFusionModule = board.getModule(SensorFusionBosch.class);
  167.         loggingModule = board.getModule(Logging.class);
  168.         switchModule = board.getModule(Switch.class);
  169.         if(ledModule == null || sensorFusionModule == null || loggingModule == null || switchModule == null){
  170.             Log.d(LOG_TAG, "One of the required modules are not supported");
  171.             board.disconnectAsync();
  172.         }
  173.  
  174.     }
  175.  
  176.  
  177.     private void setupRoutes(){
  178.         configureSensorFusion(SensorFusionBosch.Mode.IMU_PLUS, SensorFusionBosch.AccRange.AR_16G, SensorFusionBosch.GyroRange.GR_2000DPS );
  179.         configureSensorFusionRoute(sensorFusionModule);
  180.         configureLinearAccelerationRoute(sensorFusionModule);
  181.     }
  182.  
  183.  
  184.     public SensorFusionBosch configureSensorFusion(SensorFusionBosch.Mode mode, SensorFusionBosch.AccRange accRange, SensorFusionBosch.GyroRange gyroRange){
  185.  
  186.         sensorFusionModule.configure()
  187.                 .mode(mode)
  188.                 .accRange(accRange)
  189.                 .gyroRange(gyroRange)
  190.                 .commit();
  191.         return sensorFusionModule;
  192.     }
  193.  
  194.     public void configureSensorFusionRoute(SensorFusionBosch sensorFusionBosch) {
  195.         sensorFusionBosch.quaternion().addRouteAsync(new RouteBuilder() {
  196.             @Override
  197.             public void configure(RouteComponent source) {
  198.                 source.log(QUATERNION_SUBSCRIBER);
  199.             }
  200.         }).continueWith(new Continuation<Route, Void>() {
  201.             @Override
  202.             public Void then(Task<Route> task) throws Exception {
  203.                 fosQuaternion = openFileOutput(QUATERNION_FILENAME, MODE_PRIVATE);
  204.                 // Pass the output stream to the first Subscriber (idx 0)
  205.                 // by setting its environment
  206.                 task.getResult().setEnvironment(0, fosQuaternion);
  207.                 return null;
  208.             }
  209.         });
  210.  
  211.     }
  212.  
  213.     public void configureLinearAccelerationRoute(SensorFusionBosch sensorFusionBosch){
  214.         sensorFusionBosch.linearAcceleration().addRouteAsync(new RouteBuilder(){
  215.             @Override
  216.             public void configure(RouteComponent source) {
  217.                 source.log(LINEAR_ACCELERATION_SUBSCRIBER);
  218.             }
  219.         }).continueWith(new Continuation<Route, Void>() {
  220.             @Override
  221.             public Void then(Task<Route> task) throws Exception {
  222.                 fosLinearAccelration = openFileOutput(LINEAR_ACC_FILENAME, MODE_PRIVATE);
  223.                 // Pass the output stream to the first Subscriber (idx 0)
  224.                 // by seting its environment
  225.                 task.getResult().setEnvironment(0, fosLinearAccelration);
  226.                 return null;
  227.             }
  228.         });
  229.     }
  230.  
  231.     /**
  232.      * This should be used when
  233.      *
  234.      **/
  235.  
  236.     private Task<Route> addReactionOnClick() {
  237.         setupRoutes();
  238.         return switchModule.state().addRouteAsync(new RouteBuilder() {
  239.             @Override
  240.             public void configure(RouteComponent source) {
  241.  
  242.                 source.accumulate()
  243.                         .map(Function2.MODULUS, 2)
  244.                         .multicast()
  245.                         .to().filter(Comparison.EQ, 1).react(new RouteComponent.Action() {
  246.                     @Override
  247.                     public void execute(DataToken token) {
  248.  
  249.                         ledModule.editPattern(Led.Color.BLUE, Led.PatternPreset.BLINK)
  250.                                 .repeatCount(Led.PATTERN_REPEAT_INDEFINITELY)
  251.                                 .commit();
  252.                         ledModule.play();
  253.                         startLogging();
  254.                     }
  255.                 }).to().filter(Comparison.EQ, 0).react(new RouteComponent.Action() {
  256.                     @Override
  257.                     public void execute(DataToken token) {
  258.                         ledModule.stop(true);
  259.                         stopLogging();
  260.                     }
  261.                 }).end();
  262.             }
  263.         });
  264.     }
  265.  
  266.  
  267.     public void startLogging(){
  268.         loggingModule.start(true);
  269.         sensorFusionModule.quaternion().start();
  270.         sensorFusionModule.linearAcceleration().start();
  271.         sensorFusionModule.start();
  272.     }
  273.     public void stopLogging(){
  274.         sensorFusionModule.quaternion().stop();
  275.         sensorFusionModule.linearAcceleration().stop();
  276.         sensorFusionModule.stop();
  277.         loggingModule.stop();
  278.  
  279.     }
  280.  
  281.     public void downloadLoggedData() {
  282.         // download log data and send 100 progress updates during the download
  283.  
  284.         if( board == null ){
  285.             Log.d(LOG_TAG, "The board is not connected ....");
  286.             return;
  287.         }
  288.         if(loggingModule == null){
  289.             Log.d(LOG_TAG, "There logging module were not initiated");
  290.             return;
  291.         }
  292.  
  293.  
  294.         loggingModule.downloadAsync(100, new Logging.LogDownloadUpdateHandler() {
  295.             @Override
  296.             public void receivedUpdate(long nEntriesLeft, long totalEntries) {
  297.                 Log.i("MainActivity", "Download progress Update = " + nEntriesLeft + "/" + totalEntries);
  298.  
  299.             }
  300.         }).continueWithTask(new Continuation<Void, Task<Void>>() {
  301.             @Override
  302.             public Task<Void> then(Task<Void> task) throws Exception {
  303.                 Log.i("MainActivity", "Download completed " );
  304.                 loggingModule.clearEntries();
  305.                 openFile(QUATERNION_FILENAME);
  306.                 openFile(LINEAR_ACC_FILENAME);
  307.                 return null;
  308.             }
  309.         });
  310.     }
  311.  
  312.     private void openFile(String filename){
  313.         FileInputStream in = null;
  314.         try {
  315.             in = openFileInput(filename);
  316.  
  317.             InputStreamReader inputStreamReader = new InputStreamReader(in);
  318.             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  319.             StringBuilder sb = new StringBuilder();
  320.             String line;
  321.             while ((line = bufferedReader.readLine()) != null) {
  322.                 sb.append(line);
  323.  
  324.                 Log.d(LOG_TAG,"Data: "+ line);
  325.             }
  326.             inputStreamReader.close();
  327.  
  328.         } catch (FileNotFoundException e) {
  329.             e.printStackTrace();
  330.         } catch (IOException e) {
  331.             e.printStackTrace();
  332.         }
  333.     }
  334.  
  335. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement