Advertisement
Guest User

Untitled

a guest
Jan 20th, 2020
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.14 KB | None | 0 0
  1. package com.example.androidsensor;
  2.  
  3. import androidx.appcompat.app.AppCompatActivity;
  4. import androidx.core.app.ActivityCompat;
  5. import androidx.core.content.ContextCompat;
  6.  
  7. import android.Manifest;
  8. import android.content.pm.PackageManager;
  9. import android.graphics.Color;
  10. import android.os.Bundle;
  11.  
  12. import android.content.Context;
  13. import android.hardware.Sensor;
  14. import android.hardware.SensorEvent;
  15. import android.hardware.SensorEventListener;
  16. import android.hardware.SensorManager;
  17.  
  18. import android.os.Environment;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.widget.TextView;
  22. import android.widget.Button;
  23.  
  24. import com.github.mikephil.charting.charts.LineChart;
  25. import com.github.mikephil.charting.components.Legend;
  26. import com.github.mikephil.charting.components.XAxis;
  27. import com.github.mikephil.charting.components.YAxis;
  28. import com.github.mikephil.charting.data.Entry;
  29. import com.github.mikephil.charting.data.LineData;
  30. import com.github.mikephil.charting.data.LineDataSet;
  31. import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
  32. import com.google.firebase.database.DatabaseReference;
  33. import com.google.firebase.database.FirebaseDatabase;
  34.  
  35. import java.io.BufferedReader;
  36. import java.io.BufferedWriter;
  37. import java.io.File;
  38. import java.io.FileOutputStream;
  39. import java.io.FileReader;
  40. import java.io.FileWriter;
  41. import java.io.IOException;
  42. import java.io.InputStream;
  43. import java.io.InputStreamReader;
  44.  
  45. import java.util.Locale;
  46. import java.text.SimpleDateFormat;
  47. import java.util.Date;
  48.  
  49. public class MainActivity extends AppCompatActivity implements SensorEventListener {
  50.  
  51.     private SensorManager mSensorManager;
  52.     private Sensor mSensorAccelerometer;
  53.     private Sensor mSensorGyroscope;
  54.     private Sensor mSensorMagnetometer;
  55.     private Sensor mSensorOrientation;
  56.  
  57.     private TextView mTextSensorAccelerometer;
  58.     private TextView mTextSensorGyroscope;
  59.     private TextView mTextSensorOrientation;
  60.  
  61.     private LineChart mChartGyro, mChartAccel, mChartMagneto;
  62.  
  63.     private float firstValue, secondValue, thirdValue; // Variables to store data retrieved form sensor
  64.  
  65.     private Thread thread;
  66.     private boolean plotData = true;
  67.  
  68.     private File fileDir, file;
  69.     private TextView tv;
  70.     private Context context;
  71.  
  72.     private Button startButton;
  73.     private Button stopButton;
  74.     private boolean record = false;
  75.  
  76.     // Server related
  77.     private FirebaseDatabase mFirebaseDatabase;
  78.     private DatabaseReference mDatabase;
  79.  
  80.     @Override
  81.     protected void onCreate(Bundle savedInstanceState) {
  82.  
  83.         super.onCreate(savedInstanceState);
  84.         setContentView(R.layout.activity_main);
  85.  
  86.         // Get database info
  87.         mFirebaseDatabase = FirebaseDatabase.getInstance();
  88.         mDatabase = mFirebaseDatabase.getReference("data");
  89.  
  90.  
  91.  
  92.  
  93.         mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // SensorManager to access device sensors
  94.  
  95.         // Access text in the app.
  96.         mTextSensorAccelerometer = (TextView) findViewById(R.id.label_accelerometer);
  97.         mTextSensorOrientation = (TextView) findViewById(R.id.label_compass);
  98.         //mTextSensorOrientation = (TextView) findViewById(R.id.label_compass);
  99.  
  100.         // Variables to get sensors
  101.         mSensorAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
  102.         mSensorGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
  103.         mSensorMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED);
  104.         mSensorOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
  105.  
  106.  
  107.         /*   NOTE : There's TYPE_ACCELEROMETER and TYPE_LINEAR_ACCELERATION that can be used
  108.          *   TYPE_ACCELEROMETER will provide data with gravity calculations
  109.          *   TYPE_LINEAR_ACCELERATION will give raw data
  110.          *   Will need further discussion on which is more appropriate as the X Y Z values given might differ.
  111.          * */
  112.  
  113.         // Print the string variable if no sensor is detected, e.g device doesn't have the sensor.
  114.         String sensor_error = getResources().getString(R.string.error_no_sensor);
  115.         if(mSensorAccelerometer == null) {
  116.             mTextSensorAccelerometer.setText(sensor_error);
  117.         }
  118.         if(mSensorGyroscope == null) {
  119.             mTextSensorGyroscope.setText(sensor_error);
  120.         }
  121.  
  122.         if(mSensorOrientation == null) {
  123.             mTextSensorOrientation.setText(sensor_error);
  124.         }
  125.  
  126.         mChartGyro = createChart(R.id.chart_gyroscope, mChartGyro, -10, 10);
  127.         mChartAccel = createChart(R.id.chart_accelerometer, mChartAccel, -10, 10);
  128.         mChartMagneto = createChart(R.id.chart_magnetometer, mChartMagneto, -100, 100);
  129.  
  130.         feedMultiple();
  131.  
  132.         // get IDs of buttons
  133.         startButton = findViewById(R.id.startButton);
  134.         stopButton = findViewById(R.id.stopButton);
  135.         context = this.getApplicationContext();
  136.  
  137.         startButton.setOnClickListener(new View.OnClickListener() {
  138.             public void onClick(View v) {
  139.                 record = true;
  140.                 startButton.setEnabled(false);
  141.  
  142.                 /*
  143.                  * Datalogging part, create/check for file.
  144.                  * Very rough implementation, can possibly be improved.
  145.                  * */
  146.                 String currentTime = new SimpleDateFormat("HH.mm.ss", Locale.getDefault()).format(new Date());
  147.                 String pathName = context.getExternalFilesDir(null) + "/" + "AccelLog " + currentTime + ".csv";
  148.                 file = new File(pathName); // Create subfolder + text file
  149.  
  150.                 if(!file.exists()){
  151.                     try {
  152.                         file.createNewFile();
  153.                     } catch (IOException e) {
  154.                         e.printStackTrace();
  155.                         Log.v("fileDir ", "Not created");
  156.                     }
  157.                 }
  158.  
  159.                 if(file.exists()){
  160.                     Log.v("fileDir ", "Exists");
  161.                     Log.v("fileDir ", context.getExternalFilesDir(null)+ "***");
  162.                 }
  163.  
  164.  
  165.                 tv = (TextView)findViewById(R.id.text_view); // Show in app for debugging purposes. Can be removed if direct access to csv is possible
  166.  
  167.                 // End of datalogging part
  168.             }
  169.         });
  170.  
  171.         stopButton.setOnClickListener(new View.OnClickListener() {
  172.             public void onClick(View v) {
  173.                 record = false;
  174.                 startButton.setEnabled(true);
  175.             }
  176.         });
  177.     }
  178.  
  179.     @Override
  180.     protected void onStart(){
  181.         super.onStart();
  182.  
  183.         // Listener to retrieve data
  184.         if(mSensorAccelerometer != null){
  185.             mSensorManager.registerListener(this, mSensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
  186.         }
  187.         if(mSensorGyroscope != null) {
  188.             mSensorManager.registerListener(this, mSensorGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
  189.         }
  190.         if(mSensorMagnetometer != null){
  191.             mSensorManager.registerListener(this, mSensorMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);
  192.         }
  193.         if(mSensorOrientation != null){
  194.             mSensorManager.registerListener(this, mSensorOrientation, SensorManager.SENSOR_DELAY_NORMAL);
  195.         }
  196.     }
  197.  
  198.     @Override
  199.     protected void onStop(){
  200.         super.onStop();
  201.         mSensorManager.unregisterListener(this); // Remove Listener
  202.     }
  203.  
  204.     @Override
  205.     public void onSensorChanged(SensorEvent event) {
  206.         int sensorType = event.sensor.getType();
  207.  
  208.         switch (sensorType){
  209.             case Sensor.TYPE_LINEAR_ACCELERATION :
  210.                 firstValue = event.values[0];
  211.                 secondValue = event.values[1];
  212.                 thirdValue = event.values[2];
  213.                 mTextSensorAccelerometer.setText(getResources().getString(R.string.label_accelerometer, firstValue, secondValue, thirdValue)); // Set the text in the app
  214.                 addEntry(event, mChartAccel);
  215.  
  216.                 /*
  217.                  *  BELOW
  218.                  *  Writing to AccelLog.csv
  219.                  *  Very rough implementation, can possibly be improved.
  220.                  * */
  221.                 if (record == true) {
  222.  
  223.                     mDatabase.child("X").setValue(firstValue);
  224.                     mDatabase.child("Y").setValue(secondValue);
  225.                     mDatabase.child("Z").setValue(thirdValue);
  226.  
  227.                     /*
  228.                     if (file.exists()) {
  229.                         try {
  230.                             FileWriter fileWriter = new FileWriter(file, true);
  231.  
  232.                             //String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
  233.  
  234.                             fileWriter.append("X,Y,Z,Compass,Time\n");
  235.                             fileWriter.append(String.format("%.2f", firstValue));
  236.                             fileWriter.append(',');
  237.                             fileWriter.append(String.format("%.2f", secondValue));
  238.                             fileWriter.append(',');
  239.                             fileWriter.append(String.format("%.2f", thirdValue));
  240.                             fileWriter.append(',');
  241.                             //fileWriter.append(currentTime);
  242.                             //fileWriter.append("\n");
  243.  
  244.                             fileWriter.flush();
  245.                             fileWriter.close();
  246.                         } catch (IOException e) {
  247.                             e.printStackTrace();
  248.                         }
  249.                     }
  250.                     */
  251.                 }
  252.  
  253.                 break;
  254.  
  255.             case Sensor.TYPE_GYROSCOPE :
  256.                 firstValue = event.values[0];
  257.                 secondValue = event.values[1];
  258.                 thirdValue = event.values[2];
  259.                 //mTextSensorGyroscope.setText(getResources().getString(R.string.label_gyroscope, firstValue, secondValue, thirdValue));
  260.                 addEntry(event, mChartGyro);
  261.  
  262.                 break;
  263.  
  264.             case Sensor.TYPE_MAGNETIC_FIELD_UNCALIBRATED:
  265.                 firstValue = event.values[0];
  266.                 secondValue = event.values[1];
  267.                 thirdValue = event.values[2];
  268.                 addEntry(event, mChartMagneto);
  269.  
  270.                 break;
  271.  
  272.             case Sensor.TYPE_ORIENTATION:
  273.                 firstValue = Math.round(event.values[0]);
  274.                 mTextSensorOrientation.setText("Compass : " + Float.toString(firstValue) + (char) 0x00B0);
  275.  
  276.                 if (record == true) {
  277.  
  278.                     mDatabase.child("compass").setValue(firstValue);
  279.  
  280.  
  281.                     /*
  282.                     if (file.exists()) {
  283.                         try {
  284.                             FileWriter fileWriter = new FileWriter(file, true);
  285.  
  286.                             String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());
  287.  
  288.                             //fileWriter.append("X    Y   Z   Time\n");
  289.                             fileWriter.append(String.format("%.2f", firstValue));
  290.                             fileWriter.append(',');
  291.                             fileWriter.append(currentTime);
  292.                             fileWriter.append("\n");
  293.  
  294.                             fileWriter.flush();
  295.                             fileWriter.close();
  296.                         } catch (IOException e) {
  297.                             e.printStackTrace();
  298.                         }
  299.                     }
  300.                     */
  301.                 }
  302.  
  303.                 break;
  304.  
  305.  
  306.             default :
  307.                 break;
  308.  
  309.         }
  310.  
  311.     }
  312.  
  313.     private void addEntry(SensorEvent event, LineChart chart) {
  314.  
  315.         LineData data = chart.getData();
  316.  
  317.         if (data != null) {
  318.  
  319.             ILineDataSet setX = data.getDataSetByIndex(0);
  320.             ILineDataSet setY = data.getDataSetByIndex(1);
  321.             ILineDataSet setZ = data.getDataSetByIndex(2);
  322.             // set.addEntry(...); // can be called as well
  323.  
  324.             if (setX == null) {
  325.                 setX = createSet(Color.RED, "X");
  326.                 data.addDataSet(setX);
  327.             }
  328.             if (setY == null) {
  329.                 setY = createSet(Color.GREEN, "Y");
  330.                 data.addDataSet(setY);
  331.             }
  332.             if (setZ == null) {
  333.                 setZ = createSet(Color.BLUE, "Z");
  334.                 data.addDataSet(setZ);
  335.             }
  336.  
  337.             //data.addEntry(new Entry(set.getEntryCount(), (float) (Math.random() * 80) + 10f), 0);
  338.             data.addEntry(new Entry(setX.getEntryCount(), event.values[0]), 0);
  339.             data.addEntry(new Entry(setY.getEntryCount(), event.values[1]), 1);
  340.             data.addEntry(new Entry(setZ.getEntryCount(), event.values[2]), 2);
  341.             data.notifyDataChanged();
  342.  
  343.             // let the chart know it's data has changed
  344.             chart.notifyDataSetChanged();
  345.  
  346.             // limit the number of visible entries
  347.             chart.setVisibleXRangeMaximum(150);
  348.             // mChart.setVisibleYRange(30, AxisDependency.LEFT);
  349.  
  350.             // move to the latest entry
  351.             chart.moveViewToX(data.getEntryCount());
  352.  
  353.         }
  354.     }
  355.  
  356.     private LineDataSet createSet(int colorID, String label) {
  357.  
  358.         LineDataSet set = new LineDataSet(null, label);
  359.         //set.setLabel(label);
  360.         set.setAxisDependency(YAxis.AxisDependency.LEFT);
  361.         set.setLineWidth(3f);
  362.         set.setColor(colorID);
  363.         set.setHighlightEnabled(false);
  364.         set.setDrawValues(false);
  365.         set.setDrawCircles(false);
  366.         set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
  367.         set.setCubicIntensity(0.2f);
  368.         return set;
  369.     }
  370.  
  371.     private void feedMultiple() {
  372.  
  373.         if (thread != null){
  374.             thread.interrupt();
  375.         }
  376.  
  377.         thread = new Thread(new Runnable() {
  378.  
  379.             @Override
  380.             public void run() {
  381.                 while (true){
  382.                     plotData = true;
  383.                     try {
  384.                         Thread.sleep(10);
  385.                     } catch (InterruptedException e) {
  386.                         // TODO Auto-generated catch block
  387.                         e.printStackTrace();
  388.                     }
  389.                 }
  390.             }
  391.         });
  392.  
  393.         thread.start();
  394.     }
  395.  
  396.     protected void onPause() {
  397.         super.onPause();
  398.  
  399.         if (thread != null) {
  400.             thread.interrupt();
  401.         }
  402.         mSensorManager.unregisterListener(this);
  403.  
  404.     }
  405.  
  406.     @Override
  407.     protected void onResume() {
  408.         super.onResume();
  409.         mSensorManager.registerListener(this, mSensorAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
  410.         mSensorManager.registerListener(this, mSensorGyroscope, SensorManager.SENSOR_DELAY_NORMAL);
  411.         mSensorManager.registerListener(this, mSensorMagnetometer, SensorManager.SENSOR_DELAY_NORMAL);
  412.     }
  413.  
  414.     @Override
  415.     protected void onDestroy() {
  416.         mSensorManager.unregisterListener(MainActivity.this);
  417.         thread.interrupt();
  418.         super.onDestroy();
  419.     }
  420.  
  421.     private LineChart createChart(int viewID, LineChart mChart, float YMin, float YMax){
  422.  
  423.         mChart = (LineChart) findViewById(viewID);
  424.  
  425.         mChart.getDescription().setEnabled(true); // Enable description text
  426.         mChart.getDescription().setText("Gyroscope measurements in radians");
  427.         mChart.getDescription().setTextSize(12f);
  428.  
  429.         mChart.setTouchEnabled(true); // Enable touch gestures
  430.  
  431.         mChart.setDragEnabled(true); // Enable scaling and dragging
  432.         mChart.setScaleEnabled(true);
  433.         mChart.setDrawGridBackground(true);
  434.  
  435.         mChart.setPinchZoom(true); // If disabled, scaling can be done on x- and y-axis separately
  436.         mChart.setBackgroundColor(Color.WHITE); // Set an alternative background color
  437.  
  438.         LineData data = new LineData();
  439.         data.setValueTextColor(Color.BLACK);
  440.  
  441.         // add empty data
  442.         mChart.setData(data);
  443.  
  444.         // get the legend (only possible after setting data)
  445.         Legend l = mChart.getLegend();
  446.  
  447.         // modify the legend ...
  448.         l.setForm(Legend.LegendForm.LINE);
  449.         l.setTextColor(Color.BLACK);
  450.  
  451.         XAxis xl = mChart.getXAxis();
  452.         xl.setTextColor(Color.WHITE);
  453.         xl.setDrawGridLines(false);
  454.         xl.setAvoidFirstLastClipping(true);
  455.         xl.setEnabled(true);
  456.  
  457.         YAxis rightAxis = mChart.getAxisRight();
  458.         rightAxis.setTextColor(Color.BLACK);
  459.         rightAxis.setDrawGridLines(true);
  460.         rightAxis.setAxisMaximum(YMax);
  461.         rightAxis.setAxisMinimum(YMin);
  462.         rightAxis.setDrawGridLines(true);
  463.  
  464.         YAxis leftAxis = mChart.getAxisLeft();
  465.         leftAxis.setTextColor(Color.BLACK);
  466.         leftAxis.setDrawGridLines(true);
  467.         leftAxis.setAxisMaximum(YMax);
  468.         leftAxis.setAxisMinimum(YMin);
  469.         leftAxis.setDrawGridLines(true);
  470.  
  471.         mChart.getAxisRight().setDrawGridLines(false);
  472.         mChart.getXAxis().setDrawGridLines(false);
  473.         mChart.setDrawBorders(true);
  474.  
  475.         return mChart;
  476.     }
  477.  
  478.  
  479.     @Override
  480.     public void onAccuracyChanged(Sensor sensor, int accuracy) {
  481.  
  482.     }
  483.  
  484.     @Override
  485.     public void onPointerCaptureChanged(boolean hasCapture) {
  486.  
  487.     }
  488.  
  489.  
  490. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement