diff --git a/app/build.gradle b/app/build.gradle index d415cc1f6..9cc765e86 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -8,8 +8,8 @@ android { applicationId "io.pslab" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 16 - versionName "2.0.15" + versionCode 17 + versionName "2.0.16" multiDexEnabled true testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } diff --git a/app/src/main/java/io/pslab/activity/AccelerometerActivity.java b/app/src/main/java/io/pslab/activity/AccelerometerActivity.java index 2047c2af6..243d5fd54 100644 --- a/app/src/main/java/io/pslab/activity/AccelerometerActivity.java +++ b/app/src/main/java/io/pslab/activity/AccelerometerActivity.java @@ -115,19 +115,8 @@ private void reinstateConfigurations() { accelerometerConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); locationEnabled = accelerometerConfigurations.getBoolean(AccelerometerSettingsFragment.KEY_INCLUDE_LOCATION, true); AccelerometerDataFragment.setParameters( - getValueFromText(accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_HIGH_LIMIT, "2000"), - 10, 10000), - getValueFromText(accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_UPDATE_PERIOD, "1000"), - 100, 1000), - accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_ACCELEROMETER_SENSOR_TYPE, "0"), + Float.valueOf(accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_HIGH_LIMIT, "20")), + Integer.valueOf(accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_UPDATE_PERIOD, "1000")), accelerometerConfigurations.getString(AccelerometerSettingsFragment.KEY_ACCELEROMETER_SENSOR_GAIN, "1")); } - - private int getValueFromText(String strValue, int lowerBound, int upperBound) { - if (strValue.isEmpty()) return lowerBound; - int value = Integer.parseInt(strValue); - if (value > upperBound) return upperBound; - else if (value < lowerBound) return lowerBound; - else return value; - } } \ No newline at end of file diff --git a/app/src/main/java/io/pslab/activity/GyroscopeActivity.java b/app/src/main/java/io/pslab/activity/GyroscopeActivity.java index ef03eb09f..c953cd3f6 100644 --- a/app/src/main/java/io/pslab/activity/GyroscopeActivity.java +++ b/app/src/main/java/io/pslab/activity/GyroscopeActivity.java @@ -107,12 +107,12 @@ protected void onResume() { } private void reinstateConfigurations() { - SharedPreferences accelerometerConfigurations; - accelerometerConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); - locationEnabled = accelerometerConfigurations.getBoolean(GyroscopeSettingsFragment.KEY_INCLUDE_LOCATION, true); + SharedPreferences gyroscopeConfigurations; + gyroscopeConfigurations = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); + locationEnabled = gyroscopeConfigurations.getBoolean(GyroscopeSettingsFragment.KEY_INCLUDE_LOCATION, true); GyroscopeDataFragment.setParameters( - Float.valueOf(accelerometerConfigurations.getString(GyroscopeSettingsFragment.KEY_HIGH_LIMIT, "20")), - Integer.valueOf(accelerometerConfigurations.getString(GyroscopeSettingsFragment.KEY_UPDATE_PERIOD, "1000")), - accelerometerConfigurations.getString(GyroscopeSettingsFragment.KEY_GYROSCOPE_SENSOR_GAIN, "1")); + Float.valueOf(gyroscopeConfigurations.getString(GyroscopeSettingsFragment.KEY_HIGH_LIMIT, "20")), + Integer.valueOf(gyroscopeConfigurations.getString(GyroscopeSettingsFragment.KEY_UPDATE_PERIOD, "1000")), + gyroscopeConfigurations.getString(GyroscopeSettingsFragment.KEY_GYROSCOPE_SENSOR_GAIN, "1")); } } diff --git a/app/src/main/java/io/pslab/activity/OscilloscopeActivity.java b/app/src/main/java/io/pslab/activity/OscilloscopeActivity.java index ddc9922f4..8b63a4975 100644 --- a/app/src/main/java/io/pslab/activity/OscilloscopeActivity.java +++ b/app/src/main/java/io/pslab/activity/OscilloscopeActivity.java @@ -111,12 +111,12 @@ public class OscilloscopeActivity extends AppCompatActivity implements View.OnCl public boolean isCH3Selected; public boolean isMICSelected; public boolean isInBuiltMicSelected; + public boolean isAudioInputSelected; public boolean isTriggerSelected; public boolean isFourierTransformSelected; public boolean isXYPlotSelected; public boolean sineFit; public boolean squareFit; - public boolean viewIsClicked; public boolean isCH1FrequencyRequired; public boolean isCH2FrequencyRequired; public String triggerChannel; @@ -171,14 +171,10 @@ public class OscilloscopeActivity extends AppCompatActivity implements View.OnCl private XAxis x1; private YAxis y1; private YAxis y2; - private CaptureTask captureTask; - private CaptureTaskTwo captureTask2; - private CaptureTaskThree captureTask3; private XYPlotTask xyPlotTask; private AudioJack audioJack = null; private AnalyticsClass analyticsClass; - private CaptureAudioBuffer captureAudioBuffer; - private CaptureAudioBufferTwo captureAudioBufferTwo; + private CaptureTask captureTask; private Thread monitorThread; private volatile boolean monitor = true; private BottomSheetBehavior bottomSheetBehavior; @@ -196,8 +192,6 @@ public class OscilloscopeActivity extends AppCompatActivity implements View.OnCl private long recordPeriod = 100; private String oscilloscopeCSVHeader = "Timestamp,DateTime,Channel,xData,yData,Timebase,lat,lon"; private String loggingXdata = ""; - private String loggingYdata1 = ""; - private String loggingYdata2 = ""; private final String KEY_LOG = "has_log"; private final String DATA_BLOCK = "data_block"; private int currentPosition = 0; @@ -206,6 +200,11 @@ public class OscilloscopeActivity extends AppCompatActivity implements View.OnCl private double lat; private double lon; public boolean isPlaybackFourierChecked = false; + private HashMap channelIndexMap; + private Integer[] channelColors = {Color.CYAN, Color.GREEN, Color.WHITE, Color.MAGENTA}; + private String[] loggingYdata = new String[4]; + public String xyPlotAxis1 = "CH1"; + public String xyPlotAxis2 = "CH2"; private enum CHANNEL {CH1, CH2, CH3, MIC} @@ -230,6 +229,12 @@ public void onClick(View v) { }); mainLayout = findViewById(R.id.oscilloscope_mail_layout); + channelIndexMap = new HashMap<>(); + channelIndexMap.put(CHANNEL.CH1.toString(), 0); + channelIndexMap.put(CHANNEL.CH2.toString(), 1); + channelIndexMap.put(CHANNEL.CH3.toString(), 2); + channelIndexMap.put(CHANNEL.MIC.toString(), 3); + realm = LocalDataLog.with().getRealm(); gpsLogger = new GPSLogger(this, (LocationManager) getSystemService(Context.LOCATION_SERVICE)); @@ -253,7 +258,6 @@ public void onClick(View v) { curveFittingChannel2 = "None"; xyPlotXAxisChannel = CHANNEL.CH1.toString(); xyPlotYAxisChannel = CHANNEL.CH2.toString(); - viewIsClicked = false; analyticsClass = new AnalyticsClass(); isCH1FrequencyRequired = false; isCH2FrequencyRequired = false; @@ -293,7 +297,11 @@ public void onClick(View v) { public void run() { //Thread to check which checkbox is enabled while (monitor) { - if (scienceLab.isConnected() && isCH1Selected && !isCH2Selected && !isCH3Selected && !isMICSelected && !isXYPlotSelected && !isFourierTransformSelected && !isInBuiltMicSelected) { + if (isInBuiltMicSelected && audioJack == null) { + audioJack = new AudioJack("input"); + } + + if (scienceLab.isConnected() && isCH1Selected && !isCH2Selected && !isCH3Selected && !isAudioInputSelected && !isXYPlotSelected) { captureTask = new CaptureTask(); captureTask.execute(CHANNEL.CH1.toString()); synchronized (lock) { @@ -305,7 +313,7 @@ public void run() { } } - if (scienceLab.isConnected() && isCH2Selected && !isCH1Selected && !isCH3Selected && !isMICSelected && !isXYPlotSelected && !isFourierTransformSelected && !isInBuiltMicSelected) { + if (scienceLab.isConnected() && isCH2Selected && !isCH1Selected && !isCH3Selected && !isAudioInputSelected && !isXYPlotSelected) { captureTask = new CaptureTask(); captureTask.execute(CHANNEL.CH2.toString()); synchronized (lock) { @@ -317,7 +325,7 @@ public void run() { } } - if (scienceLab.isConnected() && isCH3Selected && !isCH1Selected && !isCH2Selected && !isMICSelected && !isXYPlotSelected && !isFourierTransformSelected && !isInBuiltMicSelected) { + if (scienceLab.isConnected() && isCH3Selected && !isCH1Selected && !isCH2Selected && !isAudioInputSelected && !isXYPlotSelected) { captureTask = new CaptureTask(); captureTask.execute(CHANNEL.CH3.toString()); synchronized (lock) { @@ -329,7 +337,7 @@ public void run() { } } - if (scienceLab.isConnected() && isMICSelected && !isCH1Selected && !isCH2Selected && !isCH3Selected && !isXYPlotSelected && !isFourierTransformSelected && !isInBuiltMicSelected) { + if (scienceLab.isConnected() && isAudioInputSelected && !isCH1Selected && !isCH2Selected && !isCH3Selected && !isXYPlotSelected) { captureTask = new CaptureTask(); captureTask.execute(CHANNEL.MIC.toString()); synchronized (lock) { @@ -341,9 +349,9 @@ public void run() { } } - if (scienceLab.isConnected() && isCH1Selected && isCH2Selected && !isCH3Selected && !isMICSelected && !isXYPlotSelected && !isFourierTransformSelected && !isInBuiltMicSelected) { - captureTask2 = new CaptureTaskTwo(); - captureTask2.execute(CHANNEL.CH1.toString(), CHANNEL.CH2.toString()); + if (scienceLab.isConnected() && isCH1Selected && isCH2Selected && !isCH3Selected && !isAudioInputSelected && !isXYPlotSelected) { + captureTask = new CaptureTask(); + captureTask.execute(CHANNEL.CH1.toString(), CHANNEL.CH2.toString()); synchronized (lock) { try { lock.wait(); @@ -353,9 +361,9 @@ public void run() { } } - if (scienceLab.isConnected() && isCH3Selected && isCH2Selected && !isCH1Selected && !isMICSelected && !isXYPlotSelected && !isFourierTransformSelected && !isInBuiltMicSelected) { - captureTask2 = new CaptureTaskTwo(); - captureTask2.execute(CHANNEL.CH1.toString(), CHANNEL.CH3.toString()); + if (scienceLab.isConnected() && isCH1Selected && !isCH2Selected && isCH3Selected && !isAudioInputSelected && !isXYPlotSelected) { + captureTask = new CaptureTask(); + captureTask.execute(CHANNEL.CH1.toString(), CHANNEL.CH3.toString()); synchronized (lock) { try { lock.wait(); @@ -365,9 +373,9 @@ public void run() { } } - if (scienceLab.isConnected() && isMICSelected && isCH2Selected && !isCH3Selected && !isCH1Selected && !isXYPlotSelected && !isFourierTransformSelected && !isInBuiltMicSelected) { - captureTask2 = new CaptureTaskTwo(); - captureTask2.execute(CHANNEL.CH1.toString(), CHANNEL.MIC.toString()); + if (scienceLab.isConnected() && isAudioInputSelected && isCH1Selected && !isCH3Selected && !isCH2Selected && !isXYPlotSelected) { + captureTask = new CaptureTask(); + captureTask.execute(CHANNEL.CH1.toString(), CHANNEL.MIC.toString()); synchronized (lock) { try { lock.wait(); @@ -377,9 +385,9 @@ public void run() { } } - if (scienceLab.isConnected() && isCH2Selected && isCH3Selected && !isCH1Selected && !isMICSelected && !isXYPlotSelected && !isInBuiltMicSelected) { - captureTask2 = new CaptureTaskTwo(); - captureTask2.execute(CHANNEL.CH2.toString(), CHANNEL.CH3.toString()); + if (scienceLab.isConnected() && isCH2Selected && isCH3Selected && !isCH1Selected && !isAudioInputSelected && !isXYPlotSelected) { + captureTask = new CaptureTask(); + captureTask.execute(CHANNEL.CH2.toString(), CHANNEL.CH3.toString()); synchronized (lock) { try { lock.wait(); @@ -389,9 +397,9 @@ public void run() { } } - if (scienceLab.isConnected() && isCH2Selected && isMICSelected && !isCH3Selected && !isCH1Selected && !isXYPlotSelected && !isInBuiltMicSelected) { - captureTask2 = new CaptureTaskTwo(); - captureTask2.execute(CHANNEL.CH2.toString(), CHANNEL.MIC.toString()); + if (scienceLab.isConnected() && isCH2Selected && isAudioInputSelected && !isCH3Selected && !isCH1Selected && !isXYPlotSelected) { + captureTask = new CaptureTask(); + captureTask.execute(CHANNEL.CH2.toString(), CHANNEL.MIC.toString()); synchronized (lock) { try { lock.wait(); @@ -401,9 +409,9 @@ public void run() { } } - if (scienceLab.isConnected() && isCH1Selected && isCH2Selected && isCH3Selected && isMICSelected && !isXYPlotSelected && !isFourierTransformSelected && !isInBuiltMicSelected) { - captureTask3 = new CaptureTaskThree(); - captureTask3.execute(CHANNEL.CH1.toString()); + if (scienceLab.isConnected() && isCH3Selected && isAudioInputSelected && !isCH2Selected && !isCH1Selected && !isXYPlotSelected) { + captureTask = new CaptureTask(); + captureTask.execute(CHANNEL.CH3.toString(), CHANNEL.MIC.toString()); synchronized (lock) { try { lock.wait(); @@ -413,7 +421,30 @@ public void run() { } } - if (!scienceLab.isConnected() || (!isCH1Selected && !isCH2Selected && !isCH3Selected && !isMICSelected)) { + if (scienceLab.isConnected() && isCH1Selected && isCH2Selected && isCH3Selected && !isAudioInputSelected && !isXYPlotSelected) { + captureTask = new CaptureTask(); + captureTask.execute(CHANNEL.CH1.toString(), CHANNEL.CH2.toString(), CHANNEL.CH3.toString()); + synchronized (lock) { + try { + lock.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + if (scienceLab.isConnected() && isCH1Selected && isCH2Selected && isCH3Selected && isAudioInputSelected && !isXYPlotSelected) { + captureTask = new CaptureTask(); + captureTask.execute(CHANNEL.CH1.toString(), CHANNEL.CH2.toString(), CHANNEL.CH3.toString(), CHANNEL.MIC.toString()); + synchronized (lock) { + try { + lock.wait(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + if (!scienceLab.isConnected() || (!isCH1Selected && !isCH2Selected && !isCH3Selected && !isAudioInputSelected)) { if (!String.valueOf(ledImageView.getTag()).equals("red")) { runOnUiThread(new Runnable() { @Override @@ -425,12 +456,9 @@ public void run() { } } - if (scienceLab.isConnected() && viewIsClicked && isXYPlotSelected) { + if (scienceLab.isConnected() && isXYPlotSelected) { xyPlotTask = new XYPlotTask(); - if (xyPlotXAxisChannel.equals(CHANNEL.CH2.toString())) - xyPlotTask.execute(xyPlotYAxisChannel); - else - xyPlotTask.execute(xyPlotXAxisChannel); + xyPlotTask.execute(xyPlotAxis1, xyPlotAxis2); synchronized (lock) { try { lock.wait(); @@ -440,88 +468,10 @@ public void run() { } } - if (scienceLab.isConnected() && isFourierTransformSelected) { - if (isCH1Selected && !isCH2Selected) { - new FFTTask().execute(CHANNEL.CH1.toString()); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } else if (!isCH1Selected && isCH2Selected) { - new FFTTask().execute(CHANNEL.CH2.toString()); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } else if (isCH1Selected && isCH2Selected) { - new FFTTaskTwo().execute(CHANNEL.CH1.toString(), CHANNEL.CH2.toString()); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } - - if (isInBuiltMicSelected) { - if (audioJack == null) - audioJack = new AudioJack("input"); - if (!isCH1Selected && !isCH2Selected && !isCH3Selected) { - captureAudioBuffer = new CaptureAudioBuffer(audioJack); - captureAudioBuffer.execute(); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } else if (isCH1Selected && !isCH2Selected && !isCH3Selected) { - captureAudioBufferTwo = new CaptureAudioBufferTwo(audioJack, CHANNEL.CH1.toString()); - captureAudioBufferTwo.execute(); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } else if (!isCH1Selected && isCH2Selected && !isCH3Selected) { - captureAudioBufferTwo = new CaptureAudioBufferTwo(audioJack, CHANNEL.CH2.toString()); - captureAudioBufferTwo.execute(); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } else if (!isCH1Selected && !isCH2Selected && isCH3Selected) { - captureAudioBufferTwo = new CaptureAudioBufferTwo(audioJack, CHANNEL.CH3.toString()); - captureAudioBufferTwo.execute(); - synchronized (lock) { - try { - lock.wait(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - } else { - if (audioJack != null) { - audioJack.release(); - audioJack = null; - } + if (!isInBuiltMicSelected && audioJack != null) { + audioJack.release(); + audioJack = null; } - } } }; @@ -635,17 +585,19 @@ public void run() { try { if (currentPosition < recordedOscilloscopeData.size()) { OscilloscopeData data = recordedOscilloscopeData.get(currentPosition); - if (data.getMode() == 1) { - currentPosition += 1; - ArrayList entries = new ArrayList<>(); + int mode = data.getMode(); + List dataSets = new ArrayList<>(); + ArrayList> entries = new ArrayList<>(); + for (int i = 0; i < mode; i++) { + data = recordedOscilloscopeData.get(currentPosition); + entries.add(new ArrayList<>()); String[] xData = data.getDataX().split(" "); String[] yData = data.getDataY().split(" "); - if (!isPlaybackFourierChecked) { int n = Math.min(xData.length, yData.length); - for (int i = 0; i < n; i++) { - if (xData[i].length() > 0 && yData[i].length() > 0) { - entries.add(new Entry(Float.valueOf(xData[i]), Float.valueOf(yData[i]))); + for (int j = 0; j < n; j++) { + if (xData[j].length() > 0 && yData[j].length() > 0) { + entries.get(i).add(new Entry(Float.valueOf(xData[j]), Float.valueOf(yData[j]))); } } setLeftYAxisScale(16f, -16f); @@ -653,104 +605,37 @@ public void run() { setXAxisScale(data.getTimebase()); } else { Complex[] yComplex = new Complex[yData.length]; - for (int i = 0; i < yData.length; i++) { - yComplex[i] = Complex.valueOf(Double.valueOf(yData[i])); + for (int j = 0; j < yData.length; j++) { + yComplex[j] = Complex.valueOf(Double.valueOf(yData[j])); } Complex[] fftOut = fft(yComplex); int n = fftOut.length; double mA = 0; double factor = samples * timeGap * 1e-3; double mF = (n / 2 - 1) / factor; - for (int i = 0; i < n / 2; i++) { - float y = (float) fftOut[i].abs() / samples; + for (int j = 0; j < n / 2; j++) { + float y = (float) fftOut[j].abs() / samples; if (y > mA) { mA = y; } - entries.add(new Entry((float) (i / factor), y)); + entries.get(i).add(new Entry((float) (j / factor), y)); } setLeftYAxisScale(mA, 0); setRightYAxisScale(mA, 0); setXAxisScale(mF); } - LineDataSet dataSet = new LineDataSet(entries, data.getChannel()); - LineData lineData = new LineData(dataSet); + currentPosition++; + LineDataSet dataSet; + dataSet = new LineDataSet(entries.get(i), data.getChannel()); dataSet.setDrawCircles(false); - mChart.setData(lineData); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - - ((OscilloscopePlaybackFragment) playbackFragment).setTimeBase(String.valueOf(data.getTimebase())); - } else if (data.getMode() == 2) { - OscilloscopeData data2 = recordedOscilloscopeData.get(currentPosition + 1); - currentPosition += 2; - ArrayList entries1 = new ArrayList<>(); - ArrayList entries2 = new ArrayList<>(); - String[] xData = data.getDataX().split(" "); - String[] yData1 = data.getDataY().split(" "); - String[] yData2 = data2.getDataY().split(" "); - - if (!isPlaybackFourierChecked) { - int n = Math.min(xData.length, Math.min(yData1.length, yData2.length)); - for (int i = 0; i < n; i++) { - if (xData[i].length() > 0 && yData1[i].length() > 0 && yData2[i].length() > 0) { - entries1.add(new Entry(Float.valueOf(xData[i]), Float.valueOf(yData1[i]))); - entries2.add(new Entry(Float.valueOf(xData[i]), Float.valueOf(yData2[i]))); - } - } - - setLeftYAxisScale(16f, -16f); - setRightYAxisScale(16f, -16f); - setXAxisScale(data.getTimebase()); - } else { - Complex[] yComplex1 = new Complex[yData1.length]; - Complex[] yComplex2 = new Complex[yData2.length]; - for (int i = 0; i < Math.min(yData1.length, yData2.length); i++) { - yComplex1[i] = Complex.valueOf(Double.valueOf(yData1[i])); - yComplex2[i] = Complex.valueOf(Double.valueOf(yData2[i])); - } - Complex[] fftOut1 = fft(yComplex1); - Complex[] fftOut2 = fft(yComplex2); - int n = Math.min(fftOut1.length, fftOut2.length); - double mA = 0; - - float maxAmp1 = 0; - float maxAmp2 = 0; - double factor = samples * timeGap * 1e-3; - double mF = (n / 2 - 1) / factor; - for (int i = 0; i < n / 2; i++) { - float y1 = (float) fftOut1[i].abs() / samples; - if (y1 > maxAmp1) { - maxAmp1 = y1; - } - entries1.add(new Entry((float) (i / factor), y1)); - float y2 = (float) fftOut2[i].abs() / samples; - if (y2 > maxAmp2) { - maxAmp2 = y2; - } - entries2.add(new Entry((float) (i / factor), y2)); - } - mA = Math.max(maxAmp1, maxAmp2); - setXAxisScale(mF); - setLeftYAxisScale(mA, 0); - setRightYAxisScale(mA, 0); - } - LineDataSet dataSet1 = new LineDataSet(entries1, data.getChannel()); - LineDataSet dataSet2 = new LineDataSet(entries2, data2.getChannel()); - dataSet1.setDrawCircles(false); - dataSet2.setDrawCircles(false); - dataSet2.setColor(Color.GREEN); - dataSet2.setDrawCircles(false); - List dataSets = new ArrayList<>(); - dataSets.add(dataSet1); - dataSets.add(dataSet2); - - LineData lineData = new LineData(dataSets); - mChart.setData(lineData); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - + dataSet.setColor(channelColors[i]); + dataSets.add(dataSet); ((OscilloscopePlaybackFragment) playbackFragment).setTimeBase(String.valueOf(data.getTimebase())); } + LineData lineData = new LineData(dataSets); + mChart.setData(lineData); + mChart.notifyDataSetChanged(); + mChart.invalidate(); } else { playbackTimer.cancel(); playbackTimer = null; @@ -758,8 +643,10 @@ public void run() { currentPosition = 0; } } catch (Exception e) { - playbackTimer.cancel(); - playbackTimer = null; + if (playbackTimer != null) { + playbackTimer.cancel(); + playbackTimer = null; + } ((OscilloscopePlaybackFragment) playbackFragment).resetPlayButton(); currentPosition = 0; } @@ -775,27 +662,14 @@ public void pauseData() { playbackTimer = null; } - private void logSingleChannelData(String channel) { + private void logChannelData(String[] channels) { long timestamp = System.currentTimeMillis(); - if (loggingXdata.length() > 0 && loggingYdata1.length() > 0) { - recordSensorData(new OscilloscopeData(timestamp, block, 1, channel, loggingXdata, loggingYdata1, xAxisScale, lat, lon)); - String timeData = timestamp + "," + CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - String locationData = lat + "," + lon; - String data = timeData + "," + channel + "," + loggingXdata + "," + loggingYdata1 + "," + xAxisScale + "," + locationData; - csvLogger.writeCSVFile(data); - } - } - - private void logTwoChannelData(String channel1, String channel2) { - long timestamp = System.currentTimeMillis(); - if (loggingXdata.length() > 0 && loggingYdata1.length() > 0 && loggingYdata2.length() > 0) { - recordSensorData(new OscilloscopeData(timestamp, block, 2, channel1, loggingXdata, loggingYdata1, xAxisScale, lat, lon)); - recordSensorData(new OscilloscopeData(timestamp + 1, block, 2, channel2, loggingXdata, loggingYdata2, xAxisScale, lat, lon)); - String timeData = timestamp + "," + CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); - String locationData = lat + "," + lon; - String data = timeData + "," + channel1 + "," + loggingXdata + "," + loggingYdata1 + "," + xAxisScale + "," + locationData; - csvLogger.writeCSVFile(data); - data = timeData + "," + channel2 + "," + loggingXdata + "," + loggingYdata2 + "," + xAxisScale + "," + locationData; + int noOfChannels = channels.length; + String timeData = timestamp + "," + CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); + String locationData = lat + "," + lon; + for (int i = 0; i < noOfChannels; i++) { + recordSensorData(new OscilloscopeData(timestamp + i, block, noOfChannels, channels[i], loggingXdata, loggingYdata[i], xAxisScale, lat, lon)); + String data = timeData + "," + channels[i] + "," + loggingXdata + "," + loggingYdata[i] + "," + xAxisScale + "," + locationData; csvLogger.writeCSVFile(data); } } @@ -911,22 +785,14 @@ protected void onDestroy() { if (captureTask != null) { captureTask.cancel(true); } - if (captureTask2 != null) { - captureTask2.cancel(true); - } - if (captureTask3 != null) { - captureTask3.cancel(true); - } - if (captureAudioBuffer != null) { - captureAudioBuffer.cancel(true); - if (audioJack != null) { - audioJack.release(); - } - } if (recordTimer != null) { recordTimer.cancel(); recordTimer = null; } + if (audioJack != null) { + audioJack.release(); + audioJack = null; + } super.onDestroy(); } @@ -1074,141 +940,119 @@ public boolean onTouchEvent(MotionEvent event) { } public class CaptureTask extends AsyncTask { - ArrayList entries; - String analogInput; + private ArrayList> entries = new ArrayList<>(); + private Integer noOfChannels; + private String[] paramsChannels; @Override - protected Void doInBackground(String... params) { - try { - analogInput = params[0]; - if (isTriggerSelected) { - scienceLab.configureTrigger(0, analogInput, trigger, null, null); - } - // number of samples and timeGap still need to be determined - scienceLab.captureTraces(1, samples, timeGap, analogInput, isTriggerSelected, null); - Log.v("Sleep Time", "" + (1024 * 10 * 1e-3)); - Thread.sleep((long) (1000 * 10 * 1e-3)); - HashMap data = scienceLab.fetchTrace(1); //fetching data - - double[] xData = data.get("x"); - double[] yData = data.get("y"); - - String[] xString = new String[xData.length]; - String[] yString = new String[yData.length]; - entries = new ArrayList<>(); - for (int i = 0; i < xData.length; i++) { - xData[i] = xData[i] / ((timebase == 875) ? 1 : 1000); - entries.add(new Entry((float) xData[i], (float) yData[i])); - - xString[i] = String.valueOf(xData[i]); - yString[i] = String.valueOf(yData[i]); - } - - loggingXdata = String.join(" ", xString); - loggingYdata1 = String.join(" ", yString); - if (isRecording) { - runOnUiThread(new Runnable() { - @Override - public void run() { - logSingleChannelData(analogInput); - } - }); - } - - } catch (NullPointerException e) { - cancel(true); - } catch (InterruptedException e) { - e.printStackTrace(); + protected Void doInBackground(String... channels) { + paramsChannels = channels; + noOfChannels = channels.length; + if (isInBuiltMicSelected) { + noOfChannels--; } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (!String.valueOf(ledImageView.getTag()).equals("green")) { - ledImageView.setImageResource(R.drawable.green_led); - ledImageView.setTag("green"); - } - - setLeftYAxisScale(16f, -16f); - setRightYAxisScale(16f, -16f); - setXAxisScale(xAxisScale); - LineDataSet dataSet = new LineDataSet(entries, analogInput); - LineData lineData = new LineData(dataSet); - dataSet.setDrawCircles(false); - mChart.setData(lineData); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - - synchronized (lock) { - lock.notify(); - } - - } - } - - public class CaptureTaskTwo extends AsyncTask { - private ArrayList entries1; - private ArrayList entries2; - private String analogInput1, analogInput2; - - @Override - protected Void doInBackground(String... params) { try { - analogInput1 = params[0]; - analogInput2 = params[1]; - // number of samples and timeGap still need to be determined - HashMap data1; - HashMap data2; - if (isTriggerSelected && (triggerChannel.equals(analogInput1) || triggerChannel.equals(analogInput2))) { - if (triggerChannel.equals(analogInput1)) - scienceLab.configureTrigger(0, analogInput1, trigger, null, null); - else if (triggerChannel.equals(analogInput2)) - scienceLab.configureTrigger(1, analogInput2, trigger, null, null); - scienceLab.captureTraces(1, samples, timeGap, analogInput1, isTriggerSelected, null); - data1 = scienceLab.fetchTrace(1); //fetching data - Thread.sleep((long) (1000 * 10 * 1e-3)); - scienceLab.captureTraces(1, samples, timeGap, analogInput2, isTriggerSelected, null); - data2 = scienceLab.fetchTrace(1); - Thread.sleep((long) (1000 * 10 * 1e-3)); - - } else { - scienceLab.captureTraces(1, samples, timeGap, analogInput1, isTriggerSelected, null); - data1 = scienceLab.fetchTrace(1); //fetching data - Thread.sleep((long) (1000 * 10 * 1e-3)); - scienceLab.captureTraces(1, samples, timeGap, analogInput2, isTriggerSelected, null); - data2 = scienceLab.fetchTrace(1); + double[] xData; + double[] yData; + ArrayList yDataString = new ArrayList<>(); + String[] xDataString = null; + maxAmp = 0; + for (int i = 0; i < noOfChannels; i++) { + entries.add(new ArrayList<>()); + String channel = channels[i]; + HashMap data; + if (triggerChannel.equals(channel)) + scienceLab.configureTrigger(channelIndexMap.get(channel), channel, trigger, null, null); + scienceLab.captureTraces(1, samples, timeGap, channel, isTriggerSelected, null); + data = scienceLab.fetchTrace(1); Thread.sleep((long) (1000 * 10 * 1e-3)); + xData = data.get("x"); + yData = data.get("y"); + int n = Math.min(xData.length, yData.length); + xDataString = new String[n]; + yDataString.add(new String[n]); + Complex[] fftOut = null; + if (isFourierTransformSelected) { + Complex[] yComplex = new Complex[yData.length]; + for (int j = 0; j < yData.length; j++) { + yComplex[j] = Complex.valueOf(yData[j]); + } + fftOut = fft(yComplex); + } + double factor = samples * timeGap * 1e-3; + maxFreq = (n / 2 - 1) / factor; + double mA = 0; + for (int j = 0; j < n; j++) { + xData[j] = xData[j] / ((timebase == 875) ? 1 : 1000); + if (!isFourierTransformSelected) { + entries.get(i).add(new Entry((float) xData[j], (float) yData[j])); + } else { + if (j < n / 2) { + float y = (float) fftOut[j].abs() / samples; + if (y > mA) { + mA = y; + } + entries.get(i).add(new Entry((float) (j / factor), y)); + } + } + xDataString[j] = String.valueOf(xData[j]); + yDataString.get(i)[j] = String.valueOf(yData[j]); + } + if (mA > maxAmp) { + maxAmp = mA; + } } - double[] xData = data1.get("x"); - double[] y1Data = data1.get("y"); - double[] y2Data = data2.get("y"); - - entries1 = new ArrayList<>(); - entries2 = new ArrayList<>(); + if (isInBuiltMicSelected) { + noOfChannels++; + entries.add(new ArrayList<>()); + if (audioJack == null) { + audioJack = new AudioJack("input"); + } + short[] buffer = audioJack.read(); + yDataString.add(new String[buffer.length]); + + int n = buffer.length; + Complex[] fftOut = null; + if (isFourierTransformSelected) { + Complex[] yComplex = new Complex[n]; + for (int j = 0; j < n; j++) { + float audioValue = (float) map(buffer[j], -32768, 32767, -3, 3); + yComplex[j] = Complex.valueOf(audioValue); + } + fftOut = fft(yComplex); + } + double factor = buffer.length * timeGap * 1e-3; + maxFreq = (n / 2 - 1) / factor; + double mA = 0; + for (int i = 0; i < n; i++) { + float audioValue = (float) map(buffer[i], -32768, 32767, -3, 3); + if (!isFourierTransformSelected) { + entries.get(noOfChannels - 1).add(new Entry(i, audioValue)); + } else { + if (i < n / 2) { + float y = (float) fftOut[i].abs() / samples; + if (y > mA) { + mA = y; + } + entries.get(noOfChannels - 1).add(new Entry((float) (i / factor), y)); + } + } + yDataString.get(noOfChannels - 1)[i] = String.valueOf(audioValue); + } + if (mA > maxAmp) { + maxAmp = mA; + } - int n = Math.min(xData.length, Math.min(y1Data.length, y2Data.length)); - String[] xString = new String[n]; - String[] y1String = new String[n]; - String[] y2String = new String[n]; - for (int i = 0; i < n; i++) { - xData[i] = xData[i] / ((timebase == 875) ? 1 : 1000); - entries1.add(new Entry((float) xData[i], (float) y1Data[i])); - entries2.add(new Entry((float) xData[i], (float) y2Data[i])); - xString[i] = String.valueOf(xData[i]); - y1String[i] = String.valueOf(y1Data[i]); - y2String[i] = String.valueOf(y2Data[i]); } - loggingXdata = String.join(" ", xString); - loggingYdata1 = String.join(" ", y1String); - loggingYdata2 = String.join(" ", y2String); - if (isRecording) { + loggingXdata = String.join(" ", xDataString); + for (int i = 0; i < noOfChannels; i++) { + loggingYdata[i] = String.join(" ", yDataString.get(i)); + } runOnUiThread(new Runnable() { @Override public void run() { - logTwoChannelData(analogInput1, analogInput2); + logChannelData(paramsChannels); } }); } @@ -1218,83 +1062,7 @@ public void run() { } catch (InterruptedException e) { e.printStackTrace(); } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (!String.valueOf(ledImageView.getTag()).equals("green")) { - ledImageView.setImageResource(R.drawable.green_led); - ledImageView.setTag("green"); - } - - LineDataSet dataSet1; - LineDataSet dataSet2; - dataSet1 = new LineDataSet(entries1, analogInput1); - dataSet2 = new LineDataSet(entries2, analogInput2); - dataSet2.setColor(Color.GREEN); - - dataSet1.setDrawCircles(false); - dataSet2.setDrawCircles(false); - - List dataSets = new ArrayList<>(); - dataSets.add(dataSet1); - dataSets.add(dataSet2); - - LineData data = new LineData(dataSets); - setXAxisScale(xAxisScale); - setLeftYAxisScale(16, -16); - setRightYAxisScale(16, -16); - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - synchronized (lock) { - lock.notify(); - } - } - } - - public class CaptureTaskThree extends AsyncTask { - ArrayList entries1; - ArrayList entries2; - ArrayList entries3; - ArrayList entries4; - String analogInput; - @Override - protected Void doInBackground(String... params) { - try { - // number of samples and timeGap still need to be determined - analogInput = params[0]; - HashMap data; - - if (isTriggerSelected) { - scienceLab.configureTrigger(CHANNEL.valueOf(triggerChannel).ordinal(), analogInput, trigger, null, null); - } - data = scienceLab.captureFour(samples, timeGap, analogInput, isTriggerSelected); - - double[] xData = data.get("x"); - double[] y1Data = data.get("y"); - double[] y2Data = data.get("y2"); - double[] y3Data = data.get("y3"); - double[] y4Data = data.get("y4"); - - entries1 = new ArrayList<>(); - entries2 = new ArrayList<>(); - entries3 = new ArrayList<>(); - entries4 = new ArrayList<>(); - - for (int i = 0; i < xData.length; i++) { - float xi = (float) xData[i] / ((timebase == 875) ? 1 : 1000); - entries1.add(new Entry(xi, (float) y1Data[i])); - entries2.add(new Entry(xi, (float) y2Data[i])); - entries3.add(new Entry(xi, (float) y3Data[i])); - entries4.add(new Entry(xi, (float) y4Data[i])); - } - } catch (NullPointerException e) { - cancel(true); - } return null; } @@ -1306,207 +1074,25 @@ protected void onPostExecute(Void aVoid) { ledImageView.setTag("green"); } - LineDataSet dataSet1 = new LineDataSet(entries1, CHANNEL.CH1.toString()); - LineDataSet dataSet2 = new LineDataSet(entries2, CHANNEL.CH2.toString()); - LineDataSet dataSet3 = new LineDataSet(entries3, CHANNEL.CH3.toString()); - LineDataSet dataSet4 = new LineDataSet(entries4, CHANNEL.MIC.toString()); - - dataSet1.setColor(Color.BLUE); - dataSet2.setColor(Color.GREEN); - dataSet3.setColor(Color.RED); - dataSet4.setColor(Color.YELLOW); - dataSet1.setDrawCircles(false); - dataSet2.setDrawCircles(false); - dataSet3.setDrawCircles(false); - dataSet4.setDrawCircles(false); - List dataSets = new ArrayList<>(); - dataSets.add(dataSet1); - dataSets.add(dataSet2); - dataSets.add(dataSet3); - dataSets.add(dataSet4); + for (int i = 0; i < Math.min(entries.size(), paramsChannels.length); i++) { + LineDataSet dataSet; + dataSet = new LineDataSet(entries.get(i), paramsChannels[i]); + dataSet.setDrawCircles(false); + dataSet.setColor(channelColors[i]); + dataSets.add(dataSet); - LineData data = new LineData(dataSets); - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - synchronized (lock) { - lock.notify(); } - } - } - - public class XYPlotTask extends AsyncTask { - String analogInput; - float[] xFloatData = new float[1000]; - float[] yFloatData = new float[1000]; - - @Override - protected Void doInBackground(String... params) { - HashMap data; - if ("CH2".equals(xyPlotXAxisChannel) || "CH2".equals(xyPlotYAxisChannel)) { - analogInput = params[0]; - data = scienceLab.captureTwo(1000, 10, analogInput, false); - double y1Data[] = data.get("y1"); - double y2Data[] = data.get("y2"); - if ("CH2".equals(xyPlotYAxisChannel)) { - for (int i = 0; i < y1Data.length; i++) { - xFloatData[i] = (float) y1Data[i]; - yFloatData[i] = (float) y2Data[i]; - } - } else { - for (int i = 0; i < y1Data.length; i++) { - xFloatData[i] = (float) y2Data[i]; - yFloatData[i] = (float) y1Data[i]; - } - } + LineData data = new LineData(dataSets); + if (!isFourierTransformSelected) { + setXAxisScale(xAxisScale); + setLeftYAxisScale(16, -16); + setRightYAxisScale(16, -16); } else { - data = scienceLab.captureFour(1000, 10, analogInput, false); - double[] y1Data = data.get("y"); - double[] y3Data = data.get("y3"); - double[] y4Data = data.get("y4"); - switch (xyPlotXAxisChannel) { - case "CH1": - for (int i = 0; i < y1Data.length; i++) { - xFloatData[i] = (float) y1Data[i]; - } - break; - case "CH3": - for (int i = 0; i < y3Data.length; i++) { - xFloatData[i] = (float) y3Data[i]; - } - break; - case "MIC": - for (int i = 0; i < y4Data.length; i++) { - xFloatData[i] = (float) y4Data[i]; - } - break; - } - - switch (xyPlotYAxisChannel) { - case "CH1": - for (int i = 0; i < y1Data.length; i++) { - yFloatData[i] = (float) y1Data[i]; - } - break; - case "CH3": - for (int i = 0; i < y3Data.length; i++) { - yFloatData[i] = (float) y3Data[i]; - } - break; - case "MIC": - for (int i = 0; i < y4Data.length; i++) { - yFloatData[i] = (float) y4Data[i]; - } - break; - } + setXAxisScale(maxFreq); + setLeftYAxisScale(maxAmp, 0); + setRightYAxisScale(maxAmp, 0); } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - graph.plotData(xFloatData, yFloatData, 1); - } - } - - public class CaptureAudioBuffer extends AsyncTask { - - private AudioJack audioJack; - private short[] buffer; - private List entries; - - public CaptureAudioBuffer(AudioJack audioJack) { - this.audioJack = audioJack; - } - - @Override - protected Void doInBackground(Void... params) { - buffer = audioJack.read(); - entries = new ArrayList<>(); - for (int i = 0; i < buffer.length; i++) { - entries.add(new Entry(i, (float) map(buffer[i], -32768, 32767, -3, 3))); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - // Update chart - LineDataSet lineDataSet = new LineDataSet(entries, "Audio Data"); - lineDataSet.setColor(Color.WHITE); - lineDataSet.setDrawCircles(false); - mChart.setData(new LineData(lineDataSet)); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - synchronized (lock) { - lock.notify(); - } - } - } - - public class CaptureAudioBufferTwo extends AsyncTask { - private AudioJack audioJack; - private short[] buffer; - private ArrayList entries1; - private ArrayList entries2; - private String analogInput; - - public CaptureAudioBufferTwo(AudioJack audioJack, String analogInput) { - this.audioJack = audioJack; - this.analogInput = analogInput; - } - - @Override - protected Void doInBackground(Void... voids) { - try { - buffer = audioJack.read(); - entries1 = new ArrayList<>(); - for (int i = 0; i < buffer.length; i++) { - entries1.add(new Entry(i, (float) map(buffer[i], -32768, 32767, -3, 3))); - } - - if (isTriggerSelected) { - scienceLab.configureTrigger(0, analogInput, trigger, null, null); - } - scienceLab.captureTraces(1, samples, timeGap, analogInput, isTriggerSelected, null); - Log.v("Sleep Time", "" + (1024 * 10 * 1e-3)); - Thread.sleep((long) (1000 * 10 * 1e-3)); - HashMap data = scienceLab.fetchTrace(1); //fetching data - - double[] xData = data.get("x"); - double[] yData = data.get("y"); - - entries2 = new ArrayList<>(); - for (int i = 0; i < xData.length; i++) { - entries2.add(new Entry((float) xData[i] / ((timebase == 875) ? 1 : 1000), (float) yData[i])); - } - } catch (NullPointerException e) { - cancel(true); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } - - @Override - protected void onPostExecute(Void aVoid) { - LineDataSet dataSet1; - LineDataSet dataSet2; - dataSet1 = new LineDataSet(entries1, "Audio Data"); - dataSet2 = new LineDataSet(entries2, analogInput); - dataSet2.setColor(Color.GREEN); - - dataSet1.setDrawCircles(false); - dataSet2.setDrawCircles(false); - - List dataSets = new ArrayList<>(); - dataSets.add(dataSet1); - dataSets.add(dataSet2); - - LineData data = new LineData(dataSets); mChart.setData(data); mChart.notifyDataSetChanged(); mChart.invalidate(); @@ -1516,136 +1102,64 @@ protected void onPostExecute(Void aVoid) { } } - public class FFTTask extends AsyncTask { - ArrayList entries; - String analogInput; + public class XYPlotTask extends AsyncTask { + private String analogInput1; + private String analogInput2; + private float[] xFloatData; + private float[] yFloatData; @Override protected Void doInBackground(String... params) { - try { - analogInput = params[0]; - if (isTriggerSelected) { - scienceLab.configureTrigger(0, analogInput, trigger, null, null); - } - // number of samples and timeGap still need to be determined - scienceLab.captureTraces(1, samples, timeGap, analogInput, isTriggerSelected, null); - Log.v("Sleep Time", "" + (1024 * 10 * 1e-3)); - Thread.sleep((long) (1000 * 10 * 1e-3)); - HashMap data = scienceLab.fetchTrace(1); //fetching data - + analogInput1 = params[0]; + analogInput2 = params[1]; + HashMap data; + if (analogInput1.equals(analogInput2)) { + scienceLab.captureTraces(1, samples, timeGap, analogInput1, isTriggerSelected, null); + data = scienceLab.fetchTrace(1); double[] yData = data.get("y"); - Complex[] yComplex = new Complex[yData.length]; - for (int i = 0; i < yData.length; i++) { - yComplex[i] = Complex.valueOf(yData[i]); + int n = yData.length; + xFloatData = new float[n]; + yFloatData = new float[n]; + for (int i = 0; i < n; i++) { + xFloatData[i] = (float) yData[i]; + yFloatData[i] = (float) yData[i]; } - Complex[] fftOut = fft(yComplex); - int n = fftOut.length; - maxAmp = 0; + } else { + int noChannels = 1; + if ((analogInput1.equals(CHANNEL.CH1.toString()) && analogInput2.equals(CHANNEL.CH2.toString())) || (analogInput1.equals(CHANNEL.CH2.toString()) && analogInput2.equals(CHANNEL.CH1.toString()))) { + noChannels = 2; + scienceLab.captureTraces(noChannels, 175, timeGap, "CH1", isTriggerSelected, null); + data = scienceLab.fetchTrace(1); + double[] yData1 = data.get("y"); + data = scienceLab.fetchTrace(2); + double[] yData2 = data.get("y"); + int n = Math.min(yData1.length, yData2.length); + xFloatData = new float[n]; + yFloatData = new float[n]; + for (int i = 0; i < n; i++) { + xFloatData[i] = (float) yData1[i]; + yFloatData[i] = (float) yData2[i]; + } - entries = new ArrayList<>(); - double factor = samples * timeGap * 1e-3; - maxFreq = (n / 2 - 1) / factor; - for (int i = 0; i < n / 2; i++) { - float y = (float) fftOut[i].abs() / samples; - if (y > maxAmp) { - maxAmp = y; + } else { + noChannels = 4; + scienceLab.captureTraces(noChannels, 175, timeGap, "CH1", isTriggerSelected, null); + data = scienceLab.fetchTrace(channelIndexMap.get(analogInput1) + 1); + double[] yData1 = data.get("y"); + data = scienceLab.fetchTrace(channelIndexMap.get(analogInput2) + 1); + double[] yData2 = data.get("y"); + int n = Math.min(yData1.length, yData2.length); + xFloatData = new float[n]; + yFloatData = new float[n]; + for (int i = 0; i < n; i++) { + xFloatData[i] = (float) yData1[i]; + yFloatData[i] = (float) yData2[i]; } - entries.add(new Entry((float) (i / factor), y)); } - } catch (NullPointerException e) { - cancel(true); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - } - @Override - protected void onPostExecute(Void aVoid) { - super.onPostExecute(aVoid); - if (!String.valueOf(ledImageView.getTag()).equals("green")) { - ledImageView.setImageResource(R.drawable.green_led); - ledImageView.setTag("green"); } - - LineDataSet dataSet = new LineDataSet(entries, analogInput); - LineData lineData = new LineData(dataSet); - dataSet.setDrawCircles(false); - setXAxisScale(maxFreq); - setLeftYAxisScale(maxAmp, 0); - setRightYAxisScale(maxAmp, 0); - mChart.setData(lineData); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - - synchronized (lock) { - lock.notify(); - } - } - } - - public class FFTTaskTwo extends AsyncTask { - private ArrayList entries1; - private ArrayList entries2; - private String analogInput1; - private String analogInput2; - - @Override - protected Void doInBackground(String... params) { try { - analogInput1 = params[0]; - analogInput2 = params[1]; - if (isTriggerSelected) { - if (triggerChannel.equals("CH1")) - scienceLab.configureTrigger(0, analogInput1, trigger, null, null); - else if (triggerChannel.equals("CH2")) - scienceLab.configureTrigger(1, analogInput2, trigger, null, null); - } - // number of samples and timeGap still need to be determined - scienceLab.captureTraces(1, samples, timeGap, analogInput1, isTriggerSelected, null); - Log.v("Sleep Time", "" + (1024 * 10 * 1e-3)); - Thread.sleep((long) (1000 * 10 * 1e-3)); - HashMap data1 = scienceLab.fetchTrace(1); //fetching data - - scienceLab.captureTraces(1, samples, timeGap, analogInput2, isTriggerSelected, null); - Log.v("Sleep Time", "" + (1024 * 10 * 1e-3)); - Thread.sleep((long) (1000 * 10 * 1e-3)); - HashMap data2 = scienceLab.fetchTrace(1); - - double[] yData1 = data1.get("y"); - double[] yData2 = data2.get("y"); - Complex[] yComplex1 = new Complex[yData1.length]; - Complex[] yComplex2 = new Complex[yData2.length]; - for (int i = 0; i < Math.min(yData1.length, yData2.length); i++) { - yComplex1[i] = Complex.valueOf(yData1[i]); - yComplex2[i] = Complex.valueOf(yData2[i]); - } - Complex[] fftOut1 = fft(yComplex1); - Complex[] fftOut2 = fft(yComplex2); - int n = Math.min(fftOut1.length, fftOut2.length); - maxAmp = 0; - - float maxAmp1 = 0; - float maxAmp2 = 0; - entries1 = new ArrayList<>(); - entries2 = new ArrayList<>(); - double factor = samples * timeGap * 1e-3; - maxFreq = (n / 2 - 1) / factor; - for (int i = 0; i < n / 2; i++) { - float y1 = (float) fftOut1[i].abs() / samples; - if (y1 > maxAmp1) { - maxAmp1 = y1; - } - entries1.add(new Entry((float) (i / factor), y1)); - float y2 = (float) fftOut2[i].abs() / samples; - if (y2 > maxAmp2) { - maxAmp2 = y2; - } - entries2.add(new Entry((float) (i / factor), y2)); - } - maxAmp = Math.max(maxAmp1, maxAmp2); - } catch (NullPointerException e) { - cancel(true); + Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } @@ -1655,30 +1169,7 @@ else if (triggerChannel.equals("CH2")) @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); - if (!String.valueOf(ledImageView.getTag()).equals("green")) { - ledImageView.setImageResource(R.drawable.green_led); - ledImageView.setTag("green"); - } - - LineDataSet dataSet1 = new LineDataSet(entries1, analogInput1); - LineDataSet dataSet2 = new LineDataSet(entries2, analogInput2); - dataSet2.setColor(Color.GREEN); - - dataSet1.setDrawCircles(false); - dataSet2.setDrawCircles(false); - - List dataSets = new ArrayList<>(); - dataSets.add(dataSet1); - dataSets.add(dataSet2); - - LineData data = new LineData(dataSets); - setXAxisScale(maxFreq); - setLeftYAxisScale(maxAmp, 0); - setRightYAxisScale(maxAmp, 0); - mChart.setData(data); - mChart.notifyDataSetChanged(); - mChart.invalidate(); - + graph.plotData(xFloatData, yFloatData, 1); synchronized (lock) { lock.notify(); } @@ -1710,6 +1201,12 @@ public Complex[] fft(Complex[] input) { for (int k = 0; k < n / 2; k++) { double kth = -2 * k * Math.PI / n; Complex wk = new Complex(Math.cos(kth), Math.sin(kth)); + if (r[k] == null) { + r[k] = new Complex(1); + } + if (q[k] == null) { + q[k] = new Complex(1); + } y[k] = q[k].add(wk.multiply(r[k])); y[k + n / 2] = q[k].subtract(wk.multiply(r[k])); } diff --git a/app/src/main/java/io/pslab/activity/RoboticArmActivity.java b/app/src/main/java/io/pslab/activity/RoboticArmActivity.java index 2246ba965..a508ed7f2 100644 --- a/app/src/main/java/io/pslab/activity/RoboticArmActivity.java +++ b/app/src/main/java/io/pslab/activity/RoboticArmActivity.java @@ -2,24 +2,31 @@ import android.content.Context; import android.content.Intent; +import android.content.SharedPreferences; import android.graphics.Point; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.CountDownTimer; +import android.os.Handler; +import android.support.annotation.NonNull; +import android.support.design.widget.BottomSheetBehavior; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Display; import android.view.DragEvent; +import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; +import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.HorizontalScrollView; +import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; @@ -30,6 +37,8 @@ import java.util.ArrayList; import java.util.Date; +import butterknife.BindView; +import butterknife.ButterKnife; import io.pslab.R; import io.pslab.communication.ScienceLab; import io.pslab.models.SensorDataBlock; @@ -38,13 +47,16 @@ import io.pslab.others.CustomSnackBar; import io.pslab.others.GPSLogger; import io.pslab.others.LocalDataLog; +import io.pslab.others.MathUtils; import io.pslab.others.ScienceLabCommon; +import io.pslab.others.SwipeGestureDetector; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RealmResults; public class RoboticArmActivity extends AppCompatActivity { + private static final String PREF_NAME = "RoboticArmActivity"; private EditText degreeText1, degreeText2, degreeText3, degreeText4; private SeekArc seekArc1, seekArc2, seekArc3, seekArc4; private LinearLayout servo1TimeLine, servo2TimeLine, servo3TimeLine, servo4TimeLine; @@ -62,11 +74,32 @@ public class RoboticArmActivity extends AppCompatActivity { private final String DATA_BLOCK = "data_block"; private int timelinePosition = 0; private ScienceLab scienceLab; + private BottomSheetBehavior bottomSheetBehavior; + private GestureDetector gestureDetector; + @BindView(R.id.sheet_slide_text_robotic_arm) + TextView bottomSheetSlideText; + @BindView(R.id.parent_layout_robotic) + View parentLayout; + @BindView(R.id.bottom_sheet_robotic_arm) + LinearLayout bottomSheet; + @BindView(R.id.img_arrow_robotic_arm) + ImageView arrowUpDown; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_robotic_arm); + ButterKnife.bind(this); + + setUpBottomSheet(); + parentLayout.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) + bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); + parentLayout.setVisibility(View.GONE); + } + }); scienceLab = ScienceLabCommon.scienceLab; if (!scienceLab.isConnected()) { @@ -484,6 +517,79 @@ public void onClick(View v) { .getBlockOfServoRecords(getIntent().getExtras().getLong(DATA_BLOCK)); setReceivedData(); } + + Button guideButton = findViewById(R.id.timeline_guide_button); + guideButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + bottomSheetBehavior.setState(bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_HIDDEN ? + BottomSheetBehavior.STATE_EXPANDED : BottomSheetBehavior.STATE_HIDDEN); + } + }); + } + + private void setUpBottomSheet() { + bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet); + + final SharedPreferences settings = this.getSharedPreferences(PREF_NAME, MODE_PRIVATE); + Boolean isFirstTime = settings.getBoolean("RoboticArmFirstTime", true); + + if (isFirstTime) { + bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); + parentLayout.setVisibility(View.VISIBLE); + parentLayout.setAlpha(0.8f); + arrowUpDown.setRotation(180); + bottomSheetSlideText.setText(R.string.hide_guide_text); + SharedPreferences.Editor editor = settings.edit(); + editor.putBoolean("RoboticArmFirstTime", false); + editor.apply(); + } else { + bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); + } + + bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() { + private Handler handler = new Handler(); + private Runnable runnable = new Runnable() { + @Override + public void run() { + bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); + } + }; + + @Override + public void onStateChanged(@NonNull final View bottomSheet, int newState) { + switch (newState) { + case BottomSheetBehavior.STATE_EXPANDED: + handler.removeCallbacks(runnable); + bottomSheetSlideText.setText(R.string.hide_guide_text); + break; + + case BottomSheetBehavior.STATE_COLLAPSED: + handler.postDelayed(runnable, 2000); + break; + + default: + handler.removeCallbacks(runnable); + bottomSheetSlideText.setText(R.string.show_guide_text); + break; + } + } + + @Override + public void onSlide(@NonNull View bottomSheet, float slideOffset) { + Float value = (float) MathUtils.map((double) slideOffset, 0.0, 1.0, 0.0, 0.8); + parentLayout.setVisibility(View.VISIBLE); + parentLayout.setAlpha(value); + arrowUpDown.setRotation(slideOffset * 180); + } + }); + gestureDetector = new GestureDetector(this, new SwipeGestureDetector(bottomSheetBehavior)); + } + + @Override + public boolean onTouchEvent(MotionEvent event) { + gestureDetector.onTouchEvent(event); //Gesture detector need this to transfer touch event to the gesture detector. + return super.onTouchEvent(event); } private void toastInvalidValueMessage() { @@ -545,7 +651,7 @@ private void saveTimeline() { } } servoCSVLogger.writeCSVFile(data); - CustomSnackBar.showSnackBar(findViewById(R.id.robotic_arm_relative_view), + CustomSnackBar.showSnackBar(findViewById(R.id.robotic_arm_coordinator), getString(R.string.csv_store_text) + " " + servoCSVLogger.getCurrentFilePath() , getString(R.string.open), new View.OnClickListener() { @Override diff --git a/app/src/main/java/io/pslab/activity/WaveGeneratorActivity.java b/app/src/main/java/io/pslab/activity/WaveGeneratorActivity.java index 3dbfded14..759b82a3f 100644 --- a/app/src/main/java/io/pslab/activity/WaveGeneratorActivity.java +++ b/app/src/main/java/io/pslab/activity/WaveGeneratorActivity.java @@ -456,8 +456,7 @@ public void onClick(View view) { double dutySqr4 = ((double) WaveGeneratorCommon.wave.get(WaveConst.SQR4).get(WaveConst.DUTY)) / 100; double phaseSqr4 = (double) WaveGeneratorCommon.wave.get(WaveConst.SQR4).get(WaveConst.PHASE) / 360; - scienceLab.sqrPWM(freqSqr1, dutySqr1, phaseSqr2, dutySqr2, phaseSqr3, dutySqr3, phaseSqr4, dutySqr4, true); - scienceLab.setState(WaveGeneratorCommon.state); + scienceLab.sqrPWM(freqSqr1, dutySqr1, phaseSqr2, dutySqr2, phaseSqr3, dutySqr3, phaseSqr4, dutySqr4, false); } waveDialog.show(); diff --git a/app/src/main/java/io/pslab/fragment/AccelerometerDataFragment.java b/app/src/main/java/io/pslab/fragment/AccelerometerDataFragment.java index c808e3eef..2792fdf1b 100644 --- a/app/src/main/java/io/pslab/fragment/AccelerometerDataFragment.java +++ b/app/src/main/java/io/pslab/fragment/AccelerometerDataFragment.java @@ -13,17 +13,11 @@ import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.text.Html; +import android.util.Pair; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; import android.widget.Toast; - -import com.github.mikephil.charting.charts.LineChart; -import com.github.mikephil.charting.components.Legend; -import com.github.mikephil.charting.components.XAxis; -import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; @@ -42,20 +36,11 @@ import java.util.Locale; import java.util.Timer; import java.util.TimerTask; - -import butterknife.BindView; -import butterknife.ButterKnife; -import butterknife.Unbinder; import io.pslab.R; import io.pslab.activity.AccelerometerActivity; -import io.pslab.communication.ScienceLab; -import io.pslab.communication.peripherals.I2C; -import io.pslab.communication.sensors.BH1750; -import io.pslab.communication.sensors.TSL2561; import io.pslab.models.AccelerometerData; import io.pslab.models.SensorDataBlock; import io.pslab.others.CSVLogger; -import io.pslab.others.ScienceLabCommon; import static android.content.Context.SENSOR_SERVICE; import static io.pslab.others.CSVLogger.CSV_DIRECTORY; @@ -66,84 +51,20 @@ public class AccelerometerDataFragment extends Fragment { - private static int sensorType = 0; - private static int highLimit = 2000; - private static int updatePeriod = 100; - private static int gain = 1; - private int count = 0, turns = 0; - private float sum = 0; + private static int updatePeriod = 1000; + private static float highLimit = 1.2f; + private static float gain = 1; + private int turns = 0; private boolean returningFromPause = false; - private int[] colors = {Color.YELLOW, Color.MAGENTA, Color.GREEN}; - private float accelerometerValue_X = -1; - private float accelerometerValue_Y = -1; - private float accelerometerValue_Z = -1; - - private enum ACCELEROMETER_SENSOR {INBUILT_SENSOR, BH1750_SENSOR, TSL2561_SENSOR} - - @BindView(R.id.x_axis_image) - ImageView x_axis; - @BindView(R.id.x_accel_value) - TextView x_accel_value; - @BindView(R.id.x_accel_min_text) - TextView x_accel_min; - @BindView(R.id.x_accel_max_text) - TextView x_accel_max; - @BindView(R.id.x_tv_graph_label_xaxis_hmc) - TextView x_tv_graph_label_xaxis_hmc; - @BindView(R.id.x_tv_label_left_yaxis_hmc) - TextView x_tv_label_left_yaxis_hmc; - @BindView(R.id.chart_accelerometer_x) - LineChart x_chart_accelerometer; - - @BindView(R.id.y_axis_image) - ImageView y_axis; - @BindView(R.id.y_accel_value) - TextView y_accel_value; - @BindView(R.id.y_accel_min_text) - TextView y_accel_min_text; - @BindView(R.id.y_accel_max_text) - TextView y_accel_max_text; - @BindView(R.id.y_tv_graph_label_xaxis_hmc) - TextView y_tv_graph_label_xaxis_hmc; - @BindView(R.id.y_tv_label_left_yaxis_hmc) - TextView y_tv_label_left_yaxis_hmc; - @BindView(R.id.y_chart_accelerometer) - LineChart y_chart_accelerometer; - - @BindView(R.id.z_axis_image) - ImageView z_axis_image; - @BindView(R.id.z_accel_value) - TextView z_accel_value; - @BindView(R.id.z_accel_min_text) - TextView z_accel_min_text; - @BindView(R.id.z_accel_max_text) - TextView z_accel_max_text; - @BindView(R.id.z_tv_graph_label_xaxis_hmc) - TextView z_tv_graph_label_xaxis_hmc; - @BindView(R.id.z_tv_label_left_yaxis_hmc) - TextView z_tv_label_left_yaxis_hmc; - @BindView(R.id.z_chart_accelerometer) - LineChart z_chart_accelerometer; - private Timer graphTimer; private SensorManager sensorManager; private Sensor sensor; private long startTime, block; - private ArrayList entriesX, entriesY, entriesZ; - private ArrayList recordedAccelerometerArray; private AccelerometerData sensorData; - private float currentMinX = Integer.MAX_VALUE; - private float currentMaxX = Integer.MIN_VALUE; - private float currentMinY = Integer.MAX_VALUE; - private float currentMaxY = Integer.MIN_VALUE; - private float currentMinZ = Integer.MAX_VALUE; - private float currentMaxZ = Integer.MIN_VALUE; - private YAxis y; - private Unbinder unbinder; - private long previousTimeElapsed_X = (System.currentTimeMillis() - startTime) / updatePeriod; - private long previousTimeElapsed_Y = (System.currentTimeMillis() - startTime) / updatePeriod; - private long previousTimeElapsed_Z = (System.currentTimeMillis() - startTime) / updatePeriod; + private ArrayList recordedAccelerometerArray; private AccelerometerActivity accelerometerSensor; + private ArrayList accelerometerViewFragments = new ArrayList<>(); + private int[] colors = {Color.YELLOW, Color.MAGENTA, Color.GREEN}; private DecimalFormat df = new DecimalFormat("+#0.0;-#0.0"); private View rootView; @@ -151,28 +72,38 @@ public static AccelerometerDataFragment newInstance() { return new AccelerometerDataFragment(); } - public static void setParameters(int highLimit, int updatePeriod, String type, String gain) { + public static void setParameters(float highLimit, int updatePeriod, String gain) { AccelerometerDataFragment.highLimit = highLimit; AccelerometerDataFragment.updatePeriod = updatePeriod; - AccelerometerDataFragment.sensorType = Integer.valueOf(type); AccelerometerDataFragment.gain = Integer.valueOf(gain); } + public static Pair> getParameters() { + return new Pair<>(updatePeriod, new Pair<>(highLimit, gain)); + } + @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); startTime = System.currentTimeMillis(); - entriesX = new ArrayList<>(); - entriesY = new ArrayList<>(); - entriesZ = new ArrayList<>(); accelerometerSensor = (AccelerometerActivity) getActivity(); + for (AccelerometerViewFragment fragment : accelerometerViewFragments) { + fragment.clear(); + } } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_accelerometer_data, container, false); - unbinder = ButterKnife.bind(this, rootView); + accelerometerViewFragments.clear(); + accelerometerViewFragments.add((AccelerometerViewFragment) getChildFragmentManager().findFragmentById(R.id.accelerometer_x_axis_fragment)); + accelerometerViewFragments.add((AccelerometerViewFragment) getChildFragmentManager().findFragmentById(R.id.accelerometer_y_axis_fragment)); + accelerometerViewFragments.add((AccelerometerViewFragment) getChildFragmentManager().findFragmentById(R.id.accelerometer_z_axis_fragment)); + + accelerometerViewFragments.get(1).getAccelerationAxisImage().setImageResource(R.drawable.phone_y_axis); + accelerometerViewFragments.get(2).getAccelerationAxisImage().setImageResource(R.drawable.phone_z_axis); + setupInstruments(); return rootView; } @@ -185,109 +116,17 @@ public void onResume() { resetInstrumentData(); playRecordedData(); } else if (accelerometerSensor.viewingData) { - recordedAccelerometerArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); + recordedAccelerometerArray = new ArrayList<>(); + resetInstrumentData(); + plotAllRecordedData(); } else if (!accelerometerSensor.isRecording) { updateGraphs(); - sum = 0; - count = 0; - currentMinX = Integer.MAX_VALUE; - currentMaxX = Integer.MIN_VALUE; - currentMinY = Integer.MAX_VALUE; - currentMaxY = Integer.MIN_VALUE; - currentMinZ = Integer.MAX_VALUE; - currentMaxZ = Integer.MIN_VALUE; - entriesX.clear(); - entriesY.clear(); - entriesZ.clear(); - - x_chart_accelerometer.clear(); - x_chart_accelerometer.invalidate(); - - y_chart_accelerometer.clear(); - y_chart_accelerometer.invalidate(); - - z_chart_accelerometer.clear(); - z_chart_accelerometer.invalidate(); - - initiateAccelerometerSensor(sensorType); + initiateAccelerometerSensor(); } else if (returningFromPause) { updateGraphs(); } } - private void plotAllRecordedData() { - recordedAccelerometerArray.addAll(accelerometerSensor.recordedAccelerometerData); - if (recordedAccelerometerArray.size() != 0) { - for (AccelerometerData d : recordedAccelerometerArray) { - if (currentMaxX < d.getAccelerometerX()) { - currentMaxX = d.getAccelerometerX(); - } - if (currentMinX > d.getAccelerometerX()) { - currentMinX = d.getAccelerometerX(); - } - Entry entryX = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometerX()); - entriesX.add(entryX); - count++; - sum += entryX.getY(); - Entry entryY = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometerY()); - entriesY.add(entryY); - count++; - sum += entryY.getY(); - Entry entryZ = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometerZ()); - entriesZ.add(entryZ); - count++; - sum += entryZ.getY(); - } - y.setAxisMaximum(20); - y.setAxisMinimum(-20); - y.setLabelCount(5); - - LineDataSet dataSet_X = new LineDataSet(entriesX, getString(R.string.accelerometer)); - LineData data_x = new LineData(dataSet_X); - dataSet_X.setDrawCircles(false); - dataSet_X.setDrawValues(false); - dataSet_X.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet_X.setLineWidth(1); - dataSet_X.setColor(colors[0]); - - x_chart_accelerometer.setData(data_x); - x_chart_accelerometer.notifyDataSetChanged(); - x_chart_accelerometer.setVisibleXRangeMaximum(3); - x_chart_accelerometer.moveViewToX(data_x.getEntryCount()); - x_chart_accelerometer.invalidate(); - - LineDataSet dataSet_Y = new LineDataSet(entriesY, getString(R.string.accelerometer)); - LineData data_y = new LineData(dataSet_Y); - dataSet_Y.setDrawCircles(false); - dataSet_Y.setDrawValues(false); - dataSet_Y.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet_Y.setLineWidth(1); - dataSet_Y.setColor(colors[1]); - - y_chart_accelerometer.setData(data_y); - y_chart_accelerometer.notifyDataSetChanged(); - y_chart_accelerometer.setVisibleXRangeMaximum(3); - y_chart_accelerometer.moveViewToX(data_y.getEntryCount()); - y_chart_accelerometer.invalidate(); - - LineDataSet dataSet_Z = new LineDataSet(entriesZ, getString(R.string.accelerometer)); - LineData data_z = new LineData(dataSet_Z); - dataSet_Z.setDrawCircles(false); - dataSet_Z.setDrawValues(false); - dataSet_Z.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet_Z.setLineWidth(1); - dataSet_Z.setColor(colors[2]); - - z_chart_accelerometer.setData(data_z); - z_chart_accelerometer.notifyDataSetChanged(); - z_chart_accelerometer.setVisibleXRangeMaximum(3); - z_chart_accelerometer.moveViewToX(data_z.getEntryCount()); - z_chart_accelerometer.invalidate(); - } - } - @Override public void onDestroyView() { super.onDestroyView(); @@ -297,7 +136,40 @@ public void onDestroyView() { if (sensorManager != null) { sensorManager.unregisterListener(accelerometerSensorEventListener); } - unbinder.unbind(); + } + + private void plotAllRecordedData() { + recordedAccelerometerArray.addAll(accelerometerSensor.recordedAccelerometerData); + if (recordedAccelerometerArray.size() != 0) { + for (int i = 0; i < accelerometerViewFragments.size(); i++) { + AccelerometerViewFragment fragment = accelerometerViewFragments.get(i); + for (AccelerometerData d : recordedAccelerometerArray) { + if (fragment.getCurrentMax() < d.getAccelerometer()[i]) { + fragment.setCurrentMax(d.getAccelerometer()[i]); + } + if (fragment.getCurrentMin() > d.getAccelerometer()[i]) { + fragment.setCurrentMin(d.getAccelerometer()[i]); + } + Entry entry = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometer()[i]); + fragment.addEntry(entry); + } + + fragment.setYaxis(highLimit); + + LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.accelerometer)); + dataSet.setDrawCircles(false); + dataSet.setDrawValues(false); + dataSet.setLineWidth(2); + + dataSet.setDrawCircles(false); + dataSet.setDrawValues(false); + dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); + dataSet.setLineWidth(1); + dataSet.setColor(colors[i]); + LineData data = new LineData(dataSet); + fragment.setChartData(data); + } + } } private void playRecordedData() { @@ -329,146 +201,59 @@ public void run() { handler.post(new Runnable() { @Override public void run() { - try { - boolean playComplete = false; - AccelerometerData d = recordedAccelerometerArray.get(turns); - turns++; - StringBuilder builder_x = new StringBuilder(); - builder_x.append(df.format(d.getAccelerometerX())); - builder_x.append(" "); - builder_x.append(getResources().getString(R.string.meters_per_sec_text)); - x_accel_value.setText(Html.fromHtml(builder_x.toString())); - - if (currentMaxX < d.getAccelerometerX()) { - currentMaxX = d.getAccelerometerX(); - StringBuilder builder_x_max = new StringBuilder(); - builder_x_max.append("Max: "); - builder_x_max.append(df.format(currentMaxX)); - builder_x_max.append(" "); - builder_x_max.append(getResources().getString(R.string.meters_per_sec_text)); - x_accel_max.setText(Html.fromHtml(builder_x_max.toString())); + if (accelerometerSensor.viewingData) { + try { + AccelerometerData d = recordedAccelerometerArray.get(turns); + turns++; + for (int i = 0; i < accelerometerViewFragments.size(); i++) { + AccelerometerViewFragment fragment = accelerometerViewFragments.get(i); + StringBuilder builder = new StringBuilder(); + builder.append(df.format(d.getAccelerometer()[i])); + builder.append(" "); + builder.append(getResources().getString(R.string.acceleration_unit)); + fragment.setAccelerationValue(Html.fromHtml(builder.toString())); + + if (fragment.getCurrentMax() < d.getAccelerometer()[i]) { + fragment.setCurrentMax(d.getAccelerometer()[i]); + StringBuilder max_builder = new StringBuilder(); + max_builder.append("Max: "); + max_builder.append(df.format(fragment.getCurrentMax())); + max_builder.append(" "); + max_builder.append(getResources().getString(R.string.acceleration_unit)); + fragment.setAccelerationMax(Html.fromHtml(max_builder.toString())); + } + if (fragment.getCurrentMin() > d.getAccelerometer()[i]) { + fragment.setCurrentMin(d.getAccelerometer()[i]); + StringBuilder min_builder = new StringBuilder(); + min_builder.append("Min: "); + min_builder.append(df.format(fragment.getCurrentMax())); + min_builder.append(" "); + min_builder.append(getResources().getString(R.string.acceleration_unit)); + fragment.setAccelerationMin(Html.fromHtml(min_builder.toString())); + } + + fragment.setYaxis(highLimit); + Entry entryX = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometer()[i]); + fragment.addEntry(entryX); + + LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.accelerometer)); + dataSet.setDrawCircles(false); + dataSet.setDrawValues(false); + dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); + dataSet.setLineWidth(1); + dataSet.setColor(colors[i]); + LineData data = new LineData(dataSet); + + fragment.setChartData(data); + } + } catch (IndexOutOfBoundsException e) { + graphTimer.cancel(); + graphTimer = null; + turns = 0; + accelerometerSensor.playingData = false; + accelerometerSensor.startedPlay = false; + accelerometerSensor.invalidateOptionsMenu(); } - if (currentMinX > d.getAccelerometerX()) { - currentMinX = d.getAccelerometerX(); - StringBuilder builder_x_min = new StringBuilder(); - builder_x_min.append("Min: "); - builder_x_min.append(df.format(currentMinX)); - builder_x_min.append(" "); - builder_x_min.append(getResources().getString(R.string.meters_per_sec_text)); - x_accel_min.setText(Html.fromHtml(builder_x_min.toString())); - } - StringBuilder builder_y = new StringBuilder(); - builder_y.append(df.format(d.getAccelerometerY())); - builder_y.append(" "); - builder_y.append(getResources().getString(R.string.meters_per_sec_text)); - y_accel_value.setText(Html.fromHtml(builder_y.toString())); - if (currentMaxY < d.getAccelerometerY()) { - currentMaxY = d.getAccelerometerY(); - StringBuilder builder_y_max = new StringBuilder(); - builder_y_max.append("Max: "); - builder_y_max.append(df.format(currentMaxY)); - builder_y_max.append(" "); - builder_y_max.append(getResources().getString(R.string.meters_per_sec_text)); - y_accel_max_text.setText(Html.fromHtml(builder_y_max.toString())); - } - if (currentMinY > d.getAccelerometerY()) { - currentMinY = d.getAccelerometerY(); - StringBuilder builder_y_min = new StringBuilder(); - builder_y_min.append("Min: "); - builder_y_min.append(df.format(currentMinY)); - builder_y_min.append(" "); - builder_y_min.append(getResources().getString(R.string.meters_per_sec_text)); - y_accel_min_text.setText(Html.fromHtml(builder_y_min.toString())); - } - StringBuilder builder_z = new StringBuilder(); - builder_z.append(df.format(d.getAccelerometerZ())); - builder_z.append(" "); - builder_z.append(getResources().getString(R.string.meters_per_sec_text)); - z_accel_value.setText(Html.fromHtml(builder_z.toString())); - if (currentMaxZ < d.getAccelerometerZ()) { - currentMaxZ = d.getAccelerometerZ(); - StringBuilder builder_z_max = new StringBuilder(); - builder_z_max.append("Max: "); - builder_z_max.append(df.format(currentMaxZ)); - builder_z_max.append(" "); - builder_z_max.append(getResources().getString(R.string.meters_per_sec_text)); - z_accel_max_text.setText(Html.fromHtml(builder_z_max.toString())); - } - if (currentMinZ > d.getAccelerometerZ()) { - currentMinZ = d.getAccelerometerZ(); - StringBuilder builder_z_min = new StringBuilder(); - builder_z_min.append("Min: "); - builder_z_min.append(df.format(currentMinZ)); - builder_z_min.append(" "); - builder_z_min.append(getResources().getString(R.string.meters_per_sec_text)); - z_accel_min_text.setText(Html.fromHtml(builder_z_min.toString())); - } - y.setAxisMaximum(20); - y.setAxisMinimum(-20); - y.setLabelCount(5); - - Entry entryX = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometerX()); - entriesX.add(entryX); - count++; - sum += entryX.getY(); - Entry entryY = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometerY()); - entriesY.add(entryY); - count++; - sum += entryY.getY(); - Entry entryZ = new Entry((float) (d.getTime() - d.getBlock()) / 1000, d.getAccelerometerZ()); - entriesZ.add(entryZ); - count++; - sum += entryZ.getY(); - - LineDataSet dataSet_X = new LineDataSet(entriesX, getString(R.string.accelerometer)); - LineData data_x = new LineData(dataSet_X); - dataSet_X.setDrawCircles(false); - dataSet_X.setDrawValues(false); - dataSet_X.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet_X.setLineWidth(1); - dataSet_X.setColor(colors[0]); - - x_chart_accelerometer.setData(data_x); - x_chart_accelerometer.notifyDataSetChanged(); - x_chart_accelerometer.setVisibleXRangeMaximum(3); - x_chart_accelerometer.moveViewToX(data_x.getEntryCount()); - x_chart_accelerometer.invalidate(); - - LineDataSet dataSet_Y = new LineDataSet(entriesY, getString(R.string.accelerometer)); - LineData data_y = new LineData(dataSet_Y); - dataSet_Y.setDrawCircles(false); - dataSet_Y.setDrawValues(false); - dataSet_Y.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet_Y.setLineWidth(1); - dataSet_Y.setColor(colors[1]); - - y_chart_accelerometer.setData(data_y); - y_chart_accelerometer.notifyDataSetChanged(); - y_chart_accelerometer.setVisibleXRangeMaximum(3); - y_chart_accelerometer.moveViewToX(data_y.getEntryCount()); - y_chart_accelerometer.invalidate(); - - LineDataSet dataSet_Z = new LineDataSet(entriesZ, getString(R.string.accelerometer)); - LineData data_z = new LineData(dataSet_Z); - dataSet_Z.setDrawCircles(false); - dataSet_Z.setDrawValues(false); - dataSet_Z.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet_Z.setLineWidth(1); - dataSet_Z.setColor(colors[2]); - - z_chart_accelerometer.setData(data_z); - z_chart_accelerometer.notifyDataSetChanged(); - z_chart_accelerometer.setVisibleXRangeMaximum(3); - z_chart_accelerometer.moveViewToX(data_z.getEntryCount()); - z_chart_accelerometer.invalidate(); - - } catch (IndexOutOfBoundsException e) { - graphTimer.cancel(); - graphTimer = null; - turns = 0; - accelerometerSensor.playingData = false; - accelerometerSensor.startedPlay = false; - accelerometerSensor.invalidateOptionsMenu(); } } }); @@ -476,15 +261,32 @@ public void run() { }, 0, timeGap); } + public void playData() { + resetInstrumentData(); + accelerometerSensor.startedPlay = true; + try { + if (recordedAccelerometerArray.size() > 1) { + AccelerometerData i = recordedAccelerometerArray.get(1); + long timeGap = i.getTime() - i.getBlock(); + processRecordedData(timeGap); + } else { + processRecordedData(0); + } + } catch (IllegalArgumentException e) { + Toast.makeText(getActivity(), + getActivity().getResources().getString(R.string.no_data_fetched), Toast.LENGTH_SHORT).show(); + } + } + public void stopData() { if (graphTimer != null) { graphTimer.cancel(); graphTimer = null; } recordedAccelerometerArray.clear(); - entriesX.clear(); - entriesY.clear(); - entriesZ.clear(); + for (AccelerometerViewFragment fragment : accelerometerViewFragments) { + fragment.clearEntry(); + } plotAllRecordedData(); accelerometerSensor.startedPlay = false; accelerometerSensor.playingData = false; @@ -529,126 +331,10 @@ public void saveGraph() { } } - - public void playData() { - resetInstrumentData(); - accelerometerSensor.startedPlay = true; - try { - if (recordedAccelerometerArray.size() > 1) { - AccelerometerData i = recordedAccelerometerArray.get(1); - long timeGap = i.getTime() - i.getBlock(); - processRecordedData(timeGap); - } else { - processRecordedData(0); - } - } catch (IllegalArgumentException e) { - Toast.makeText(getActivity(), - getActivity().getResources().getString(R.string.no_data_fetched), Toast.LENGTH_SHORT).show(); - } - } - private void setupInstruments() { - LineData data_x = new LineData(); - XAxis x = x_chart_accelerometer.getXAxis(); - this.y = x_chart_accelerometer.getAxisLeft(); - YAxis y2 = x_chart_accelerometer.getAxisRight(); - - x_chart_accelerometer.setTouchEnabled(true); - x_chart_accelerometer.setHighlightPerDragEnabled(true); - x_chart_accelerometer.setDragEnabled(true); - x_chart_accelerometer.setScaleEnabled(true); - x_chart_accelerometer.setDrawGridBackground(false); - x_chart_accelerometer.setPinchZoom(true); - x_chart_accelerometer.setScaleYEnabled(false); - x_chart_accelerometer.setBackgroundColor(Color.BLACK); - x_chart_accelerometer.getDescription().setEnabled(false); - - Legend l = x_chart_accelerometer.getLegend(); - l.setForm(Legend.LegendForm.LINE); - l.setTextColor(Color.WHITE); - - x_chart_accelerometer.setData(data_x); - - x.setTextColor(Color.WHITE); - x.setDrawGridLines(true); - x.setAvoidFirstLastClipping(true); - x.setDrawLabels(false); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(20); - y.setAxisMinimum(-20); - y.setDrawGridLines(true); - y.setLabelCount(6); - - y2.setDrawGridLines(false); - - LineData data_y = new LineData(); - XAxis x_1 = y_chart_accelerometer.getXAxis(); - this.y = y_chart_accelerometer.getAxisLeft(); - YAxis y2_1 = y_chart_accelerometer.getAxisRight(); - - y_chart_accelerometer.setTouchEnabled(true); - y_chart_accelerometer.setHighlightPerDragEnabled(true); - y_chart_accelerometer.setDragEnabled(true); - y_chart_accelerometer.setScaleEnabled(true); - y_chart_accelerometer.setDrawGridBackground(false); - y_chart_accelerometer.setPinchZoom(true); - y_chart_accelerometer.setScaleYEnabled(false); - y_chart_accelerometer.setBackgroundColor(Color.BLACK); - y_chart_accelerometer.getDescription().setEnabled(false); - - Legend l_1 = y_chart_accelerometer.getLegend(); - l_1.setForm(Legend.LegendForm.LINE); - l_1.setTextColor(Color.WHITE); - - y_chart_accelerometer.setData(data_y); - - x_1.setTextColor(Color.WHITE); - x_1.setDrawGridLines(true); - x_1.setAvoidFirstLastClipping(true); - x_1.setDrawLabels(false); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(20); - y.setAxisMinimum(-20); - y.setDrawGridLines(true); - y.setLabelCount(6); - - y2_1.setDrawGridLines(false); - - LineData data_z = new LineData(); - XAxis x_2 = z_chart_accelerometer.getXAxis(); - this.y = z_chart_accelerometer.getAxisLeft(); - YAxis y2_2 = z_chart_accelerometer.getAxisRight(); - - z_chart_accelerometer.setTouchEnabled(true); - z_chart_accelerometer.setHighlightPerDragEnabled(true); - z_chart_accelerometer.setDragEnabled(true); - z_chart_accelerometer.setScaleEnabled(true); - z_chart_accelerometer.setDrawGridBackground(false); - z_chart_accelerometer.setPinchZoom(true); - z_chart_accelerometer.setScaleYEnabled(false); - z_chart_accelerometer.setBackgroundColor(Color.BLACK); - z_chart_accelerometer.getDescription().setEnabled(false); - - Legend l_2 = z_chart_accelerometer.getLegend(); - l_2.setForm(Legend.LegendForm.LINE); - l_2.setTextColor(Color.WHITE); - - z_chart_accelerometer.setData(data_z); - - x_2.setTextColor(Color.WHITE); - x_2.setDrawGridLines(true); - x_2.setAvoidFirstLastClipping(true); - x_2.setDrawLabels(false); - - y.setTextColor(Color.WHITE); - y.setAxisMaximum(20); - y.setAxisMinimum(-20); - y.setDrawGridLines(true); - y.setLabelCount(6); - - y2_2.setDrawGridLines(false); + for (AccelerometerViewFragment fragment : accelerometerViewFragments) { + fragment.setUp(); + } } @Override @@ -701,12 +387,12 @@ private void writeLogToFile(long timestamp, float readingX, float readingY, floa Location location = accelerometerSensor.gpsLogger.getDeviceLocation(); accelerometerSensor.csvLogger.writeCSVFile(timestamp + "," + dateTime + "," + readingX + "," + readingY + "," + readingZ + "," + location.getLatitude() + "," + location.getLongitude()); - sensorData = new AccelerometerData(timestamp, block, accelerometerValue_X, accelerometerValue_Y, accelerometerValue_Z, location.getLatitude(), location.getLongitude()); + sensorData = new AccelerometerData(timestamp, block, accelerometerViewFragments.get(0).getCurrentValue(), accelerometerViewFragments.get(1).getCurrentValue(), accelerometerViewFragments.get(2).getCurrentValue(), location.getLatitude(), location.getLongitude()); } else { String dateTime = CSVLogger.FILE_NAME_FORMAT.format(new Date(timestamp)); accelerometerSensor.csvLogger.writeCSVFile(timestamp + "," + dateTime + "," - + readingX + "," + readingY + "," + readingZ + ",0.0,0.0"); - sensorData = new AccelerometerData(timestamp, block, accelerometerValue_X, accelerometerValue_Y, accelerometerValue_Z, 0.0, 0.0); + + readingX + "," + readingY + "," + readingZ + "," + ",0.0,0.0"); + sensorData = new AccelerometerData(timestamp, block, accelerometerViewFragments.get(0).getCurrentValue(), accelerometerViewFragments.get(1).getCurrentValue(), accelerometerViewFragments.get(2).getCurrentValue(), 0.0, 0.0); } accelerometerSensor.recordSensorData(sensorData); } else { @@ -715,75 +401,27 @@ private void writeLogToFile(long timestamp, float readingX, float readingY, floa } private void visualizeData() { - boolean toWrite = false; - long timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - if (timeElapsed != previousTimeElapsed_X) { - toWrite = true; - previousTimeElapsed_X = timeElapsed; - entriesX.add(new Entry((float) timeElapsed, accelerometerValue_X)); - - LineDataSet dataSet = new LineDataSet(entriesX, getString(R.string.accelerometer)); - LineData data = new LineData(dataSet); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[0]); - - x_chart_accelerometer.setData(data); - x_chart_accelerometer.notifyDataSetChanged(); - x_chart_accelerometer.setVisibleXRangeMaximum(3); - x_chart_accelerometer.moveViewToX(data.getEntryCount()); - x_chart_accelerometer.invalidate(); - } - - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - if (timeElapsed != previousTimeElapsed_Y) { - toWrite = true; - previousTimeElapsed_Y = timeElapsed; - entriesY.add(new Entry((float) timeElapsed, accelerometerValue_Y)); - - LineDataSet dataSet = new LineDataSet(entriesY, getString(R.string.accelerometer)); - LineData data = new LineData(dataSet); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[1]); - - y_chart_accelerometer.setData(data); - y_chart_accelerometer.notifyDataSetChanged(); - y_chart_accelerometer.setVisibleXRangeMaximum(3); - y_chart_accelerometer.moveViewToX(data.getEntryCount()); - y_chart_accelerometer.invalidate(); - } - timeElapsed = (System.currentTimeMillis() - startTime) / 1000; - if (timeElapsed != previousTimeElapsed_Z) { - toWrite = true; - previousTimeElapsed_Z = timeElapsed; - entriesZ.add(new Entry((float) timeElapsed, accelerometerValue_Z)); - - LineDataSet dataSet = new LineDataSet(entriesZ, getString(R.string.accelerometer)); - LineData data = new LineData(dataSet); - dataSet.setDrawCircles(false); - dataSet.setDrawValues(false); - dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); - dataSet.setLineWidth(1); - dataSet.setColor(colors[2]); - - z_chart_accelerometer.setData(data); - z_chart_accelerometer.notifyDataSetChanged(); - z_chart_accelerometer.setVisibleXRangeMaximum(3); - z_chart_accelerometer.moveViewToX(data.getEntryCount()); - z_chart_accelerometer.invalidate(); - } - if (toWrite) { - long curretTime = System.currentTimeMillis(); - writeLogToFile(curretTime, accelerometerValue_X, accelerometerValue_Y, accelerometerValue_Z); + for (int i = 0; i < accelerometerViewFragments.size(); i++) { + AccelerometerViewFragment fragment = accelerometerViewFragments.get(i); + long timeElapsed = (System.currentTimeMillis() - startTime) / 1000; + if (timeElapsed != fragment.getPreviousTimeElapsed()) { + fragment.setPreviousTimeElapsed(timeElapsed); + fragment.addEntry(new Entry((float) timeElapsed, fragment.getCurrentValue())); + + LineDataSet dataSet = new LineDataSet(fragment.getEntries(), getString(R.string.accelerometer)); + dataSet.setDrawCircles(false); + dataSet.setDrawValues(false); + dataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER); + dataSet.setLineWidth(1); + dataSet.setColor(colors[i]); + LineData data = new LineData(dataSet); + + fragment.setChartData(data); + fragment.setYaxis(highLimit); + } } - y.setAxisMaximum(20); - y.setAxisMinimum(-20); - y.setLabelCount(5); + Long currentTime = System.currentTimeMillis(); + writeLogToFile(currentTime, accelerometerViewFragments.get(0).getCurrentValue(), accelerometerViewFragments.get(1).getCurrentValue(), accelerometerViewFragments.get(2).getCurrentValue()); } private SensorEventListener accelerometerSensorEventListener = new SensorEventListener() { @@ -794,148 +432,47 @@ public void onAccuracyChanged(Sensor sensor, int accuracy) {/**/} @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { - accelerometerValue_X = event.values[0]; - StringBuilder builder_x = new StringBuilder(); - builder_x.append(df.format(accelerometerValue_X)); - builder_x.append(" "); - builder_x.append(getResources().getString(R.string.meters_per_sec_text)); - x_accel_value.setText(Html.fromHtml(builder_x.toString())); - if (accelerometerValue_X > currentMaxX) { - builder_x.insert(0, getResources().getString(R.string.text_max)); - builder_x.insert(3, " "); - x_accel_max.setText(Html.fromHtml(builder_x.toString())); - currentMaxX = accelerometerValue_X; - } else if (accelerometerValue_X < currentMinX) { - builder_x.insert(0, getResources().getString(R.string.text_min)); - builder_x.insert(3, " "); - x_accel_min.setText(Html.fromHtml(builder_x.toString())); - currentMinX = accelerometerValue_X; - } - accelerometerValue_Y = event.values[1]; - StringBuilder builder_y = new StringBuilder(); - builder_y.append(df.format(accelerometerValue_Y)); - builder_y.append(" "); - builder_y.append(getResources().getString(R.string.meters_per_sec_text)); - y_accel_value.setText(Html.fromHtml(builder_y.toString())); - if (accelerometerValue_Y > currentMaxY) { - builder_y.insert(0, getResources().getString(R.string.text_max)); - builder_y.insert(3, " "); - y_accel_max_text.setText(Html.fromHtml(builder_y.toString())); - currentMaxY = accelerometerValue_Y; - } else if (accelerometerValue_Y < currentMinY) { - builder_y.insert(0, getResources().getString(R.string.text_min)); - builder_y.insert(3, " "); - y_accel_min_text.setText(Html.fromHtml(builder_y.toString())); - currentMinY = accelerometerValue_Y; - } - accelerometerValue_Z = event.values[2]; - StringBuilder builder_z = new StringBuilder(); - builder_z.append(df.format(accelerometerValue_Z)); - builder_z.append(" "); - builder_z.append(getResources().getString(R.string.meters_per_sec_text)); - z_accel_value.setText(Html.fromHtml(builder_z.toString())); - - if (accelerometerValue_Z > currentMaxZ) { - builder_z.insert(0, getResources().getString(R.string.text_max)); - builder_z.insert(3, " "); - z_accel_max_text.setText(Html.fromHtml(builder_z.toString())); - currentMaxZ = accelerometerValue_Z; - } else if (accelerometerValue_Z < currentMinZ) { - builder_z.insert(0, getResources().getString(R.string.text_min)); - builder_z.insert(3, " "); - z_accel_min_text.setText(Html.fromHtml(builder_z.toString())); - currentMinZ = accelerometerValue_Z; + for (int i = 0; i < accelerometerViewFragments.size(); i++) { + AccelerometerViewFragment fragment = accelerometerViewFragments.get(i); + fragment.setCurrentValue(event.values[i]); + StringBuilder builder = new StringBuilder(); + builder.append(df.format(fragment.getCurrentValue())); + builder.append(" "); + builder.append(getResources().getString(R.string.acceleration_unit)); + fragment.setAccelerationValue(Html.fromHtml(builder.toString())); + + if (fragment.getCurrentValue() > fragment.getCurrentMax()) { + builder.insert(0, getResources().getString(R.string.text_max)); + builder.insert(3, " "); + fragment.setAccelerationMax(Html.fromHtml(builder.toString())); + fragment.setCurrentMax(fragment.getCurrentValue()); + } else if (fragment.getCurrentValue() < fragment.getCurrentMin()) { + builder.insert(0, getResources().getString(R.string.text_min)); + builder.insert(3, " "); + fragment.setAccelerationMin(Html.fromHtml(builder.toString())); + fragment.setCurrentMin(fragment.getCurrentValue()); + } } } } }; private void resetInstrumentData() { - accelerometerValue_X = 0; - accelerometerValue_Y = 0; - accelerometerValue_Z = 0; - count = 0; - currentMinX = Integer.MAX_VALUE; - currentMaxX = Integer.MIN_VALUE; - currentMinY = Integer.MAX_VALUE; - currentMaxY = Integer.MIN_VALUE; - currentMinZ = Integer.MAX_VALUE; - currentMaxZ = Integer.MIN_VALUE; - sum = 0; - sensor = null; - startTime = System.currentTimeMillis(); - z_axis_image.setImageResource(R.drawable.phone_z_axis); - y_axis.setImageResource(R.drawable.phone_y_axis); - x_axis.setImageResource(R.drawable.phone_x_axis); - entriesX.clear(); - entriesZ.clear(); - entriesY.clear(); + for (AccelerometerViewFragment fragment : accelerometerViewFragments) { + fragment.clear(); + } } - private void initiateAccelerometerSensor(int type) { - ACCELEROMETER_SENSOR s = ACCELEROMETER_SENSOR.values()[type]; + private void initiateAccelerometerSensor() { resetInstrumentData(); - ScienceLab scienceLab; - switch (s) { - case INBUILT_SENSOR: - sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); - sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); - if (sensor == null) { - Toast.makeText(getContext(), getResources().getString(R.string.no_accelerometer_sensor), Toast.LENGTH_LONG).show(); - } else { - float max = sensor.getMaximumRange(); - sensorManager.registerListener(accelerometerSensorEventListener, - sensor, SensorManager.SENSOR_DELAY_FASTEST); - } - break; - case BH1750_SENSOR: - scienceLab = ScienceLabCommon.scienceLab; - if (scienceLab.isConnected()) { - ArrayList data; - try { - I2C i2c = scienceLab.i2c; - data = i2c.scan(null); - if (data.contains(0x23)) { - BH1750 sensorBH1750 = new BH1750(i2c); - sensorBH1750.setRange(String.valueOf(gain)); - sensorType = 0; - } else { - Toast.makeText(getContext(), getResources().getText(R.string.sensor_not_connected_tls), Toast.LENGTH_SHORT).show(); - sensorType = 0; - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - } else { - Toast.makeText(getContext(), getResources().getText(R.string.device_not_found), Toast.LENGTH_SHORT).show(); - sensorType = 0; - } - break; - case TSL2561_SENSOR: - scienceLab = ScienceLabCommon.scienceLab; - if (scienceLab.isConnected()) { - try { - I2C i2c = scienceLab.i2c; - ArrayList data; - data = i2c.scan(null); - if (data.contains(0x39)) { - TSL2561 sensorTSL2561 = new TSL2561(i2c, scienceLab); - sensorTSL2561.setGain(String.valueOf(gain)); - sensorType = 2; - } else { - Toast.makeText(getContext(), getResources().getText(R.string.sensor_not_connected_tls), Toast.LENGTH_SHORT).show(); - sensorType = 0; - } - } catch (IOException | InterruptedException e) { - e.printStackTrace(); - } - } else { - Toast.makeText(getContext(), getResources().getText(R.string.device_not_found), Toast.LENGTH_SHORT).show(); - sensorType = 0; - } - break; - default: - break; + sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); + sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); + if (sensor == null) { + Toast.makeText(getContext(), getResources().getString(R.string.no_accelerometer_sensor), Toast.LENGTH_LONG).show(); + } else { + sensorManager.registerListener(accelerometerSensorEventListener, + sensor, SensorManager.SENSOR_DELAY_FASTEST); } + } } \ No newline at end of file diff --git a/app/src/main/java/io/pslab/fragment/AccelerometerViewFragment.java b/app/src/main/java/io/pslab/fragment/AccelerometerViewFragment.java new file mode 100644 index 000000000..fa68ac38b --- /dev/null +++ b/app/src/main/java/io/pslab/fragment/AccelerometerViewFragment.java @@ -0,0 +1,187 @@ +package io.pslab.fragment; + +import android.content.Context; +import android.graphics.Color; +import android.os.Bundle; +import android.support.v4.app.Fragment; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import com.github.mikephil.charting.charts.LineChart; +import com.github.mikephil.charting.components.Legend; +import com.github.mikephil.charting.components.XAxis; +import com.github.mikephil.charting.components.YAxis; +import com.github.mikephil.charting.data.Entry; +import com.github.mikephil.charting.data.LineData; + +import java.util.ArrayList; + +import io.pslab.R; + +public class AccelerometerViewFragment extends Fragment { + + private TextView accelerationValue, accelerationMin, accelerationMax; + private LineChart accelerationChart; + private ImageView accelerationAxisImage; + private YAxis y; + private float currentMax = Integer.MIN_VALUE; + private float currentMin = Integer.MAX_VALUE; + private float currentValue = 0; + private ArrayList entries; + private long startTime; + private static int updatePeriod = 100; + private long previousTimeElapsed = (System.currentTimeMillis() - startTime) / updatePeriod; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + } + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View rootView = inflater.inflate(R.layout.accelerometer_list_item, container, false); + + this.accelerationValue = rootView.findViewById(R.id.acceleration_value); + this.accelerationMax = rootView.findViewById(R.id.acceleration_max_text); + this.accelerationMin = rootView.findViewById(R.id.acceleration_min_text); + this.accelerationChart = rootView.findViewById(R.id.chart_accelerometer); + this.accelerationAxisImage = rootView.findViewById(R.id.acceleration_axis_image); + this.entries = new ArrayList<>(); + return rootView; + } + + @Override + public void onAttach(Context context) { + super.onAttach(context); + } + + @Override + public void onDetach() { + super.onDetach(); + } + + public ImageView getAccelerationAxisImage() { + return accelerationAxisImage; + } + + public float getCurrentMax() { + return currentMax; + } + + public void setCurrentMax(float currentMax) { + this.currentMax = currentMax; + } + + public float getCurrentMin() { + return currentMin; + } + + public void setCurrentMin(float currentMin) { + this.currentMin = currentMin; + } + + public float getCurrentValue() { + return currentValue; + } + + public void setCurrentValue(float currentValue) { + this.currentValue = currentValue; + } + + public void setUp() { + XAxis x = this.accelerationChart.getXAxis(); + this.y = this.accelerationChart.getAxisLeft(); + YAxis y2 = this.accelerationChart.getAxisRight(); + + this.accelerationChart.setTouchEnabled(true); + this.accelerationChart.setHighlightPerDragEnabled(true); + this.accelerationChart.setDragEnabled(true); + this.accelerationChart.setScaleEnabled(true); + this.accelerationChart.setDrawGridBackground(false); + this.accelerationChart.setPinchZoom(true); + this.accelerationChart.setScaleYEnabled(true); + this.accelerationChart.setBackgroundColor(Color.BLACK); + this.accelerationChart.getDescription().setEnabled(false); + + LineData data = new LineData(); + this.accelerationChart.setData(data); + + Legend l = this.accelerationChart.getLegend(); + l.setForm(Legend.LegendForm.LINE); + l.setTextColor(Color.WHITE); + + x.setTextColor(Color.WHITE); + x.setDrawGridLines(true); + x.setAvoidFirstLastClipping(true); + x.setDrawLabels(false); + + this.y.setTextColor(Color.WHITE); + this.y.setAxisMaximum(currentMax); + this.y.setAxisMinimum(currentMin); + this.y.setDrawGridLines(true); + this.y.setLabelCount(10); + + y2.setDrawGridLines(false); + y2.setMaxWidth(0); + } + + public void addEntry(Entry entry) { + this.entries.add(entry); + } + + public ArrayList getEntries() { + return this.entries; + } + + public void clearEntry() { + this.entries.clear(); + } + + public void setAccelerationValue(CharSequence value) { + this.accelerationValue.setText(value); + } + + public void setAccelerationMax(CharSequence value) { + this.accelerationMax.setText(value); + } + + public void setAccelerationMin(CharSequence value) { + this.accelerationMin.setText(value); + } + + public void setYaxis(float maxLimit) { + this.y.setAxisMaximum(maxLimit); + this.y.setAxisMinimum(-maxLimit); + this.y.setLabelCount(5); + } + + public void setChartData(LineData data) { + this.accelerationChart.setData(data); + this.accelerationChart.notifyDataSetChanged(); + this.accelerationChart.setVisibleXRangeMaximum(3); + this.accelerationChart.moveViewToX(data.getEntryCount()); + this.accelerationChart.invalidate(); + } + + public void clear() { + this.currentMax = Integer.MIN_VALUE; + this.currentMin = Integer.MAX_VALUE; + this.entries.clear(); + this.accelerationChart.clear(); + this.accelerationChart.invalidate(); + this.startTime = System.currentTimeMillis(); + } + + public long getPreviousTimeElapsed() { + return previousTimeElapsed; + } + + public void setPreviousTimeElapsed(long previousTimeElapsed) { + this.previousTimeElapsed = previousTimeElapsed; + } +} diff --git a/app/src/main/java/io/pslab/fragment/ChannelParametersFragment.java b/app/src/main/java/io/pslab/fragment/ChannelParametersFragment.java index 4c673305f..4d629c99f 100644 --- a/app/src/main/java/io/pslab/fragment/ChannelParametersFragment.java +++ b/app/src/main/java/io/pslab/fragment/ChannelParametersFragment.java @@ -226,12 +226,16 @@ public void onItemSelected(AdapterView parent, View view, int position, long micSelectedPosition = position; if (position == 1) { ((OscilloscopeActivity) getActivity()).isInBuiltMicSelected = false; - if (checkBoxMIC.isChecked()) + if (checkBoxMIC.isChecked()) { ((OscilloscopeActivity) getActivity()).isMICSelected = true; + ((OscilloscopeActivity) getActivity()).isAudioInputSelected = true; + } } else { ((OscilloscopeActivity) getActivity()).isMICSelected = false; - if (checkBoxMIC.isChecked()) + if (checkBoxMIC.isChecked()) { ((OscilloscopeActivity) getActivity()).isInBuiltMicSelected = true; + ((OscilloscopeActivity) getActivity()).isAudioInputSelected = true; + } } } @@ -265,8 +269,10 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (micSelectedPosition == 1) { + ((OscilloscopeActivity) getActivity()).isAudioInputSelected = isChecked; ((OscilloscopeActivity) getActivity()).isMICSelected = isChecked; } else if (micSelectedPosition == 2) { + ((OscilloscopeActivity) getActivity()).isAudioInputSelected = isChecked; // check for RECORD_AUDIO permission if has then change boolean if (isChecked) if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { @@ -276,6 +282,8 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } else ((OscilloscopeActivity) getActivity()).isInBuiltMicSelected = false; + } else { + ((OscilloscopeActivity) getActivity()).isAudioInputSelected = false; } } }); diff --git a/app/src/main/java/io/pslab/fragment/GyroscopeDataFragment.java b/app/src/main/java/io/pslab/fragment/GyroscopeDataFragment.java index 16e203046..59075aa6e 100644 --- a/app/src/main/java/io/pslab/fragment/GyroscopeDataFragment.java +++ b/app/src/main/java/io/pslab/fragment/GyroscopeDataFragment.java @@ -120,20 +120,10 @@ public void onResume() { resetInstrumentData(); playRecordedData(); } else if (gyroSensor.viewingData) { - if (sensorManager != null) { - recordedGyroArray = new ArrayList<>(); - resetInstrumentData(); - plotAllRecordedData(); - } - else { - gyroscopeViewFragments.clear(); - rootView.findViewById(R.id.gyroscope_x_axis_fragment).setVisibility(View.INVISIBLE); - rootView.findViewById(R.id.gyroscope_y_axis_fragment).setVisibility(View.INVISIBLE); - rootView.findViewById(R.id.gyroscope_z_axis_fragment).setVisibility(View.INVISIBLE); - noSensorText.setText(getResources().getString(R.string.no_data_recorded_gyro)); - noSensorText.setAllCaps(true); - gyroLinearLayout.addView(noSensorText); - } + recordedGyroArray = new ArrayList<>(); + resetInstrumentData(); + plotAllRecordedData(); + } else if (!gyroSensor.isRecording) { updateGraphs(); initiateGyroSensor(); @@ -150,8 +140,7 @@ public void onDestroyView() { } if (sensorManager != null) { sensorManager.unregisterListener(gyroScopeSensorEventListener); - } - else { + } else { gyroLinearLayout.removeView(noSensorText); } } @@ -484,13 +473,26 @@ private void resetInstrumentData() { private void initiateGyroSensor() { resetInstrumentData(); sensorManager = (SensorManager) getContext().getSystemService(SENSOR_SERVICE); - sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); - if (sensor == null) { - Toast.makeText(getContext(), getResources().getString(R.string.no_gyroscope_sensor), Toast.LENGTH_LONG).show(); + if (sensorManager == null) { + noSensorLayoutUpdate(); } else { - sensorManager.registerListener(gyroScopeSensorEventListener, - sensor, SensorManager.SENSOR_DELAY_FASTEST); + sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); + if (sensor == null) { + Toast.makeText(getContext(), getResources().getString(R.string.no_gyroscope_sensor), Toast.LENGTH_LONG).show(); + } else { + sensorManager.registerListener(gyroScopeSensorEventListener, + sensor, SensorManager.SENSOR_DELAY_FASTEST); + } } + } + private void noSensorLayoutUpdate() { + gyroscopeViewFragments.clear(); + rootView.findViewById(R.id.gyroscope_x_axis_fragment).setVisibility(View.GONE); + rootView.findViewById(R.id.gyroscope_y_axis_fragment).setVisibility(View.GONE); + rootView.findViewById(R.id.gyroscope_z_axis_fragment).setVisibility(View.GONE); + noSensorText.setText(getResources().getString(R.string.no_data_recorded_gyro)); + noSensorText.setAllCaps(true); + gyroLinearLayout.addView(noSensorText); } } diff --git a/app/src/main/java/io/pslab/fragment/GyroscopeSettingsFragment.java b/app/src/main/java/io/pslab/fragment/GyroscopeSettingsFragment.java index 6b49a194d..32c908ede 100644 --- a/app/src/main/java/io/pslab/fragment/GyroscopeSettingsFragment.java +++ b/app/src/main/java/io/pslab/fragment/GyroscopeSettingsFragment.java @@ -15,9 +15,9 @@ public class GyroscopeSettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { public static final String KEY_INCLUDE_LOCATION = "include_location_sensor_data"; - public static final String KEY_UPDATE_PERIOD = "setting_lux_update_period"; - public static final String KEY_HIGH_LIMIT = "setting_lux_high_limit"; - public static final String KEY_GYROSCOPE_SENSOR_GAIN = "setting_lux_sensor_gain"; + public static final String KEY_UPDATE_PERIOD = "setting_gyro_update_period"; + public static final String KEY_HIGH_LIMIT = "setting_gyro_high_limit"; + public static final String KEY_GYROSCOPE_SENSOR_GAIN = "setting_gyro_sensor_gain"; private PSLabPermission psLabPermission; diff --git a/app/src/main/java/io/pslab/fragment/GyroscopeViewFragment.java b/app/src/main/java/io/pslab/fragment/GyroscopeViewFragment.java index 148e2a84b..d3d7d281e 100644 --- a/app/src/main/java/io/pslab/fragment/GyroscopeViewFragment.java +++ b/app/src/main/java/io/pslab/fragment/GyroscopeViewFragment.java @@ -54,22 +54,6 @@ public ImageView getGyroAxisImage() { return gyroAxisImage; } - public LineChart getGyroChart() { - return gyroChart; - } - - public TextView getGyroMax() { - return gyroMax; - } - - public TextView getGyroMin() { - return gyroMin; - } - - public TextView getGyroValue() { - return gyroValue; - } - public void setUp() { XAxis x = this.gyroChart.getXAxis(); this.y = this.gyroChart.getAxisLeft(); diff --git a/app/src/main/java/io/pslab/fragment/XYPlotFragment.java b/app/src/main/java/io/pslab/fragment/XYPlotFragment.java index 5dcd389c3..fe1622ddd 100644 --- a/app/src/main/java/io/pslab/fragment/XYPlotFragment.java +++ b/app/src/main/java/io/pslab/fragment/XYPlotFragment.java @@ -22,7 +22,6 @@ public class XYPlotFragment extends Fragment { private Spinner spinnerChannelSelect1; private Spinner spinnerChannelSelect2; private CheckBox checkBoxXYPlot; - private Button viewButton; public static XYPlotFragment newInstance() { return new XYPlotFragment(); @@ -36,10 +35,10 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, spinnerChannelSelect1 = v.findViewById(R.id.spinner_channel_select_xy1); spinnerChannelSelect2 = v.findViewById(R.id.spinner_channel_select_xy2); checkBoxXYPlot = v.findViewById(R.id.checkBox_enable_xy_xy); - viewButton = v.findViewById(R.id.button_view_xy); spinnerChannelSelect1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int position, long l) { + ((OscilloscopeActivity) getActivity()).xyPlotAxis1 = channels[position]; if (((OscilloscopeActivity) getActivity()).isXYPlotSelected) { ((OscilloscopeActivity) getActivity()).setXAxisLabel(channels[position]); ((OscilloscopeActivity) getActivity()).xAxisLabelUnit.setText("(V)"); @@ -56,6 +55,7 @@ public void onNothingSelected(AdapterView adapterView) { @Override public void onItemSelected(AdapterView adapterView, View view, int position, long l) { + ((OscilloscopeActivity) getActivity()).xyPlotAxis2 = channels[position]; if (((OscilloscopeActivity) getActivity()).isXYPlotSelected) { ((OscilloscopeActivity) getActivity()).setLeftYAxisLabel(channels[position]); } @@ -110,13 +110,6 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { } }); - viewButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - ((OscilloscopeActivity) getActivity()).viewIsClicked = true; - } - }); - return v; } } diff --git a/app/src/main/java/io/pslab/models/AccelerometerData.java b/app/src/main/java/io/pslab/models/AccelerometerData.java index 89b543a11..932ab9ec8 100644 --- a/app/src/main/java/io/pslab/models/AccelerometerData.java +++ b/app/src/main/java/io/pslab/models/AccelerometerData.java @@ -69,6 +69,10 @@ public void setAccelerometerZ(float accelerometer) { this.accelerometer_Z = accelerometer_Z; } + public float[] getAccelerometer(){ + return new float[]{this.accelerometer_X, this.accelerometer_Y, this.accelerometer_Z}; + } + public double getLat() { return lat; } diff --git a/app/src/main/res/layout/accelerometer_list_item.xml b/app/src/main/res/layout/accelerometer_list_item.xml new file mode 100644 index 000000000..d8e9c87db --- /dev/null +++ b/app/src/main/res/layout/accelerometer_list_item.xml @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_robotic_arm.xml b/app/src/main/res/layout/activity_robotic_arm.xml index 5ba516f79..51b168343 100644 --- a/app/src/main/res/layout/activity_robotic_arm.xml +++ b/app/src/main/res/layout/activity_robotic_arm.xml @@ -1,135 +1,147 @@ - - - - - + android:layout_height="match_parent" + android:keepScreenOn="true" + android:orientation="vertical" + android:weightSum="1" + android:id="@+id/robotic_arm_coordinator"> - + - + android:layout_height="wrap_content" + android:orientation="horizontal" + android:scrollbars="horizontal"> - + + - - -