data = LocalDataLog.with().getBlockOfSoundRecords(block.getBlock());
- JSONArray array = new JSONArray();
- for (SoundData d : data) {
- try {
- JSONObject i = new JSONObject();
- i.put("date", CSVLogger.FILE_NAME_FORMAT.format(d.getTime()));
- i.put("dB", d.getdB());
- i.put("lon", d.getLon());
- i.put("lat", d.getLat());
- if (d.getLat() != 0.0 && d.getLon() != 0.0) array.put(i);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- setMapDataToIntent(array);
- }
- }
-
- private void setMapDataToIntent(JSONArray array) {
- Intent map = new Intent(context, MapsActivity.class);
- if (array.length() > 0) {
- map.putExtra("hasMarkers", true);
- map.putExtra("markers", array.toString());
- context.startActivity(map);
- } else {
- map.putExtra("hasMarkers", false);
- CustomSnackBar.showSnackBar(context.findViewById(android.R.id.content),
- context.getString(R.string.no_location_data), null, null, Snackbar.LENGTH_LONG);
- }
- }
-
- public class ViewHolder extends RecyclerView.ViewHolder {
- private TextView sensor, dateTime;
- private ImageView deleteIcon, mapIcon, tileIcon;
- private CardView cardView;
-
- public ViewHolder(View itemView) {
- super(itemView);
- dateTime = itemView.findViewById(R.id.date_time);
- sensor = itemView.findViewById(R.id.sensor_name);
- deleteIcon = itemView.findViewById(R.id.delete_item);
- mapIcon = itemView.findViewById(R.id.map_item);
- tileIcon = itemView.findViewById(R.id.sensor_tile_icon);
- cardView = itemView.findViewById(R.id.data_item_card);
- }
- }
-}
diff --git a/app/src/main/java/io/pslab/communication/AnalyticsClass.java b/app/src/main/java/io/pslab/communication/AnalyticsClass.java
deleted file mode 100644
index 8a0019ed5..000000000
--- a/app/src/main/java/io/pslab/communication/AnalyticsClass.java
+++ /dev/null
@@ -1,602 +0,0 @@
-package io.pslab.communication;
-
-import android.util.Log;
-
-import org.apache.commons.math3.analysis.ParametricUnivariateFunction;
-import org.apache.commons.math3.complex.Complex;
-import org.apache.commons.math3.fitting.CurveFitter;
-import org.apache.commons.math3.optim.nonlinear.vector.jacobian.LevenbergMarquardtOptimizer;
-import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
-import org.apache.commons.math3.transform.DftNormalization;
-import org.apache.commons.math3.transform.FastFourierTransformer;
-import org.apache.commons.math3.transform.TransformType;
-
-import io.pslab.filters.BandstopFilter;
-import io.pslab.filters.Lfilter;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import static java.lang.Math.cos;
-import static org.apache.commons.lang3.math.NumberUtils.min;
-import static org.apache.commons.lang3.math.NumberUtils.max;
-import static org.apache.commons.math3.util.FastMath.abs;
-import static org.apache.commons.math3.util.FastMath.exp;
-import static org.apache.commons.math3.util.FastMath.sin;
-
-/**
- * Created by akarshan on 5/13/17.
- *
- * Unlike python, the curve fitting and the fourier transorm methods only accepts the arrays
- * of length of power of 2.
- *
- * JAVA equivalent of scipy.fftpack.rfft, scipy.fftpack.rfftfreq and scipy.fftpack.fftfreq functions are'nt
- * available so they are been added in this class by the name fftToRfft, rfftFrequency and fftFrequency
- * respectively.
- *
- * The fit functions have passed some dry tests but required to be tested with data points generated by PSLab.
- *
- */
-
-@SuppressWarnings("ALL")
-public class AnalyticsClass {
-
- // todo : check the accuracy of the all the curve fitting methods with data points generated by PSLab
- //-------------------------- Exponential Fit ----------------------------------------//
-
- private ParametricUnivariateFunction exponentialParametricUnivariateFunction = new ParametricUnivariateFunction() {
- @Override
- public double value(double x, double... parameters) {
- double a = parameters[0];
- double b = parameters[1];
- double c = parameters[2];
- return a * exp(-x / b) + c;
- }
-
- @Override
- public double[] gradient(double x, double... parameters) {
- double a = parameters[0];
- double b = parameters[1];
- double c = parameters[2];
-
- return new double[]{
- exp(-x / b),
- (a * exp(-x / b) * x) / (b * b),
- 1
- }; //partial derivatives
- }
- };
-
- public ArrayList fitExponential(double time[], double voltage[]) {
- //length of time and voltage arrays should be in the power of 2
- double size = time.length;
- double v80 = voltage[0] * 0.8;
- double rc = 0;
- double[] vf = new double[time.length];
- for (int k = 0; k < size - 1; k++) {
- if (voltage[k] < v80) {
- rc = time[k] / .223;
- break;
- }
- }
- double[] initialGuess = new double[]{voltage[0], rc, 0};
- //initialize the optimizer and curve fitter.
- LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
- CurveFitter fitter = new CurveFitter(optimizer);
- for (int i = 0; i < time.length; i++)
- fitter.addObservedPoint(time[i], voltage[i]);
- double[] result = fitter.fit(exponentialParametricUnivariateFunction, initialGuess); //result -> the fitted parameters.
- for (int i = 0; i < time.length; i++)
- vf[i] = result[0] * exp(-time[i] / result[1]) + result[2];
- return new ArrayList(Arrays.asList(result, vf));
- }
-
- //-------------------------- Sine Fit ----------------------------------------//
-
- private ParametricUnivariateFunction sineParametricUnivariateFunction = new ParametricUnivariateFunction() {
- @Override
- public double value(double x, double... parameters) {
- double a1 = parameters[0];
- double a2 = parameters[1];
- double a3 = parameters[2];
- double a4 = parameters[3];
- return a4 + a1 * sin(abs(a2 * (2 * Math.PI)) * x + a3);
- }
-
- @Override
- public double[] gradient(double x, double... parameters) {
- double a = parameters[0];
- double b = parameters[1];
- double c = parameters[2];
- double d = parameters[3];
- return new double[]{
- Math.sin(c + 2 * Math.PI * b * x),
- 2 * a * Math.PI * x * cos(c + 2 * b * Math.PI * x),
- a * cos(c + 2 * b * Math.PI * x),
- 1
- };
- }
- };
-
- public double[] sineFit(double[] xReal, double[] yReal) {
- int n = xReal.length;
- int index = 0;
- double[] frequencyArray = new double[]{};
- double[] yReal2 = new double[yReal.length];
- double yHat[];
- double yHatSquare[];
- double max = 0.;
- double returnOffset = 0;
- double frequency;
- double returnFrequency;
- double amplitude;
- double returnAmplitude;
- double phase;
- double returnPhase;
- double[] guess;
- Complex complex[];
-
- double offset = ((double) max(yReal) + (double) min(yReal)) / 2;
- for (int i = 0; i < yReal.length; i++)
- yReal2[i] = yReal[i] - offset;
-
- FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD);
- complex = fastFourierTransformer.transform(yReal2, TransformType.FORWARD);
- yHat = fftToRfft(complex); //yHat is an array of Discrete Fourier transform of a real sequence
- yHatSquare = new double[yHat.length];
- for (int i = 0; i < yHat.length; i++) {
- yHatSquare[i] = Math.pow(yHat[i], 2);
- if (yHatSquare[i] > max) { //yHatSquare is an array square of each element of yHat
- max = yHatSquare[i];
- index = i;
- }
- }
-
- frequencyArray = rfftFrequency(n, (xReal[1] - xReal[0]) / (2 * Math.PI));
- frequency = frequencyArray[index];
- frequency /= (2 * Math.PI);
-
- amplitude = (max(yReal) - min(yReal)) / 2.0;
-
- phase = 0;
-
- LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
- CurveFitter fitter = new CurveFitter(optimizer);
- for (int i = 0; i < n; i++)
- fitter.addObservedPoint(xReal[i], yReal2[i]);
-
- guess = new double[]{amplitude, frequency, phase, 0};
- double[] result = fitter.fit(sineParametricUnivariateFunction, guess);
-
- amplitude = result[0];
- frequency = result[1];
- phase = result[2];
- returnOffset = result[3];
-
- if (frequency < 0)
- Log.v("sineFit", "negative frequency");
-
- returnOffset += offset;
- returnPhase = ((phase) * 180 / (3.14));
- if (amplitude < 0)
- returnPhase -= 180;
- if (returnPhase < 0)
- returnPhase = (returnPhase + 720) % 360;
- returnFrequency = 1e6 * abs(frequency);
- returnAmplitude = abs(amplitude);
- return new double[]{returnAmplitude, returnFrequency, returnOffset, returnPhase};
- }
-
- ParametricUnivariateFunction squareParametricUnivariateFunction = new ParametricUnivariateFunction() {
- @Override
- public double value(double x, double... parameters) {
- double amp = parameters[0];
- double freq = parameters[1];
- double phase = parameters[2];
- double dc = parameters[3]; //dc - duty cycle
- double offset = parameters[4];
- return offset + amp * signalSquare(2 * Math.PI * freq * (x - phase), freq, dc);
- }
-
- @Override
- public double[] gradient(double x, double... parameters) {
- /*partial derivatives w.r.t all the five variables. Square functions are not differentiable
- at finitely many points, still we have used it anyway since the curve fitter uses the value of
- gradients. The values are true except at points where the transition from high to low or low to high
- takes place.*/
- double a = parameters[0]; //unused for partial derivative
- double b = parameters[1];
- double c = parameters[2];
- double d = parameters[3];
- double e = parameters[4]; //unused for partial derivative
-
- return new double[]{
- signalSquare(2 * Math.PI * b * (x - c), b, d), 0, 0, 0, 1
- };
- }
- };
-
- public double[] squareFit(double[] xReal, double[] yReal) {
- int n = xReal.length;
- double mx = max(yReal);
- double mn = min(xReal);
- double offset = (mx + mn) / 2;
- double sumGreaterThanOffset = 0;
- double sumLesserThanOffset = 0;
- double n1 = 0; // count of numbers less than offset
- double n2 = 0; // count of numbers less than offset
- double[] yTmp = new double[yReal.length];
- double[] yReal2 = new double[yReal.length];
- double[] guess;
- double returnOffset;
- double returnFrequency;
- double returnAmplitude;
- double returnPhase;
- double returnDC;
-
- for (int i = 0; i < yReal.length; i++)
- yReal2[i] = yReal[i] - offset;
-
- for (int i = 0; i < yReal.length; i++) {
- if (yReal[i] > offset) {
- sumGreaterThanOffset += yReal[i];
- yTmp[i] = 2;
- n1++;
- } else if (yReal[i] < offset) {
- sumLesserThanOffset += yReal[i];
- yTmp[i] = 0;
- n2++;
- }
- }
-
- double amplitude = (sumGreaterThanOffset / n1) - (sumLesserThanOffset / n2);
- boolean[] bools = new boolean[yTmp.length];
- double tmp;
- for (int i = 0; i < yTmp.length - 1; i++) {
- tmp = yTmp[i + 1] - yTmp[i];
- tmp = abs(tmp);
- bools[i] = tmp > 1;
- }
- double[] edges = new double[bools.length];
- double[] levels = new double[bools.length];
- int j = 0;
- for (int i = 0; i < bools.length; i++) {
- if (bools[i]) {
- edges[j] = xReal[i];
- levels[j] = yTmp[i];
- j++;
- }
- }
-
- double frequency = 1 / (edges[2] - edges[0]);
- double phase = edges[0];
- double dc = 0.5;
-
- if (edges.length >= 4) {
- if (levels[0] == 0)
- dc = (edges[1] - edges[0]) / (edges[2] - edges[0]);
- else {
- dc = (edges[2] - edges[1]) / (edges[3] - edges[1]);
- phase = edges[1];
- }
- }
-
- LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
- CurveFitter fitter = new CurveFitter(optimizer);
- for (int i = 0; i < n; i++)
- fitter.addObservedPoint(xReal[i], yReal2[i]);
-
- guess = new double[]{amplitude, frequency, phase, dc, 0};
- double[] result = fitter.fit(squareParametricUnivariateFunction, guess);
-
- amplitude = result[0];
- frequency = result[1];
- phase = result[2];
- dc = result[3];
- returnOffset = result[4];
-
- if (frequency < 0)
- Log.v("squareFit", "negative frequency");
-
- returnOffset += offset;
- returnFrequency = 1e6 * abs(frequency);
- returnAmplitude = abs(amplitude);
- returnPhase = phase;
- returnDC = dc;
-
- return new double[]{returnAmplitude, returnFrequency, returnPhase, returnDC, returnOffset};
- }
-
- public double findSignalFrequency(double[] voltage, double samplingInterval) {
- int voltageLength = voltage.length;
- double[] frequency;
- double[] amplitude;
- int index = 0;
- double max = 0;
- Complex[] complex;
- DescriptiveStatistics stats = new DescriptiveStatistics();
- for (int i = 0; i < voltageLength; i++)
- stats.addValue(voltage[i]);
- double voltageMean = stats.getMean();
- for (int i = 0; i < voltageLength; i++)
- voltage[i] = voltage[i] - voltageMean; // remove DC component
- frequency = Arrays.copyOfRange(fftFrequency(voltageLength, samplingInterval), 0, voltageLength / 2); // take only the +ive half of the frequncy array
- FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD);
- complex = fastFourierTransformer.transform(voltage, TransformType.FORWARD);
- amplitude = new double[complex.length / 2];
- for (int i = 0; i < complex.length / 2; i++) { // take only the +ive half of the fft result
- amplitude[i] = complex[i].abs() / voltageLength;
- if (amplitude[i] > max) { // search for the tallest peak, the fundamental
- max = amplitude[i];
- index = i;
- }
- }
- double noiseThreshold = 0.1;
- if (max >= noiseThreshold) {
- return frequency[index];
- } else {
- return -1;
- }
- }
-
- public double findFrequency(double[] voltage, double samplingInterval) {
- int voltageLength = voltage.length;
- double[] frequency;
- double[] amplitude;
- int index = 0;
- double max = 0;
- Complex[] complex;
- DescriptiveStatistics stats = new DescriptiveStatistics();
- for (int i = 0; i < voltageLength; i++)
- stats.addValue(voltage[i]);
- double voltageMean = stats.getMean();
- for (int i = 0; i < voltageLength; i++)
- voltage[i] = voltage[i] - voltageMean; // remove DC component
- frequency = Arrays.copyOfRange(fftFrequency(voltageLength, samplingInterval), 0, voltageLength / 2); // take only the +ive half of the frequncy array
- FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD);
- complex = fastFourierTransformer.transform(voltage, TransformType.FORWARD);
- amplitude = new double[complex.length / 2];
- for (int i = 0; i < complex.length / 2; i++) { // take only the +ive half of the fft result
- amplitude[i] = complex[i].abs() / voltageLength;
- if (amplitude[i] > max) { // search for the tallest peak, the fundamental
- max = amplitude[i];
- index = i;
- }
- }
- return frequency[index];
- }
-
- public ArrayList amplitudeSpectrum(double[] voltage, int samplingInterval, int nHarmonics) {
- int voltageLength = voltage.length;
- Complex[] complex;
- double[] amplitude;
- double[] newAmplitude;
- int index = 0;
- double max = 0;
- double[] frequency = Arrays.copyOfRange(fftFrequency(voltageLength, samplingInterval), 0, voltageLength / 2); // take only the +ive half of the frequncy array
- FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD);
- complex = fastFourierTransformer.transform(voltage, TransformType.FORWARD);
- amplitude = new double[complex.length / 2];
- for (int i = 0; i < complex.length / 2; i++) { // take only the +ive half of the fft result
- amplitude[i] = complex[i].abs() / voltageLength;
- if (amplitude[i] > max) { // search for the tallest peak, the fundamental
- max = amplitude[i];
- index = i;
- }
- }
- if (index == 0) { // DC component is dominating
- max = 0;
- newAmplitude = Arrays.copyOfRange(amplitude, 4, amplitude.length); // skip frequencies close to zero
- for (int i = 0; i < newAmplitude.length; i++) {
- if (newAmplitude[i] > max) {
- max = newAmplitude[i];
- index = i;
- }
- }
- }
- return new ArrayList(Arrays.asList( // restrict to 'nHarmonics' harmonics
- Arrays.copyOfRange(frequency, index * nHarmonics, frequency.length),
- Arrays.copyOfRange(amplitude, index * nHarmonics, amplitude.length)
- ));
- }
-
- //-------------------------- Damped Sine Fit ----------------------------------------//
-
- public ParametricUnivariateFunction dampedSineParametricUnivariateFunction = new ParametricUnivariateFunction() {
- @Override
- public double value(double x, double... parameters) {
- double amplitude = parameters[0];
- double frequency = parameters[1];
- double phase = parameters[2];
- double offset = parameters[3];
- double damp = parameters[4];
- return offset + amplitude * exp(-damp * x) * sin(Math.abs(frequency) * x + phase);
- }
-
- @Override
- public double[] gradient(double x, double... parameters) {
- double amplitude = parameters[0];
- double frequency = parameters[1];
- double phase = parameters[2];
- double offset = parameters[3];
- double damp = parameters[4];
- return new double[]{
- exp(-damp * x) * sin(x * frequency + phase),
- amplitude * exp(-damp * x) * x * cos(x * frequency + phase),
- amplitude * exp(-damp * x) * cos(x * frequency + phase),
- -amplitude * exp(-damp * x) * x * sin(x * frequency + phase),
- 1
- };
- }
- };
-
-
- public double[] getGuessValues(double xReal[], double yReal[], String function) {
- if (function.equals("sine") || function.equals("damped sine")) {
- int n = xReal.length;
- Complex[] complex;
- double[] yReal2 = new double[yReal.length];
- double[] yHatSquare;
- double[] yHat;
- double[] frequencyArray;
- double frequency;
- double amplitude;
- double phase;
- double max = 0;
- int index = 0;
- DescriptiveStatistics stats = new DescriptiveStatistics();
- for (int i = 0; i < yReal.length; i++)
- stats.addValue(yReal[i]);
- double offset = stats.getMean();
- for (int i = 0; i < yReal.length; i++)
- yReal2[i] = yReal[i] - offset;
- FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD);
- complex = fastFourierTransformer.transform(yReal, TransformType.FORWARD);
- yHat = fftToRfft(complex);
- yHatSquare = new double[yHat.length];
- for (int i = 0; i < yHat.length; i++) {
- yHatSquare[i] = Math.pow(yHat[i], 2);
- if (yHatSquare[i] > max) { //yHatSquare is an array square of each element of yHat
- max = yHatSquare[i];
- index = i;
- }
- }
- frequencyArray = rfftFrequency(n, (xReal[1] - xReal[0]) / 2);
- frequency = frequencyArray[index];
- amplitude = (max(yReal) - min(yReal)) / 2.0;
- phase = 0;
- if (function.equals("sine"))
- return new double[]{amplitude, frequency, phase, offset};
- if (function.equals("damped sine"))
- return new double[]{amplitude, frequency, phase, offset, 0};
- }
- return null;
- }
-
- public double[] arbitFit(double[] xReal, double[] yReal, ParametricUnivariateFunction function, double[] guessValues) {
- int n = xReal.length;
- LevenbergMarquardtOptimizer optimizer = new LevenbergMarquardtOptimizer();
- CurveFitter fitter = new CurveFitter(optimizer);
- for (int i = 0; i < n; i++)
- fitter.addObservedPoint(xReal[i], yReal[i]);
- double[] result = fitter.fit(function, guessValues);
- return result;
- }
-
- ArrayList butterNotch(double lowCut, double highCut, double fs, int order) {
- double nyq = 0.5 * fs;
- double low = lowCut / nyq;
- double high = highCut / nyq;
- BandstopFilter bandstopFilter = new BandstopFilter(order, new double[]{low, high});
- return bandstopFilter.abGetter();
- }
-
- double[] butterNotchFilter(double[] data, double lowCut, double highCut, double fs, int order) {
- ArrayList arrayList = butterNotch(lowCut, highCut, fs, order);
- double[] b = arrayList.get(0);
- double[] a = arrayList.get(1);
- Lfilter lfilter = new Lfilter();
- return lfilter.filter(b, a, data);
- }
-
- public ArrayList fft(double[] signal, double samplingInterval) {
- /*
- Returns positive half of the Fourier transform of the signal.
- Sampling interval 'samplingInterval', in milliseconds
- */
- int ns = signal.length;
- Complex[] complex;
- double[] terms;
- double[] frequencyArray;
- double[] x;
- double[] y;
- if (ns % 2 == 1) {
- ns = ns - 1;
- signal = Arrays.copyOfRange(signal, 0, ns);
- }
- FastFourierTransformer fastFourierTransformer = new FastFourierTransformer(DftNormalization.STANDARD);
- complex = fastFourierTransformer.transform(signal, TransformType.FORWARD);
- terms = new double[complex.length];
- for (int i = 0; i < complex.length; i++)
- terms[i] = complex[i].abs() / ns;
- frequencyArray = fftFrequency(ns, samplingInterval);
- x = Arrays.copyOfRange(frequencyArray, 0, ns / 2);
- y = Arrays.copyOfRange(terms, 0, ns / 2);
- return new ArrayList(Arrays.asList(x, y));
- }
-
- public double[] rfftFrequency(int n, double space) {
- /*
- The returned array contains the frequency bins in
- cycles/unit (with zero at the start) given a window length `n` and a
- sample spacing `space`
- */
- double[] returnArray = new double[n + 1];
- for (int i = 0; i < n + 1; i++) {
- returnArray[i] = Math.floor(i / 2) / (n * space);
- }
- return Arrays.copyOfRange(returnArray, 1, returnArray.length);
- }
-
- public double[] fftFrequency(int n, double space) {
- /*
- Return the Discrete Fourier Transform sample frequencies.
- The returned array contains the frequency bin centers in cycles
- per unit of the sample spacing (with zero at the start). For instance, if
- the sample spacing is in seconds, then the frequency unit is cycles/second.
- Given a window length `n` and a sample spacing `spacing`.
- */
- double value = 1.0 / (n * space);
- int N = Math.floorDiv(n - 1, 2) + 1;
- double[] results = new double[n];
- for (int i = 0; i < N; i++) {
- results[i] = i;
- results[i] = results[i] * value;
- }
- int j = N;
- for (int i = -Math.floorDiv(n, 2); i < 0; i++) {
-
- results[j] = i;
- results[j] = results[j] * value;
- j++;
- }
- return results;
- }
-
- public double[] fftToRfft(Complex[] complex) {
- //The returned array contains Discrete Fourier transform of a real sequence.
- double[] real = new double[complex.length];
- double[] imaginary = new double[complex.length];
- double[] result = new double[complex.length];
- int j = 0;
- int k = 0;
- int l = 0;
- for (int i = 0; i < complex.length / 2 + 1; i++) {
- real[i] = complex[i].getReal();
- imaginary[i] = complex[i].getImaginary();
- }
-
- for (int i = 0; i < complex.length / 2 + 1; i++) {
- if (real[j] == 0.0 && imaginary[k] == 0) {
- result[l++] = 0.0;
- j++;
- k++;
- } else if (real[j] != 0 && imaginary[k] == 0) {
- result[l++] = real[j++];
- k++;
- } else {
- result[l++] = real[j++];
- result[l++] = imaginary[k++];
- }
- }
- return result;
- }
-
- public double signalSquare(double xAxisValue, double freq, double dc) {
- //This method determines whether at a given x value, the value of y is in the upper half or lower half
- if (xAxisValue % (2 * Math.PI * freq) <= dc)
- return 1;
- else
- return -1;
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/io/pslab/communication/CommandsProto.java b/app/src/main/java/io/pslab/communication/CommandsProto.java
deleted file mode 100644
index 6ee80f60d..000000000
--- a/app/src/main/java/io/pslab/communication/CommandsProto.java
+++ /dev/null
@@ -1,285 +0,0 @@
-package io.pslab.communication;
-
-import android.util.Log;
-
-public class CommandsProto {
-
- private static String TAG = "CommandsProto";
-
- public int ACKNOWLEDGE = 254;
- public int MAX_SAMPLES = 10000;
- public int DATA_SPLITTING = 60;
-
- public int ADC = 2;
- public int CAPTURE_ONE = 1;
- public int CAPTURE_TWO = 2;
- public int CAPTURE_DMASPEED = 3;
- public int CAPTURE_FOUR = 4;
- public int CONFIGURE_TRIGGER = 5;
- public int GET_CAPTURE_STATUS = 6;
- public int GET_CAPTURE_CHANNEL = 7;
- public int SET_PGA_GAIN = 8;
- public int GET_VOLTAGE = 9;
- public int GET_VOLTAGE_SUMMED = 10;
- // public int START_ADC_STREAMING = 11;
- public int SELECT_PGA_CHANNEL = 12;
- public int CAPTURE_12BIT = 13;
- // public int CAPTURE_MULTIPLE = 14;
- public int SET_HI_CAPTURE = 15;
- public int SET_LO_CAPTURE = 16;
-
- public int MULTIPOINT_CAPACITANCE = 20;
- public int SET_CAP = 21;
- public int PULSE_TRAIN = 22;
-
- public int SPI_HEADER = 3;
- public int START_SPI = 1;
- public int SEND_SPI8 = 2;
- public int SEND_SPI16 = 3;
- public int STOP_SPI = 4;
- public int SET_SPI_PARAMETERS = 5;
- public int SEND_SPI8_BURST = 6;
- public int SEND_SPI16_BURST = 7;
-
- public int I2C_HEADER = 4;
- public int I2C_START = 1;
- public int I2C_SEND = 2;
- public int I2C_STOP = 3;
- public int I2C_RESTART = 4;
- public int I2C_READ_END = 5;
- public int I2C_READ_MORE = 6;
- public int I2C_WAIT = 7;
- public int I2C_SEND_BURST = 8;
- public int I2C_CONFIG = 9;
- public int I2C_STATUS = 10;
- public int I2C_READ_BULK = 11;
- public int I2C_WRITE_BULK = 12;
- public int I2C_ENABLE_SMBUS = 13;
- public int I2C_INIT = 14;
- public int I2C_PULLDOWN_SCL = 15;
- public int I2C_DISABLE_SMBUS = 16;
-
-
- public int UART_2 = 5;
- public int SEND_BYTE = 1;
- public int SEND_INT = 2;
- public int SEND_ADDRESS = 3;
- public int SET_BAUD = 4;
- public int SET_MODE = 5;
- public int READ_BYTE = 6;
- public int READ_INT = 7;
- public int READ_UART2_STATUS = 8;
-
-
- public int DAC = 6;
- public int SET_DAC = 1;
- public int SET_CALIBRATED_DAC = 2;
- public int SET_POWER = 3;
-
-
- public int WAVEGEN = 7;
- public int SET_WG = 1;
- public int SET_SQR1 = 3;
- public int SET_SQR2 = 4;
- public int SET_SQRS = 5;
- public int TUNE_SINE_OSCILLATOR = 6;
- public int SQR4 = 7;
- public int MAP_REFERENCE = 8;
- public int SET_BOTH_WG = 9;
- public int SET_WAVEFORM_TYPE = 10;
- public int SELECT_FREQ_REGISTER = 11;
- public int DELAY_GENERATOR = 12;
- public int SET_SINE1 = 13;
- public int SET_SINE2 = 14;
-
- public int LOAD_WAVEFORM1 = 15;
- public int LOAD_WAVEFORM2 = 16;
- public int SQR1_PATTERN = 17;
-
-
- public int DOUT = 8;
- public int SET_STATE = 1;
-
-
- public int DIN = 9;
- public int GET_STATE = 1;
- public int GET_STATES = 2;
-
-
- public int LA1 = 0;
- public int LA2 = 1;
- public int LA3 = 2;
- public int LA4 = 3;
- public int LMETER = 4;
-
-
- public int TIMING = 10;
- public int GET_TIMING = 1;
- public int GET_PULSE_TIME = 2;
- public int GET_DUTY_CYCLE = 3;
- public int START_ONE_CHAN_LA = 4;
- public int START_TWO_CHAN_LA = 5;
- public int START_FOUR_CHAN_LA = 6;
- public int FETCH_DMA_DATA = 7;
- public int FETCH_INT_DMA_DATA = 8;
- public int FETCH_LONG_DMA_DATA = 9;
- public int GET_LA_PROGRESS = 10;
- public int GET_INITIAL_DIGITAL_STATES = 11;
-
- public int TIMING_MEASUREMENTS = 12;
- public int INTERVAL_MEASUREMENTS = 13;
- public int CONFIGURE_COMPARATOR = 14;
- public int START_ALTERNATE_ONE_CHAN_LA = 15;
- public int START_THREE_CHAN_LA = 16;
- public int STOP_LA = 17;
-
-
- public int COMMON = 11;
-
- public int GET_CTMU_VOLTAGE = 1;
- public int GET_CAPACITANCE = 2;
- public int GET_FREQUENCY = 3;
- public int GET_INDUCTANCE = 4;
-
- public int GET_VERSION = 5;
- public int GET_FW_VERSION = 6;
- public int DEBUG_IS_ENABLED = 7;
-
- public int RETRIEVE_BUFFER = 8;
- public int GET_HIGH_FREQUENCY = 9;
- public int CLEAR_BUFFER = 10;
- public int SET_RGB1 = 11;
- public int READ_PROGRAM_ADDRESS = 12;
- public int WRITE_PROGRAM_ADDRESS = 13;
- public int READ_DATA_ADDRESS = 14;
- public int WRITE_DATA_ADDRESS = 15;
-
- public int GET_CAP_RANGE = 16;
- public int SET_RGB2 = 17;
- public int READ_LOG = 18;
- public int RESTORE_STANDALONE = 19;
- public int GET_ALTERNATE_HIGH_FREQUENCY = 20;
- public int SET_RGB_COMMON = 21;
- public int SET_RGB3 = 22;
-
- public int START_CTMU = 23;
- public int STOP_CTMU = 24;
-
- public int START_COUNTING = 25;
- public int FETCH_COUNT = 26;
- public int FILL_BUFFER = 27;
-
-
- public int SETBAUD = 12;
- public int BAUD9600 = 1;
- public int BAUD14400 = 2;
- public int BAUD19200 = 3;
- public int BAUD28800 = 4;
- public int BAUD38400 = 5;
- public int BAUD57600 = 6;
- public int BAUD115200 = 7;
- public int BAUD230400 = 8;
- public int BAUD1000000 = 9;
-
-
- public int NRFL01 = 13;
- public int NRF_SETUP = 1;
- public int NRF_RXMODE = 2;
- public int NRF_TXMODE = 3;
- public int NRF_POWER_DOWN = 4;
- public int NRF_RXCHAR = 5;
- public int NRF_TXCHAR = 6;
- public int NRF_HASDATA = 7;
- public int NRF_FLUSH = 8;
- public int NRF_WRITEREG = 9;
- public int NRF_READREG = 10;
- public int NRF_GETSTATUS = 11;
- public int NRF_WRITECOMMAND = 12;
- public int NRF_WRITEPAYLOAD = 13;
- public int NRF_READPAYLOAD = 14;
- public int NRF_WRITEADDRESS = 15;
- public int NRF_TRANSACTION = 16;
- public int NRF_START_TOKEN_MANAGER = 17;
- public int NRF_STOP_TOKEN_MANAGER = 18;
- public int NRF_TOTAL_TOKENS = 19;
- public int NRF_REPORTS = 20;
- public int NRF_WRITE_REPORT = 21;
- public int NRF_DELETE_REPORT_ROW = 22;
-
- public int NRF_WRITEADDRESSES = 23;
-
-
- public int NONSTANDARD_IO = 14;
- // public int HX711_HEADER = 1;
- public int HCSR04_HEADER = 2;
- // public int AM2302_HEADER = 3;
- // public int TCD1304_HEADER = 4;
- // public int STEPPER_MOTOR = 5;
-
-
- public int PASSTHROUGHS = 15;
- public int PASS_UART = 1;
-
- // public int STOP_STREAMING = 253;
-
- public int EVERY_SIXTEENTH_RISING_EDGE = 0b101;
- public int EVERY_FOURTH_RISING_EDGE = 0b100;
- public int EVERY_RISING_EDGE = 0b011;
- public int EVERY_FALLING_EDGE = 0b010;
- public int EVERY_EDGE = 0b001;
- public int DISABLED = 0b000;
-
- public int CSA1 = 1;
- public int CSA2 = 2;
- public int CSA3 = 3;
- public int CSA4 = 4;
- public int CSA5 = 5;
- public int CS1 = 6;
- public int CS2 = 7;
-
- public int TEN_BIT = 10;
- public int TWELVE_BIT = 12;
-
- public byte[] pack(int value) {
- int intValue = value;
- byte[] bytes = new byte[4];
- int length = bytes.length;
- for (int i = 0; i < length; i++) {
- bytes[length - i - 1] = (byte) (intValue & 0xFF);
- intValue >>= 8;
- }
- return bytes;
- }
-
- public String applySIPrefix(double value, String unit, int precision) {
- boolean negative = false;
- if (value < 0) {
- negative = true;
- value *= -1;
- } else if (value == 0)
- return "0 " + unit;
- int exponent = (int) Math.log10(value);
- if (exponent > 0) {
- exponent = (exponent / 3) * 3;
- } else {
- exponent = ((-1 * exponent + 3) / 3) * (-3);
- }
- value *= (Math.pow(10, -exponent));
- if (value >= 1000.0) {
- value /= 1000.0;
- exponent += 3;
- }
- if (negative) value *= -1;
- String PREFIXES = "yzafpnum KMGTPEZY";
- int prefixLevel = (PREFIXES.length() - 1) / 2;
- int siLevel = exponent / 3;
- if (Math.abs(siLevel) > prefixLevel) {
- Log.e(TAG, "Value Error : Exponent out range of available prefixes.");
- return "";
- } else {
- String format = "%." + precision + "f %s%s";
- return String.format(format, precision, value, PREFIXES.charAt(siLevel + prefixLevel), unit);
- }
- }
-
-}
diff --git a/app/src/main/java/io/pslab/communication/CommunicationHandler.java b/app/src/main/java/io/pslab/communication/CommunicationHandler.java
deleted file mode 100644
index 14a1ad618..000000000
--- a/app/src/main/java/io/pslab/communication/CommunicationHandler.java
+++ /dev/null
@@ -1,152 +0,0 @@
-package io.pslab.communication;
-
-import android.hardware.usb.UsbDevice;
-import android.hardware.usb.UsbDeviceConnection;
-import android.hardware.usb.UsbManager;
-import android.util.Log;
-
-import com.hoho.android.usbserial.driver.CdcAcmSerialDriver;
-import com.hoho.android.usbserial.driver.Cp21xxSerialDriver;
-import com.hoho.android.usbserial.driver.ProbeTable;
-import com.hoho.android.usbserial.driver.UsbSerialDriver;
-import com.hoho.android.usbserial.driver.UsbSerialPort;
-import com.hoho.android.usbserial.driver.UsbSerialProber;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
-public class CommunicationHandler {
- private final String TAG = this.getClass().getSimpleName();
- private static final int PSLAB_VENDOR_ID_V5 = 1240;
- private static final int PSLAB_PRODUCT_ID_V5 = 223;
- private static final int PSLAB_VENDOR_ID_V6 = 0x10C4;
- private static final int PSLAB_PRODUCT_ID_V6 = 0xEA60;
- public static int PSLAB_VERSION;
- private boolean connected = false, device_found = false;
- private UsbManager mUsbManager;
- private UsbDeviceConnection mConnection;
- private UsbSerialDriver driver;
- private UsbSerialPort port;
- public UsbDevice mUsbDevice;
- List drivers;
-
- public static final int DEFAULT_READ_BUFFER_SIZE = 32 * 1024;
- public static final int DEFAULT_WRITE_BUFFER_SIZE = 32 * 1024;
-
- private byte[] mReadBuffer;
- private byte[] mWriteBuffer;
-
- public CommunicationHandler(UsbManager usbManager) {
- this.mUsbManager = usbManager;
- mUsbDevice = null;
- ProbeTable customTable = new ProbeTable();
- customTable.addProduct(PSLAB_VENDOR_ID_V5, PSLAB_PRODUCT_ID_V5, CdcAcmSerialDriver.class);
- customTable.addProduct(PSLAB_VENDOR_ID_V6, PSLAB_PRODUCT_ID_V6, Cp21xxSerialDriver.class);
-
- UsbSerialProber prober = new UsbSerialProber(customTable);
- drivers = prober.findAllDrivers(usbManager);
-
- if (drivers.isEmpty()) {
- Log.d(TAG, "No drivers found");
- } else {
- Log.d(TAG, "Found PSLab device");
- device_found = true;
- driver = drivers.get(0);
- mUsbDevice = driver.getDevice();
- }
- mReadBuffer = new byte[DEFAULT_READ_BUFFER_SIZE];
- mWriteBuffer = new byte[DEFAULT_WRITE_BUFFER_SIZE];
- }
-
- public void open(int baudRate) throws IOException {
- if (!device_found) {
- throw new IOException("Device not Connected");
- }
- mConnection = mUsbManager.openDevice(mUsbDevice);
- if (mConnection == null) {
- throw new IOException("Could not open device.");
- }
- if (mUsbDevice.getProductId() == PSLAB_PRODUCT_ID_V6 && mUsbDevice.getVendorId() == PSLAB_VENDOR_ID_V6) {
- PSLAB_VERSION = 6;
- }
- else {
- PSLAB_VERSION = 5;
- }
- connected = true;
- port = driver.getPorts().get(0);
- port.open(mConnection);
- port.setParameters(baudRate, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
- clear();
- }
-
- public boolean isDeviceFound() {
- return device_found;
- }
-
- public boolean isConnected() {
- return connected;
- }
-
- public void close() throws IOException {
- if (mConnection == null) {
- return;
- }
- port.close();
- connected = false;
- }
-
- public int read(byte[] dest, int bytesToBeRead, int timeoutMillis) throws IOException {
- if (PSLAB_VERSION == 5) {
- return readCdcAcm(dest, bytesToBeRead, timeoutMillis);
- }
- int numBytesRead = 0;
- int readNow;
- Log.v(TAG, "TO read : " + bytesToBeRead);
- int bytesToBeReadTemp = bytesToBeRead;
- while (numBytesRead < bytesToBeRead) {
- readNow = port.read(mReadBuffer, bytesToBeReadTemp, timeoutMillis);
- if (readNow == 0) {
- Log.e(TAG, Arrays.toString(Thread.currentThread().getStackTrace()));
- Log.e(TAG, "Read Error: " + bytesToBeReadTemp);
- return numBytesRead;
- } else {
- System.arraycopy(mReadBuffer, 0, dest, numBytesRead, readNow);
- numBytesRead += readNow;
- bytesToBeReadTemp -= readNow;
- }
- }
- Log.v("Bytes Read", "" + numBytesRead);
- return numBytesRead;
- }
-
- public int readCdcAcm(byte[] dest, int bytesToBeRead, int timeoutMillis) throws IOException {
- int numBytesRead = 0;
- int readNow;
- Log.v(TAG, "TO read : " + bytesToBeRead);
- int bytesToBeReadTemp = bytesToBeRead;
- while (numBytesRead < bytesToBeRead) {
- readNow = mConnection.bulkTransfer(mUsbDevice.getInterface(1).getEndpoint(1), mReadBuffer, bytesToBeReadTemp, timeoutMillis);
- if (readNow < 0) {
- Log.e(TAG, "Read Error: " + bytesToBeReadTemp);
- return numBytesRead;
- } else {
- System.arraycopy(mReadBuffer, 0, dest, numBytesRead, readNow);
- numBytesRead += readNow;
- bytesToBeReadTemp -= readNow;
- }
- }
- Log.v("Bytes Read", "" + numBytesRead);
- return numBytesRead;
- }
-
- public void write(byte[] src, int timeoutMillis) throws IOException {
- int writeLength;
- writeLength = src.length;
- port.write(src, writeLength, timeoutMillis);
- }
-
- private void clear() throws IOException {
- port.read(mReadBuffer, 100, 50);
- }
-}
diff --git a/app/src/main/java/io/pslab/communication/HttpAsyncTask.java b/app/src/main/java/io/pslab/communication/HttpAsyncTask.java
deleted file mode 100644
index 4aae41545..000000000
--- a/app/src/main/java/io/pslab/communication/HttpAsyncTask.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package io.pslab.communication;
-
-import android.os.AsyncTask;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.IOException;
-
-import io.pslab.interfaces.HttpCallback;
-
-public class HttpAsyncTask extends AsyncTask {
-
- private HttpHandler mHttpHandler;
- private HttpCallback mHttpCallback;
-
- public HttpAsyncTask(String baseIP, HttpCallback httpCallback) {
- mHttpHandler = new HttpHandler(baseIP);
- mHttpCallback = httpCallback;
- }
-
- @Override
- protected Void doInBackground(byte[]... data) {
- int res = 0;
- try {
- if (data.length != 0) {
- res = mHttpHandler.write(data[0]);
-
- } else {
- res = mHttpHandler.read();
- }
- } catch (IOException | JSONException e) {
- mHttpCallback.error(e);
- e.printStackTrace();
- }
- if (res == 1) {
- mHttpCallback.success(mHttpHandler.getReceivedData());
- } else {
- mHttpCallback.error(new Exception());
- }
- return null;
- }
-}
diff --git a/app/src/main/java/io/pslab/communication/HttpHandler.java b/app/src/main/java/io/pslab/communication/HttpHandler.java
deleted file mode 100644
index a2f7bed38..000000000
--- a/app/src/main/java/io/pslab/communication/HttpHandler.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package io.pslab.communication;
-
-import android.util.Log;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.IOException;
-import java.net.URL;
-
-import okhttp3.MediaType;
-import okhttp3.OkHttpClient;
-import okhttp3.Request;
-import okhttp3.RequestBody;
-import okhttp3.Response;
-
-public class HttpHandler {
-
- private final String TAG = this.getClass().getSimpleName();
- private String baseIP;
- private String sendDataEndPoint = "send";
- private String getDataEndPoint = "get";
- private String dataKeyString = "data";
- private OkHttpClient client;
- private JSONObject receivedData;
-
- public HttpHandler(String baseIP) {
- this.baseIP = baseIP;
- this.client = new OkHttpClient();
- }
-
- /**
- * Method to send data to ESP
- *
- * @param data data to be sent in byte array
- * @return 1 if response code is "200" 0 otherwise;
- */
- public int write(byte[] data) throws IOException, JSONException {
- int result = 1;
- URL baseURL = new URL("http://" + baseIP + "/" + sendDataEndPoint);
- int written = 0;
- JSONArray responseArray = new JSONArray();
- while (written < data.length) {
- JSONObject jsonObject = new JSONObject();
- jsonObject.put(dataKeyString, data[written]);
- RequestBody body = RequestBody.create(jsonObject.toString(), MediaType.get("application/json; charset=utf-8"));
- Request request = new Request.Builder()
- .url(baseURL)
- .post(body)
- .build();
- Response response = client.newCall(request).execute();
- responseArray.put(new JSONObject(response.body().string()));
- if (response.code() != 200) {
- Log.e(TAG, "Error writing byte:" + written);
- return 0;
- }
- written++;
- }
- receivedData = new JSONObject(responseArray.toString());
- return result;
- }
-
- /**
- * Method to get data from ESP
- * @return 1 if data was received 0 otherwise
- */
- public int read() throws IOException, JSONException {
- int result = 1;
- URL baseURL = new URL("http://" + baseIP + "/" + getDataEndPoint);
- Request request = new Request.Builder()
- .url(baseURL)
- .build();
- Response response = client.newCall(request).execute();
- if (response.code() != 200) {
- Log.e(TAG, "Error reading data");
- return 0;
- } else {
- receivedData = new JSONObject(response.body().string());
- }
- return result;
- }
-
- public JSONObject getReceivedData() {
- return receivedData;
- }
-}
diff --git a/app/src/main/java/io/pslab/communication/PacketHandler.java b/app/src/main/java/io/pslab/communication/PacketHandler.java
deleted file mode 100644
index 709b26659..000000000
--- a/app/src/main/java/io/pslab/communication/PacketHandler.java
+++ /dev/null
@@ -1,295 +0,0 @@
-package io.pslab.communication;
-
-import android.util.Log;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-
-import io.pslab.interfaces.HttpCallback;
-import io.pslab.others.ScienceLabCommon;
-
-/**
- * Created by viveksb007 on 28/3/17.
- */
-
-public class PacketHandler {
-
- private static final String TAG = "PacketHandler";
- private final int BUFSIZE = 10000;
- private byte[] buffer = new byte[BUFSIZE];
- private boolean loadBurst, connected;
- private int inputQueueSize = 0, BAUD = 1000000;
- private CommunicationHandler mCommunicationHandler = null;
- public static String version = "";
- private CommandsProto mCommandsProto;
- private int timeout = 500, VERSION_STRING_LENGTH = 8, FW_VERSION_LENGTH = 3;
- public static int PSLAB_FW_VERSION = 0;
- ByteBuffer burstBuffer = ByteBuffer.allocate(2000);
- private HttpAsyncTask httpAsyncTask;
-
- public PacketHandler(int timeout, CommunicationHandler communicationHandler) {
- this.loadBurst = false;
- this.connected = false;
- this.timeout = timeout;
- this.mCommandsProto = new CommandsProto();
- this.mCommunicationHandler = communicationHandler;
- connected = (mCommunicationHandler.isConnected() || ScienceLabCommon.isWifiConnected());
- }
-
- public boolean isConnected() {
- connected = (mCommunicationHandler.isConnected() || ScienceLabCommon.isWifiConnected());
- return connected;
- }
-
- public String getVersion() {
- try {
- sendByte(mCommandsProto.COMMON);
- sendByte(mCommandsProto.GET_VERSION);
- // Read "\n"
- commonRead(VERSION_STRING_LENGTH + 1);
- // Only use first line, just like in the Python implementation.
- version = new BufferedReader(
- new InputStreamReader(
- new ByteArrayInputStream(buffer, 0, VERSION_STRING_LENGTH),
- StandardCharsets.UTF_8))
- .readLine();
- } catch (IOException e) {
- Log.e("Error in Communication", e.toString());
- }
- return version;
- }
-
- public int getFirmwareVersion() {
- try {
- sendByte(mCommandsProto.COMMON);
- sendByte(mCommandsProto.GET_FW_VERSION);
- int numByteRead = commonRead(FW_VERSION_LENGTH);
- if (numByteRead == 1) {
- return 2;
- } else {
- return buffer[0];
- }
- } catch (IOException e) {
- Log.e("Error in Communication", e.toString());
- }
- return 0;
- }
-
- public String readLine() {
- String line = "";
- try {
- commonRead(CommunicationHandler.DEFAULT_READ_BUFFER_SIZE);
- line = new BufferedReader(
- new InputStreamReader(
- new ByteArrayInputStream(buffer, 0, CommunicationHandler.DEFAULT_READ_BUFFER_SIZE),
- StandardCharsets.UTF_8))
- .readLine();
- return line;
- } catch (IOException e) {
- Log.e("Error in Communication", e.toString());
- }
- return line;
- }
-
- public void sendByte(int val) throws IOException {
- if (!connected) {
- throw new IOException("Device not connected");
- }
- if (!loadBurst) {
- try {
- commonWrite(new byte[]{(byte) (val & 0xff)});
- } catch (IOException | NullPointerException e) {
- Log.e("Error in sending byte", e.toString());
- e.printStackTrace();
- }
- } else {
- burstBuffer.put((byte) (val & 0xff));
- }
- }
-
- public void sendInt(int val) throws IOException {
- if (!connected) {
- throw new IOException("Device not connected");
- }
- if (!loadBurst) {
- try {
- commonWrite(new byte[]{(byte) (val & 0xff), (byte) ((val >> 8) & 0xff)});
- } catch (IOException e) {
- Log.e("Error in sending int", e.toString());
- e.printStackTrace();
- }
- } else {
- burstBuffer.put(new byte[]{(byte) (val & 0xff), (byte) ((val >> 8) & 0xff)});
- }
- }
-
- public int getAcknowledgement() {
- /*
- fetches the response byte
- 1 SUCCESS
- 2 ARGUMENT_ERROR
- 3 FAILED
- used as a handshake
- */
- if (loadBurst) {
- inputQueueSize++;
- return 1;
- } else {
- try {
- commonRead(1);
- return buffer[0];
- } catch (IOException | NullPointerException e) {
- e.printStackTrace();
- return 3;
- }
- }
- }
-
- public byte getByte() {
- try {
- int numByteRead = commonRead(1);
- if (numByteRead == 1) {
- return buffer[0];
- } else {
- Log.e(TAG, "Error in reading byte");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return -1;
- }
-
- int getVoltageSummation() {
- try {
- // Note : bytesToBeRead has to be +1 than the requirement
- int numByteRead = commonRead(3);
- if (numByteRead == 3) {
- return (buffer[0] & 0xff) | ((buffer[1] << 8) & 0xff00);
- } else {
- Log.e(TAG, "Error in reading byte");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return -1;
- }
-
- public int getInt() {
- try {
- int numByteRead = commonRead(2);
- if (numByteRead == 2) {
- // LSB is read first
- return (buffer[0] & 0xff) | ((buffer[1] << 8) & 0xff00);
- } else {
- Log.e(TAG, "Error in reading byte");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return -1;
- }
-
- public long getLong() {
- try {
- int numByteRead = commonRead(4);
- if (numByteRead == 4) {
- // C++ has long of 4-bytes but in Java int has 4-bytes
- // refer "https://stackoverflow.com/questions/7619058/convert-a-byte-array-to-integer-in-java-and-vice-versa" for Endian
- return ByteBuffer.wrap(Arrays.copyOfRange(buffer, 0, 4)).order(ByteOrder.LITTLE_ENDIAN).getInt();
- } else {
- Log.e(TAG, "Error in reading byte");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return -1;
- }
-
- public boolean waitForData() {
- return false;
- }
-
- public int read(byte[] dest, int bytesToRead) throws IOException {
- int numBytesRead = commonRead(bytesToRead);
- for (int i = 0; i < bytesToRead; i++) {
- dest[i] = buffer[i];
- }
- if (numBytesRead == bytesToRead) {
- return numBytesRead;
- } else {
- Log.e(TAG, "Error in packetHandler Reading");
- }
- return -1;
- }
-
- public byte[] sendBurst() {
- try {
- commonWrite(burstBuffer.array());
- burstBuffer.clear();
- loadBurst = false;
- int bytesRead = commonRead(inputQueueSize);
- inputQueueSize = 0;
- return Arrays.copyOfRange(buffer, 0, bytesRead);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return new byte[]{-1};
- }
-
- public int commonRead(int bytesToRead) throws IOException {
- final int[] bytesRead = {0};
- if (mCommunicationHandler.isConnected()) {
- bytesRead[0] = mCommunicationHandler.read(buffer, bytesToRead, timeout);
- } else if (ScienceLabCommon.isWifiConnected()) {
- httpAsyncTask = new HttpAsyncTask(ScienceLabCommon.getEspIP(), new HttpCallback() {
- @Override
- public void success(JSONObject jsonObject) {
- try {
- //Server will send byte array
- buffer = (byte[]) jsonObject.get("data");
- bytesRead[0] = buffer.length;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- @Override
- public void error(Exception e) {
- Log.e(TAG, "Error reading data over ESP");
- }
- });
- httpAsyncTask.execute(new byte[]{});
- }
- return bytesRead[0];
- }
-
- public void commonWrite(byte[] data) throws IOException {
- if (mCommunicationHandler.isConnected()) {
- mCommunicationHandler.write(data, timeout);
- } else if (ScienceLabCommon.isWifiConnected()) {
- httpAsyncTask = new HttpAsyncTask(ScienceLabCommon.getEspIP(), new HttpCallback() {
- @Override
- public void success(JSONObject jsonObject) {
- Log.v(TAG, "write response:" + jsonObject.toString());
- }
-
- @Override
- public void error(Exception e) {
- Log.e(TAG, "Error writing data over ESP");
- }
- });
-
- httpAsyncTask.execute(data);
- }
-
- }
-}
diff --git a/app/src/main/java/io/pslab/communication/ScienceLab.java b/app/src/main/java/io/pslab/communication/ScienceLab.java
deleted file mode 100644
index 7b8430d1c..000000000
--- a/app/src/main/java/io/pslab/communication/ScienceLab.java
+++ /dev/null
@@ -1,2932 +0,0 @@
-package io.pslab.communication;
-
-import static java.lang.Math.pow;
-import static io.pslab.others.MathUtils.linSpace;
-
-import android.os.Build;
-import android.os.Handler;
-import android.os.Looper;
-import android.util.Log;
-
-
-import org.apache.commons.lang3.ArrayUtils;
-import org.apache.commons.math3.analysis.polynomials.PolynomialFunction;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.time.Duration;
-import java.time.Instant;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Objects;
-
-import io.pslab.activity.MainActivity;
-import io.pslab.communication.analogChannel.AnalogAquisitionChannel;
-import io.pslab.communication.analogChannel.AnalogConstants;
-import io.pslab.communication.analogChannel.AnalogInputSource;
-import io.pslab.communication.digitalChannel.DigitalChannel;
-import io.pslab.communication.peripherals.DACChannel;
-import io.pslab.communication.peripherals.I2C;
-import io.pslab.fragment.HomeFragment;
-import io.pslab.others.InitializationVariable;
-
-/**
- * Created by viveksb007 on 28/3/17.
- */
-
-public class ScienceLab {
-
- private static final String TAG = "ScienceLab";
- public static Thread initialisationThread;
- public int DDS_CLOCK, MAX_SAMPLES, samples, triggerLevel, triggerChannel, errorCount,
- channelsInBuffer, digitalChannelsInBuffer, dataSplitting;
- public double sin1Frequency, sin2Frequency;
- double[] currents, gainValues, buffer;
- int[] currentScalars;
- double SOCKET_CAPACITANCE, resistanceScaling, timebase;
- private static final double CAPACITOR_DISCHARGE_VOLTAGE = 0.01 * 3.3;
- private static final int CTMU_CHANNEL = 0b11110;
- public boolean streaming;
- String[] allAnalogChannels, allDigitalChannels;
- HashMap analogInputSources = new HashMap<>();
- HashMap squareWaveFrequency = new HashMap<>();
- HashMap gains = new HashMap<>();
- HashMap waveType = new HashMap<>();
- ArrayList aChannels = new ArrayList<>();
- ArrayList dChannels = new ArrayList<>();
- public Map dacChannels = new LinkedHashMap<>();
- private Map values = new LinkedHashMap<>();
-
- private CommunicationHandler mCommunicationHandler;
- private PacketHandler mPacketHandler;
- private CommandsProto mCommandsProto;
- private AnalogConstants mAnalogConstants;
- private int LAChannelFrequency;
- public I2C i2c;
-
- /**
- * Constructor
- *
- * @param communicationHandler
- */
- public ScienceLab(CommunicationHandler communicationHandler) {
- mCommandsProto = new CommandsProto();
- mAnalogConstants = new AnalogConstants();
- mCommunicationHandler = communicationHandler;
- if (isDeviceFound() && MainActivity.hasPermission) {
- try {
- mCommunicationHandler.open(1000000);
- //Thread.sleep(200);
- mPacketHandler = new PacketHandler(50, mCommunicationHandler);
- } catch (IOException | NullPointerException e) {
- e.printStackTrace();
- }
- }
- if (isConnected()) {
- initializeVariables();
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- initialisationThread = new Thread(new Runnable() {
-
- @Override
- public void run() {
- try {
- runInitSequence();
- } catch (IOException e) {
- e.printStackTrace();
- }
- new Handler(Looper.getMainLooper()).post(new Runnable() {
- @Override
- public void run() {
- if (HomeFragment.booleanVariable == null) {
- HomeFragment.booleanVariable = new InitializationVariable();
- }
- HomeFragment.booleanVariable.setVariable(true);
- }
- });
- }
- });
- initialisationThread.start();
-
- }
- }, 1000);
- }
- }
-
- private void initializeVariables() {
- DDS_CLOCK = 0;
- timebase = 40;
- MAX_SAMPLES = mCommandsProto.MAX_SAMPLES;
- samples = MAX_SAMPLES;
- triggerChannel = 0;
- triggerLevel = 550;
- errorCount = 0;
- channelsInBuffer = 0;
- digitalChannelsInBuffer = 0;
- currents = new double[]{0.55e-3, 0.55e-6, 0.55e-5, 0.55e-4};
- currentScalars = new int[]{1, 2, 3, 0};
- dataSplitting = mCommandsProto.DATA_SPLITTING;
- allAnalogChannels = mAnalogConstants.allAnalogChannels;
- LAChannelFrequency = 0;
- for (String aChannel : allAnalogChannels) {
- analogInputSources.put(aChannel, new AnalogInputSource(aChannel));
- }
- sin1Frequency = 0;
- sin2Frequency = 0;
- squareWaveFrequency.put("SQR1", 0.0);
- squareWaveFrequency.put("SQR2", 0.0);
- squareWaveFrequency.put("SQR3", 0.0);
- squareWaveFrequency.put("SQR4", 0.0);
- if (CommunicationHandler.PSLAB_VERSION == 6) {
- dacChannels.put("PCS", new DACChannel("PCS", new double[]{0, 3.3}, 0, 0));
- dacChannels.put("PV3", new DACChannel("PV3", new double[]{0, 3.3}, 1, 1));
- dacChannels.put("PV2", new DACChannel("PV2", new double[]{-3.3, 3.3}, 2, 0));
- dacChannels.put("PV1", new DACChannel("PV1", new double[]{-5., 5.}, 3, 1));
- } else {
- dacChannels.put("PCS", new DACChannel("PCS", new double[]{0, 3.3}, 0, 0));
- dacChannels.put("PV3", new DACChannel("PV3", new double[]{0, 3.3}, 1, 1));
- dacChannels.put("PV2", new DACChannel("PV2", new double[]{-3.3, 3.3}, 2, 2));
- dacChannels.put("PV1", new DACChannel("PV1", new double[]{-5., 5.}, 3, 3));
- }
- values.put("PV1", 0.);
- values.put("PV2", 0.);
- values.put("PV3", 0.);
- values.put("PCS", 0.);
- }
-
- private void runInitSequence() throws IOException {
- fetchFirmwareVersion();
- ArrayList aboutArray = new ArrayList<>();
- if (!isConnected()) {
- Log.e(TAG, "Check hardware connections. Not connected");
- }
- streaming = false;
- for (String aChannel : mAnalogConstants.biPolars) {
- aChannels.add(new AnalogAquisitionChannel(aChannel));
- }
- gainValues = mAnalogConstants.gains;
- this.buffer = new double[10000];
- Arrays.fill(this.buffer, 0);
- SOCKET_CAPACITANCE = 46e-12;
- resistanceScaling = 1;
- allDigitalChannels = DigitalChannel.digitalChannelNames;
- gains.put("CH1", 0);
- gains.put("CH2", 0);
- for (int i = 0; i < 4; i++) {
- dChannels.add(new DigitalChannel(i));
- }
- i2c = new I2C(mPacketHandler);
- if (isConnected()) {
- for (String temp : new String[]{"CH1", "CH2"}) {
- this.setGain(temp, 0, true);
- }
- for (String temp : new String[]{"SI1", "SI2"}) {
- loadEquation(temp, "sine");
- }
- }
- this.clearBuffer(0, samples);
- }
-
- /**
- * @return Resistance of connected resistor between RES an GND pins
- */
- public Double getResistance() {
- double volt = this.getAverageVoltage("RES", null);
- if (volt > 3.295) return null;
- double current = (3.3 - volt) / 5.1e3;
- return (volt / current) * this.resistanceScaling;
- }
-
- public String getVersion() throws IOException {
- if (isConnected()) {
- return mPacketHandler.getVersion();
- } else {
- return "Not Connected";
- }
- }
-
- public void fetchFirmwareVersion() {
- if (isConnected()) {
- PacketHandler.PSLAB_FW_VERSION = mPacketHandler.getFirmwareVersion();
- if (PacketHandler.PSLAB_FW_VERSION == 2) {
- MainActivity.getInstance().runOnUiThread(new Runnable() {
- @Override
- public void run() {
- MainActivity.getInstance().showFirmwareDialog();
- }
- });
- }
- }
- }
-
- public void close() {
- try {
- mCommunicationHandler.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- private void captureFullSpeedHrInitialize(String channel, int samples, double timeGap, List args) {
- timeGap = (int) (timeGap * 8) / 8;
- if (timeGap < 0.5) timeGap = (int) (0.5 * 8) / 8;
- if (samples > this.MAX_SAMPLES) {
- Log.v(TAG, "Sample limit exceeded. 10,000 max");
- samples = this.MAX_SAMPLES;
- }
- this.timebase = (int) (timeGap * 8) / 8;
- this.samples = samples;
- int CHOSA = this.analogInputSources.get(channel).CHOSA;
-
- try {
- mPacketHandler.sendByte(mCommandsProto.ADC);
- if (args.contains("SET_LOW"))
- mPacketHandler.sendByte(mCommandsProto.SET_LO_CAPTURE);
- else if (args.contains("SET_HIGH"))
- mPacketHandler.sendByte(mCommandsProto.SET_HI_CAPTURE);
- else if (args.contains("READ_CAP")) {
- mPacketHandler.sendByte(mCommandsProto.MULTIPOINT_CAPACITANCE);
- } else
- mPacketHandler.sendByte(mCommandsProto.CAPTURE_DMASPEED);
- mPacketHandler.sendByte(CHOSA | 0x80);
- mPacketHandler.sendInt(samples);
- mPacketHandler.sendInt((int) timeGap * 8);
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * @param channel Channel name 'CH1' / 'CH2' ... 'RES'
- * @param samples Number of samples to fetch. Maximum 10000/(total specified channels)
- * @param timeGap Timegap between samples in microseconds.
- * @param args timestamp array ,voltage_value array
- * @return Timestamp array ,voltage_value array
- */
- public Map captureFullSpeedHr(String channel, int samples, double timeGap, List args) {
- this.captureFullSpeedHrInitialize(channel, samples, timeGap, args);
- try {
- Thread.sleep((long) (1e-6 * this.samples * this.timebase + 0.1));
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- Map axisData = retrieveBufferData(channel, this.samples, this.timebase);
- if (axisData == null) {
- Log.v(TAG, "Retrieved Buffer Data as null");
- return null;
- }
- Map retData = new HashMap<>();
- retData.put("x", axisData.get("x"));
- retData.put("y", this.analogInputSources.get(channel).cal12(axisData.get("y")));
- return retData;
- }
-
- private Map retrieveBufferData(String channel, int samples, double timeGap) {
- ArrayList listData = new ArrayList<>();
- try {
- for (int i = 0; i < samples / this.dataSplitting; i++) {
- mPacketHandler.sendByte(mCommandsProto.ADC);
- mPacketHandler.sendByte(mCommandsProto.GET_CAPTURE_CHANNEL);
- mPacketHandler.sendByte(0);
- mPacketHandler.sendInt(this.dataSplitting);
- mPacketHandler.sendInt(i * this.dataSplitting);
- byte[] data = new byte[this.dataSplitting * 2 + 1];
- mPacketHandler.read(data, this.dataSplitting * 2 + 1);
- for (int j = 0; j < data.length - 1; j++)
- listData.add((int) data[j] & 0xff);
- }
-
- if ((samples % this.dataSplitting) != 0) {
- mPacketHandler.sendByte(mCommandsProto.ADC);
- mPacketHandler.sendByte(mCommandsProto.GET_CAPTURE_CHANNEL);
- mPacketHandler.sendByte(0);
- mPacketHandler.sendInt(samples * this.dataSplitting);
- mPacketHandler.sendInt(samples - samples % this.dataSplitting);
- byte[] data = new byte[2 * (samples % this.dataSplitting)];
- mPacketHandler.read(data, 2 * (samples % this.dataSplitting));
- for (int j = 0; j < data.length - 1; j++)
- listData.add((int) data[j] & 0xff);
- }
-
- for (int i = 0; i < samples; i++) {
- this.buffer[i] = (listData.get(i * 2) | (listData.get(i * 2 + 1) << 8));
- }
-
- double[] timeAxis = linSpace(0, timeGap * (samples - 1), samples);
- Map retData = new HashMap<>();
- retData.put("x", timeAxis);
- retData.put("y", Arrays.copyOfRange(buffer, 0, samples));
- return retData;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Instruct the ADC to start sampling. use fetchTrace to retrieve the data
- *
- * @param number Channels to acquire. 1/2/4
- * @param samples Total points to store per channel. Maximum 3200 total
- * @param timeGap Timegap between two successive samples (in uSec)
- * @param channelOneInput Map channel 1 to 'CH1'
- * @param trigger Whether or not to trigger the oscilloscope based on the voltage level set
- * @param CH123SA
- */
- public void captureTraces(int number, int samples, double timeGap, String channelOneInput, Boolean trigger, Integer CH123SA) {
- if (CH123SA == null) CH123SA = 0;
- if (channelOneInput == null) channelOneInput = "CH1";
- this.timebase = timeGap;
- this.timebase = (int) (this.timebase * 8) / 8;
- if (!this.analogInputSources.containsKey(channelOneInput)) {
- Log.e(TAG, "Invalid input channel");
- return;
- }
- int CHOSA = this.analogInputSources.get(channelOneInput).CHOSA;
- this.aChannels.get(0).setParams(channelOneInput, samples, 0, this.timebase, 10, this.analogInputSources.get(channelOneInput), null);
- try {
- mPacketHandler.sendByte(mCommandsProto.ADC);
- if (number == 1) {
- if (timeGap < 0.5)
- this.timebase = (int) (0.5 * 8) / 8;
- if (samples > this.MAX_SAMPLES)
- samples = this.MAX_SAMPLES;
- if (trigger) {
- if (timeGap < 0.75)
- this.timebase = (int) (0.75 * 8) / 8;
- mPacketHandler.sendByte(mCommandsProto.CAPTURE_ONE);
- mPacketHandler.sendByte(CHOSA | 0x80);
- } else if (timeGap > 1) {
- this.aChannels.get(0).setParams(channelOneInput, samples, 0, this.timebase, 12, this.analogInputSources.get(channelOneInput), null);
- mPacketHandler.sendByte(mCommandsProto.CAPTURE_DMASPEED);
- mPacketHandler.sendByte(CHOSA | 0x80);
- } else {
- mPacketHandler.sendByte(mCommandsProto.CAPTURE_DMASPEED);
- mPacketHandler.sendByte(CHOSA);
- }
- } else if (number == 2) {
- if (timeGap < 0.875)
- this.timebase = (int) (0.875 * 8) / 8;
- if (samples > this.MAX_SAMPLES / 2)
- samples = this.MAX_SAMPLES / 2;
- this.aChannels.get(1).setParams("CH2", samples, samples, this.timebase, 10, this.analogInputSources.get("CH2"), null);
- mPacketHandler.sendByte(mCommandsProto.CAPTURE_TWO);
- mPacketHandler.sendByte(CHOSA | (0x80 * (trigger ? 1 : 0)));
- } else {
- if (timeGap < 1.75)
- this.timebase = (int) (1.75 * 8) / 8;
- if (samples > this.MAX_SAMPLES / 4)
- samples = this.MAX_SAMPLES / 4;
- int i = 1;
- for (String temp : new String[]{"CH2", "CH3", "MIC"}) {
- this.aChannels.get(i).setParams(temp, samples, i * samples, this.timebase, 10, this.analogInputSources.get(temp), null);
- i++;
- }
- mPacketHandler.sendByte(mCommandsProto.CAPTURE_FOUR);
- mPacketHandler.sendByte(CHOSA | (CH123SA << 4) | (0x80 * (trigger ? 1 : 0)));
- }
- this.samples = samples;
- mPacketHandler.sendInt(samples);
- mPacketHandler.sendInt((int) this.timebase * 8);
- mPacketHandler.getAcknowledgement();
- this.channelsInBuffer = number;
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
- /**
- * Fetches a channel(1-4) captured by :func:captureTraces called prior to this, and returns xAxis,yAxis
- *
- * @param channelNumber Any of the maximum of four channels that the oscilloscope captured. 1/2/3/4
- * @return time array,voltage array
- */
- public HashMap fetchTrace(int channelNumber) {
- this.fetchData(channelNumber);
- HashMap retData = new HashMap<>();
- retData.put("x", this.aChannels.get(channelNumber - 1).getXAxis());
- retData.put("y", this.aChannels.get(channelNumber - 1).getYAxis());
- return retData;
- }
-
- /**
- * Returns the number of samples acquired by the capture routines, and the conversion_done status
- *
- * @return conversion done(bool) ,samples acquired (number)
- */
- public int[] oscilloscopeProgress() {
- /*
- * returns the number of samples acquired by the capture routines, and the conversion_done status
- *
- * return structure int[]{conversionDone, samples}
- */
-
- int conversionDone = 0;
- int samples = 0;
- try {
- mPacketHandler.sendByte(mCommandsProto.ADC);
- mPacketHandler.sendByte(mCommandsProto.GET_CAPTURE_STATUS);
- conversionDone = (int) mPacketHandler.getByte() & 0xff;
- samples = mPacketHandler.getInt();
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return new int[]{conversionDone, samples};
- }
-
- private boolean fetchData(int channelNumber) {
- int samples = this.aChannels.get(channelNumber - 1).length;
- if (channelNumber > this.channelsInBuffer) {
- Log.v(TAG, "Channel Unavailable");
- return false;
- }
- Log.v("Samples", "" + samples);
- Log.v("Data Splitting", "" + this.dataSplitting);
- ArrayList listData = new ArrayList<>();
- try {
- for (int i = 0; i < samples / this.dataSplitting; i++) {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER);
- mPacketHandler.sendInt(this.aChannels.get(channelNumber - 1).bufferIndex + (i * this.dataSplitting));
- mPacketHandler.sendInt(this.dataSplitting);
- byte[] data = new byte[this.dataSplitting * 2 + 1];
- mPacketHandler.read(data, this.dataSplitting * 2 + 1);
- for (int j = 0; j < data.length - 1; j++)
- listData.add((int) data[j] & 0xff);
- }
-
- if ((samples % this.dataSplitting) != 0) {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER);
- mPacketHandler.sendInt(this.aChannels.get(channelNumber - 1).bufferIndex + samples - samples % this.dataSplitting);
- mPacketHandler.sendInt(samples % this.dataSplitting);
- byte[] data = new byte[2 * (samples % this.dataSplitting) + 1];
- mPacketHandler.read(data, 2 * (samples % this.dataSplitting) + 1);
- for (int j = 0; j < data.length - 1; j++)
- listData.add((int) data[j] & 0xff);
- }
-
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
-
- for (int i = 0; i < listData.size() / 2; i++) {
- this.buffer[i] = (listData.get(i * 2)) | (listData.get(i * 2 + 1) << 8);
- while (this.buffer[i] > 1023) this.buffer[i] -= 1023;
- }
-
- Log.v("RAW DATA:", Arrays.toString(Arrays.copyOfRange(buffer, 0, samples)));
-
- this.aChannels.get(channelNumber - 1).yAxis = this.aChannels.get(channelNumber - 1).fixValue(Arrays.copyOfRange(this.buffer, 0, samples));
- return true;
- }
-
- /**
- * Configure trigger parameters for 10-bit capture commands
- * The capture routines will wait till a rising edge of the input signal crosses the specified level.
- * The trigger will timeout within 8mS, and capture routines will start regardless.
- * These settings will not be used if the trigger option in the capture routines are set to False
- *
- * @param channel Channel 0,1,2,3. Corresponding to the channels being recorded by the capture routine(not the analog inputs)
- * @param channelName Name of the channel. 'CH1','CH2','CH3','MIC','V+'
- * @param voltage The voltage level that should trigger the capture sequence(in Volts)
- * @param resolution
- * @param prescalar
- */
- public void configureTrigger(int channel, String channelName, double voltage, Integer resolution, Integer prescalar) {
- if (resolution == null) resolution = 10;
- if (prescalar == null) prescalar = 0;
- try {
- mPacketHandler.sendByte(mCommandsProto.ADC);
- mPacketHandler.sendByte(mCommandsProto.CONFIGURE_TRIGGER);
- mPacketHandler.sendByte((prescalar << 4) | (1 << channel));
- double level;
- if (resolution == 12) {
- level = this.analogInputSources.get(channelName).voltToCode12.value(voltage);
- if (level < 0) level = 0;
- else if (level > 4095) level = 4095;
- } else {
- level = this.analogInputSources.get(channelName).voltToCode10.value(voltage);
- if (level < 0) level = 0;
- else if (level > 1023) level = 1023;
- }
- if (level > pow(2, resolution - 1))
- level = pow(2, resolution - 1);
- else if (level < 0)
- level = 0;
- mPacketHandler.sendInt((int) level);
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Set the gain of the selected PGA
- *
- * @param channel 'CH1','CH2'
- * @param gain (0-8) -> (1x,2x,4x,5x,8x,10x,16x,32x,1/11x)
- * @param force If True, the amplifier gain will be set even if it was previously set to the same value.
- * @return
- */
- public double setGain(String channel, int gain, Boolean force) {
- if (force == null) force = false;
- if (gain < 0 || gain > 8) {
- Log.v(TAG, "Invalid gain parameter. 0-7 only.");
- return 0;
- }
- if (this.analogInputSources.get(channel).gainPGA == -1) {
- Log.v(TAG, "No amplifier exists on this channel : " + channel);
- return 0;
- }
- boolean refresh = false;
- if (this.gains.get(channel) != gain) {
- this.gains.put(channel, gain);
- refresh = true;
- }
- if (refresh || force) {
- analogInputSources.get(channel).setGain(gain); // giving index of gainValues
- if (gain > 7) gain = 0;
- try {
- mPacketHandler.sendByte(mCommandsProto.ADC);
- mPacketHandler.sendByte(mCommandsProto.SET_PGA_GAIN);
- mPacketHandler.sendByte(analogInputSources.get(channel).gainPGA);
- mPacketHandler.sendByte(gain);
- mPacketHandler.getAcknowledgement();
- return this.gainValues[gain];
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return 0;
- }
-
- /**
- * set the gain of the selected PGA
- *
- * @param channel 'CH1','CH2'
- * @param voltageRange Choose from [16,8,4,3,2,1.5,1,.5,160]
- * @return
- */
- public Double selectRange(String channel, double voltageRange) {
- double[] ranges = new double[]{16, 8, 4, 3, 2, 1.5, 1, .5, 160};
- if (Arrays.asList(ArrayUtils.toObject(ranges)).contains(voltageRange)) {
- return this.setGain(channel, Arrays.asList(ArrayUtils.toObject(ranges)).indexOf(voltageRange), null);
- } else
- Log.e(TAG, "Not a valid Range");
- return null;
- }
-
- private int calcCHOSA(String channelName) {
- channelName = channelName.toUpperCase();
- AnalogInputSource source = analogInputSources.get(channelName);
- boolean found = false;
- for (String temp : allAnalogChannels) {
- if (temp.equals(channelName)) {
- found = true;
- break;
- }
- }
- if (!found) {
- Log.e(TAG, "Not a valid channel name. selecting CH1");
- return calcCHOSA("CH1");
- }
-
- return source.CHOSA;
- }
-
- public double getVoltage(String channelName, Integer sample) {
- this.voltmeterAutoRange(channelName);
- double Voltage = this.getAverageVoltage(channelName, sample);
- if (channelName.equals("CH2") || channelName.equals("CH1")) {
- return 2 * Voltage;
- } else {
- return Voltage;
- }
- }
-
- private void voltmeterAutoRange(String channelName) {
- if (this.analogInputSources.get(channelName).gainPGA != 0) {
- this.setGain(channelName, 0, true);
- }
- }
-
- /**
- * Return the voltage on the selected channel
- *
- * @param channelName : 'CH1','CH2','CH3','MIC','IN1','RES','V+'
- * @param sample Samples to average
- * @return Voltage on the selected channel
- */
- private double getAverageVoltage(String channelName, Integer sample) {
- if (sample == null) sample = 1;
- PolynomialFunction poly;
- double sum = 0;
- poly = analogInputSources.get(channelName).calPoly12;
- ArrayList vals = new ArrayList<>();
- for (int i = 0; i < sample; i++) {
- vals.add(getRawAverageVoltage(channelName));
- }
- for (int j = 0; j < vals.size(); j++) {
- sum = sum + poly.value(vals.get(j));
- }
- return sum / 2 * vals.size();
- }
-
- private double getRawAverageVoltage(String channelName) {
- try {
- int chosa = this.calcCHOSA(channelName);
- mPacketHandler.sendByte(mCommandsProto.ADC);
- mPacketHandler.sendByte(mCommandsProto.GET_VOLTAGE_SUMMED);
- mPacketHandler.sendByte(chosa);
- int vSum = mPacketHandler.getVoltageSummation();
- return vSum / 16.0;
- } catch (IOException | NullPointerException e) {
- e.printStackTrace();
- Log.e(TAG, "Error in getRawAverageVoltage");
- }
- return 0;
- }
-
- /**
- * Fetches a section of the ADC hardware buffer
- *
- * @param startingPosition Starting index
- * @param totalPoints Total points to fetch
- */
- private void fetchBuffer(int startingPosition, int totalPoints) {
- try {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER);
- mPacketHandler.sendInt(startingPosition);
- mPacketHandler.sendInt(totalPoints);
- for (int i = 0; i < totalPoints; i++) {
- byte[] data = new byte[2];
- mPacketHandler.read(data, 2);
- this.buffer[i] = (data[0] & 0xff) | ((data[1] << 8) & 0xff00);
- }
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- Log.e(TAG, "Error in fetching buffer");
- }
- }
-
- /**
- * Clears a section of the ADC hardware buffer
- *
- * @param startingPosition Starting index
- * @param totalPoints Total points to fetch
- */
- private void clearBuffer(int startingPosition, int totalPoints) {
- try {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.CLEAR_BUFFER);
- mPacketHandler.sendInt(startingPosition);
- mPacketHandler.sendInt(totalPoints);
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- Log.e(TAG, "Error in clearing buffer");
- }
- }
-
- /**
- * Fill a section of the ADC hardware buffer with data
- *
- * @param startingPosition Starting index
- * @param pointArray Total points to fetch
- */
- private void fillBuffer(int startingPosition, int[] pointArray) {
- try {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.FILL_BUFFER);
- mPacketHandler.sendInt(startingPosition);
- mPacketHandler.sendInt(pointArray.length);
- for (int aPointArray : pointArray) {
- mPacketHandler.sendInt(aPointArray);
- }
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- Log.e(TAG, "Error in filling Buffer");
- }
-
- }
-
- public void setDataSplitting(int dataSplitting) {
- this.dataSplitting = dataSplitting;
- }
-
- /**
- * Checks if PSLab device is found
- *
- * @return true is device found; false otherwise
- */
- public boolean isDeviceFound() {
- return mCommunicationHandler.isDeviceFound();
- }
-
- /**
- * Checks if PSLab device is connected
- *
- * @return true is device is connected; false otherwise
- */
- public boolean isConnected() {
- return mCommunicationHandler.isConnected();
- }
-
- /* DIGITAL SECTION */
-
- public Integer calculateDigitalChannel(String name) {
- if (Arrays.asList(DigitalChannel.digitalChannelNames).contains(name))
- return Arrays.asList(DigitalChannel.digitalChannelNames).indexOf(name);
- else {
- Log.v(TAG, "Invalid channel " + name + " , selecting LA1 instead ");
- return null;
- }
- }
-
- private Double getHighFrequencyBackup(String pin) {
- try {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.GET_HIGH_FREQUENCY);
- mPacketHandler.sendByte(this.calculateDigitalChannel(pin));
- int scale = mPacketHandler.getByte();
- long value = mPacketHandler.getLong();
- mPacketHandler.getAcknowledgement();
- return scale * value / 1.0e-1;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Retrieves the frequency of the signal connected to LA1. For frequencies > 1MHz
- * Also good for lower frequencies, but avoid using it since the oscilloscope cannot be used simultaneously due to hardware limitations.
- * The input frequency is fed to a 32 bit counter for a period of 100mS.
- * The value of the counter at the end of 100mS is used to calculate the frequency.
- *
- * @param pin The input pin to measure frequency from : ['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @return frequency
- */
- public Double getHighFrequency(String pin) {
- /*
- Retrieves the frequency of the signal connected to LA1. for frequencies > 1MHz
- also good for lower frequencies, but avoid using it since
- the oscilloscope cannot be used simultaneously due to hardware limitations.
- The input frequency is fed to a 32 bit counter for a period of 100mS.
- The value of the counter at the end of 100mS is used to calculate the frequency.
- */
- try {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.GET_ALTERNATE_HIGH_FREQUENCY);
- mPacketHandler.sendByte(this.calculateDigitalChannel(pin));
- int scale = mPacketHandler.getByte();
- long value = mPacketHandler.getLong();
- mPacketHandler.getAcknowledgement();
- return scale * value / 1.0e-1;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Frequency measurement on IDx.
- * Measures time taken for 16 rising edges of input signal.
- * Returns the frequency in Hertz
- *
- * @param channel The input to measure frequency from. ['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @return frequency
- */
- public Double getFrequency(String channel) {
- /*
- Frequency measurement on IDx.
- Measures time taken for 16 rising edges of input signal.
- returns the frequency in Hertz
- */
- if (channel == null) channel = "LA1";
- LinkedHashMap data;
- try {
- startOneChannelLA(channel, 1, channel, 3);
- Thread.sleep(250);
- data = getLAInitialStates();
- Thread.sleep(250);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- return fetchLAChannelFrequency(calculateDigitalChannel(channel), data);
- }
-
- /**
- * Stores a list of rising edges that occurred within the timeout period.
- *
- * @param channel The input to measure time between two rising edges.['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param skipCycle Number of points to skip. eg. Pendulums pass through light barriers twice every cycle. SO 1 must be skipped
- * @param timeout Number of seconds to wait for datapoints. (Maximum 60 seconds)
- * @return
- */
- public Double r2rTime(String channel, Integer skipCycle, Integer timeout) {
- /*
- Return a list of rising edges that occured within the timeout period.
- */
- if (skipCycle == null) skipCycle = 0;
- if (timeout == null) timeout = 5;
- if (timeout > 60) timeout = 60;
- this.startOneChannelLA(channel, 3, null, 0);
- long startTime = System.currentTimeMillis();
- while (System.currentTimeMillis() - startTime < timeout) {
- LinkedHashMap initialStates = this.getLAInitialStates();
- if (initialStates.get("A") == this.MAX_SAMPLES / 4)
- initialStates.put("A", 0);
- if (initialStates.get("A") >= skipCycle + 2) {
- long[] data = this.fetchLongDataFromLA(initialStates.get("A"), 1);
- LinkedHashMap tempMap = new LinkedHashMap<>();
- tempMap.put("LA1", initialStates.get("LA1"));
- tempMap.put("LA2", initialStates.get("LA2"));
- tempMap.put("LA3", initialStates.get("LA3"));
- tempMap.put("LA4", initialStates.get("LA4"));
- tempMap.put("RES", initialStates.get("RES"));
- double[] doubleData = new double[data.length];
- for (int i = 0; i < data.length; i++) {
- doubleData[i] = data[i];
- }
- this.dChannels.get(0).loadData(tempMap, doubleData);
- return 1e-6 * (this.dChannels.get(0).timestamps[skipCycle + 1] - this.dChannels.get(0).timestamps[0]);
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
- /**
- * Stores a list of falling edges that occured within the timeout period.
- *
- * @param channel The input to measure time between two falling edges.['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param skipCycle Number of points to skip. eg. Pendulums pass through light barriers twice every cycle. SO 1 must be skipped
- * @param timeout Number of seconds to wait for datapoints. (Maximum 60 seconds)
- * @return
- */
- public Double f2fTime(String channel, Integer skipCycle, Integer timeout) {
- /*
- Return a list of falling edges that occured within the timeout period.
- */
- if (skipCycle == null) skipCycle = 0;
- if (timeout == null) timeout = 5;
- if (timeout > 60) timeout = 60;
- this.startOneChannelLA(channel, 2, null, 0);
- long startTime = System.currentTimeMillis();
- while (System.currentTimeMillis() - startTime < timeout) {
- LinkedHashMap initialStates = this.getLAInitialStates();
- if (initialStates.get("A") == this.MAX_SAMPLES / 4)
- initialStates.put("A", 0);
- if (initialStates.get("A") >= skipCycle + 2) {
- long[] data = this.fetchLongDataFromLA(initialStates.get("A"), 1);
- LinkedHashMap tempMap = new LinkedHashMap<>();
- tempMap.put("LA1", initialStates.get("LA1"));
- tempMap.put("LA2", initialStates.get("LA2"));
- tempMap.put("LA3", initialStates.get("LA3"));
- tempMap.put("LA4", initialStates.get("LA4"));
- tempMap.put("RES", initialStates.get("RES"));
- double[] doubleData = new double[data.length];
- for (int i = 0; i < data.length; i++) {
- doubleData[i] = data[i];
- }
- this.dChannels.get(0).loadData(tempMap, doubleData);
- return 1e-6 * (this.dChannels.get(0).timestamps[skipCycle + 1] - this.dChannels.get(0).timestamps[0]);
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- return null;
- }
-
- /**
- * Measures time intervals between two logic level changes on any two digital inputs(both can be the same) and returns the calculated time.
- * For example, one can measure the time interval between the occurrence of a rising edge on LA1, and a falling edge on LA3.
- * If the returned time is negative, it simply means that the event corresponding to channel2 occurred first.
- *
- * @param channel1 The input pin to measure first logic level change
- * @param channel2 The input pin to measure second logic level change -['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param edge1 The type of level change to detect in order to start the timer - ['rising', 'falling', 'four rising edges']
- * @param edge2 The type of level change to detect in order to stop the timer - ['rising', 'falling', 'four rising edges']
- * @param timeout Use the timeout option if you're unsure of the input signal time period. Returns -1 if timed out
- * @return time
- */
- public Double measureInterval(String channel1, String channel2, String edge1, String edge2, Float timeout) {
- /*
- Measures time intervals between two logic level changes on any two digital inputs(both can be the same)
- For example, one can measure the time interval between the occurence of a rising edge on LA1, and a falling edge on LA3.
- If the returned time is negative, it simply means that the event corresponding to channel2 occurred first.
- Returns the calculated time
- */
-
- if (timeout == null) timeout = 0.1f;
- try {
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.INTERVAL_MEASUREMENTS);
- int timeoutMSB = ((int) (timeout * 64e6)) >> 16;
- mPacketHandler.sendInt(timeoutMSB);
- mPacketHandler.sendByte(this.calculateDigitalChannel(channel1) | (this.calculateDigitalChannel(channel2) << 4));
- int params = 0;
- if ("rising".equals(edge1))
- params |= 3;
- else if ("falling".equals(edge1))
- params |= 2;
- else
- params |= 4;
-
- if ("rising".equals(edge2))
- params |= 3 << 3;
- else if ("falling".equals(edge2))
- params |= 2 << 3;
- else
- params |= 4 << 3;
-
- mPacketHandler.sendByte(params);
- long A = mPacketHandler.getLong();
- long B = mPacketHandler.getLong();
- int tmt = mPacketHandler.getInt();
- mPacketHandler.getAcknowledgement();
- if (tmt > timeoutMSB || B == 0) return null;
-
- return (B - A + 20) / 64e6;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Duty cycle measurement on channel. Returns wavelength(seconds), and length of first half of pulse(high time)
- * Low time = (wavelength - high time)
- *
- * @param channel The input pin to measure wavelength and high time.['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param timeout Use the timeout option if you're unsure of the input signal time period. Returns 0 if timed out
- * @return Wavelength, Duty cycle
- */
- public double[] dutyCycle(String channel, Double timeout) {
- /*
- duty cycle measurement on channel
- returns wavelength(seconds), and length of first half of pulse(high time)
- low time = (wavelength - high time)
- */
- if (channel == null) channel = "LA1";
- if (timeout == null) timeout = 1.;
- Map data = this.measureMultipleDigitalEdges(channel, channel, "rising", "falling", 2, 2, timeout, null, true);
- double[] retData = new double[2];
- if (data != null) {
- double[] x = data.get("CHANNEL1");
- double[] y = data.get("CHANNEL2");
- if (x != null && y != null) { // Both timers registered something. did not timeout
- if (y[0] > 0) {
- retData[0] = y[0];
- retData[1] = x[1];
- } else {
- if (y[1] > x[1]) {
- retData[0] = -1;
- retData[1] = -1;
- return retData;
- }
- retData[0] = y[1];
- retData[1] = x[1];
- }
- double[] params = new double[2];
- params[0] = retData[1];
- params[1] = retData[0] / retData[1];
- if (params[1] > 0.5) {
- Log.v(TAG, Arrays.toString(x) + "\n" + Arrays.toString(y) + "\n" + Arrays.toString(retData));
- }
- return params;
- }
- }
- retData[0] = -1;
- retData[1] = -1;
- return retData;
- }
-
- /**
- * Duty cycle measurement on channel. Returns wavelength(seconds), and length of first half of pulse(high time)
- * Low time = (wavelength - high time)
- *
- * @param channel The input pin to measure wavelength and high time.['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param pulseType Type of pulse to detect. May be 'HIGH' or 'LOW'
- * @param timeout Use the timeout option if you're unsure of the input signal time period. Returns 0 if timed out
- * @return Pulse width
- */
- public Double pulseTime(String channel, String pulseType, Double timeout) {
- if (channel == null) channel = "LA1";
- if (pulseType == null) pulseType = "LOW";
- if (timeout == null) timeout = 0.1;
-
- Map data = this.measureMultipleDigitalEdges(channel, channel, "rising", "falling", 2, 2, timeout, null, true);
- if (data != null) {
- double[] x = data.get("CHANNEL1");
- double[] y = data.get("CHANNEL2");
- if (x != null && y != null) { // Both timers registered something. did not timeout
- if (y[0] > 0) {
- if ("HIGH".equals(pulseType))
- return y[0];
- else if ("LOW".equals(pulseType)) {
- return x[1] - y[0];
- }
- } else {
- if ("HIGH".equals(pulseType))
- return y[1];
- else if ("LOW".equals(pulseType)) {
- return Math.abs(y[0]);
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Measures a set of timestamped logic level changes(Type can be selected) from two different digital inputs.
- *
- * @param channel1 The input pin to measure first logic level change
- * @param channel2 The input pin to measure second logic level change -['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param edgeType1 The type of level change that should be recorded - ['rising', 'falling', 'four rising edges(default)']
- * @param edgeType2 The type of level change that should be recorded - ['rising', 'falling', 'four rising edges(default)']
- * @param points1 Number of data points to obtain for input 1 (Max 4)
- * @param points2 Number of data points to obtain for input 2 (Max 4)
- * @param timeout Use the timeout option if you're unsure of the input signal time period. returns -1 if timed out
- * @param SQR1 Set the state of SQR1 output(LOW or HIGH) and then start the timer. eg. SQR1 = 'LOW'
- * @param zero subtract the timestamp of the first point from all the others before returning. Default: True
- * @return time
- */
- private Map measureMultipleDigitalEdges(String channel1, String channel2, String edgeType1, String edgeType2, int points1, int points2, Double timeout, String SQR1, Boolean zero) {
-
- if (timeout == null) timeout = 0.1;
- try {
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.TIMING_MEASUREMENTS);
- int timeoutMSB = ((int) (timeout * 64e6)) >> 16;
- mPacketHandler.sendInt(timeoutMSB);
- mPacketHandler.sendByte(this.calculateDigitalChannel(channel1) | (this.calculateDigitalChannel(channel2) << 4));
- int params = 0;
- if ("rising".equals(edgeType1))
- params |= 3;
- else if ("falling".equals(edgeType1))
- params |= 2;
- else
- params |= 4;
-
- if ("rising".equals(edgeType2))
- params |= 3 << 3;
- else if ("falling".equals(edgeType2))
- params |= 2 << 3;
- else
- params |= 4 << 3;
- if (SQR1 != null) {
- params |= (1 << 6);
- if ("HIGH".equals(SQR1))
- params |= (1 << 7);
- }
- mPacketHandler.sendByte(params);
- if (points1 > 4) points1 = 4;
- if (points2 > 4) points2 = 4;
- mPacketHandler.sendByte(points1 | (points2 << 4));
-
- //mPacketHandler.waitForData(timeout); todo : complete waitForData in PacketHandler.java
- long[] A = new long[points1];
- long[] B = new long[points2];
- for (int i = 0; i < points1; i++)
- A[i] = mPacketHandler.getLong();
- for (int i = 0; i < points2; i++)
- B[i] = mPacketHandler.getLong();
- int tmt = mPacketHandler.getInt();
- mPacketHandler.getAcknowledgement();
- Map retData = new HashMap<>();
- if (tmt > timeoutMSB) {
- retData.put("CHANNEL1", null);
- retData.put("CHANNEL2", null);
- return retData;
- }
- if (zero == null) zero = true;
- double[] A1 = new double[A.length];
- double[] B1 = new double[B.length];
- if (zero) {
- for (int i = 0; i < A.length; i++) {
- A[i] -= A[0];
- A1[i] = A[i] / 64e6;
- }
- for (int i = 0; i < B.length; i++) {
- B[i] -= B[0];
- B1[i] = B[i] / 64e6;
- }
- } else {
- for (int i = 0; i < A.length; i++) {
- A1[i] = A[i] / 64e6;
- }
- for (int i = 0; i < B.length; i++) {
- B1[i] = B[i] / 64e6;
- }
- }
- retData.put("CHANNEL1", A1);
- retData.put("CHANNEL2", B1);
- return retData;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Log timestamps of rising/falling edges on one digital input
- *
- * @param waitingTime Total time to allow the logic analyzer to collect data. This is implemented using a simple sleep routine, so if large delays will be involved, refer to startOneChannelLA() to start the acquisition, and fetchLAChannels() to retrieve data from the hardware after adequate time. The retrieved data is stored in the array self.dchans[0].timestamps.
- * @param aquireChannel LA1',...,'LA4'
- * @param triggerChannel LA1',...,'LA4'
- * @param aquireMode EVERY_SIXTEENTH_RISING_EDGE = 5
- * EVERY_FOURTH_RISING_EDGE = 4
- * EVERY_RISING_EDGE = 3
- * EVERY_FALLING_EDGE = 2
- * EVERY_EDGE = 1
- * DISABLED = 0
- * default = 3
- * @param triggerMode same as aquireMode. default_value : 3
- * @return
- */
- public double[] captureEdgesOne(Integer waitingTime, String aquireChannel, String triggerChannel, Integer aquireMode, Integer triggerMode) {
- /*
- Log timestamps of rising/falling edges on one digital input
- */
- if (waitingTime == null) waitingTime = 1;
- if (aquireChannel == null) aquireChannel = "LA1";
- if (triggerChannel == null) triggerChannel = aquireChannel;
- if (aquireMode == null) aquireMode = 3;
- if (triggerMode == null) triggerMode = 3;
- this.startOneChannelLA(aquireChannel, aquireMode, triggerChannel, triggerMode);
- try {
- Thread.sleep(waitingTime * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- LinkedHashMap data = this.getLAInitialStates();
- long[] temp = this.fetchLongDataFromLA(data.get("A"), 1);
- double[] retData = new double[temp.length];
- for (int i = 0; i < temp.length; i++) {
- retData[i] = temp[i] / 64e6;
- }
- return retData;
- }
-
- /**
- * Start logging timestamps of rising/falling edges on LA1
- *
- * @param trigger Bool . Enable edge trigger on LA1. use keyword argument edge = 'rising' or 'falling'
- * @param channel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param maximumTime Total time to sample. If total time exceeds 67 seconds, a prescaler will be used in the reference clock.
- * @param triggerChannels array of digital input names that can trigger the acquisition. Eg, trigger = ['LA1','LA2','LA3'] will triggger when a logic change specified by the keyword argument 'edge' occurs on either or the three specified trigger inputs.
- * @param edge 'rising' or 'falling' . trigger edge type for trigger_channels.
- */
- public void startOneChannelLABackup(Integer trigger, String channel, Integer maximumTime, ArrayList triggerChannels, String edge) {
- /*
- start logging timestamps of rising/falling edges on LA1
- */
- try {
- this.clearBuffer(0, this.MAX_SAMPLES / 2);
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.START_ONE_CHAN_LA);
- mPacketHandler.sendInt(this.MAX_SAMPLES / 4);
- if (triggerChannels != null & (trigger & 1) != 0) {
- if (triggerChannels.contains("LA1")) trigger |= (1 << 4);
- if (triggerChannels.contains("LA2")) trigger |= (1 << 5);
- if (triggerChannels.contains("LA3")) trigger |= (1 << 6);
- } else {
- trigger |= 1 << (this.calculateDigitalChannel(channel) + 4);
- }
- if ("rising".equals(edge)) trigger |= 2;
- trigger |= (this.calculateDigitalChannel(channel) << 2);
-
- mPacketHandler.sendByte(trigger);
- mPacketHandler.getAcknowledgement();
- this.digitalChannelsInBuffer = 1;
- for (DigitalChannel dChan : this.dChannels) {
- dChan.prescalar = 0;
- dChan.dataType = "long";
- dChan.length = this.MAX_SAMPLES / 4;
- dChan.maxTime = (int) (maximumTime * 1e6);
- dChan.mode = DigitalChannel.EVERY_EDGE;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Start logging timestamps of rising/falling edges on LA1.
- *
- * @param channel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param channelMode acquisition mode default value: 1(EVERY_EDGE)
- * - EVERY_SIXTEENTH_RISING_EDGE = 5
- * - EVERY_FOURTH_RISING_EDGE = 4
- * - EVERY_RISING_EDGE = 3
- * - EVERY_FALLING_EDGE = 2
- * - EVERY_EDGE = 1
- * - DISABLED = 0
- * @param triggerChannel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param triggerMode 1=Falling edge, 0=Rising Edge, -1=Disable Trigger
- */
- public void startOneChannelLA(String channel, Integer channelMode, String triggerChannel, Integer triggerMode) {
- if (channel == null) channel = "LA1";
- if (channelMode == null) channelMode = 1;
- if (triggerChannel == null) triggerChannel = "LA1";
- if (triggerMode == null) triggerMode = 3;
- try {
- this.clearBuffer(0, this.MAX_SAMPLES);
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.START_ALTERNATE_ONE_CHAN_LA);
- mPacketHandler.sendInt(this.MAX_SAMPLES / 4);
- int aqChannel = this.calculateDigitalChannel(channel);
- int aqMode = channelMode;
- int trChannel = this.calculateDigitalChannel(triggerChannel);
- int trMode = triggerMode;
- mPacketHandler.sendByte((aqChannel << 4) | aqMode);
- mPacketHandler.sendByte((trChannel << 4) | trMode);
- mPacketHandler.getAcknowledgement();
- this.digitalChannelsInBuffer = 1;
- this.dChannels.get(aqChannel).prescalar = 0;
- this.dChannels.get(aqChannel).dataType = "long";
- this.dChannels.get(aqChannel).length = this.MAX_SAMPLES / 4;
- this.dChannels.get(aqChannel).maxTime = (int) (67 * 1e6);
- this.dChannels.get(aqChannel).mode = channelMode;
- this.dChannels.get(aqChannel).channelName = channel;
- if (trMode == 3 || trMode == 4 || trMode == 5)
- this.dChannels.get(aqChannel).initialStateOverride = 2;
- else if (trMode == 2)
- this.dChannels.get(0).initialStateOverride = 1;
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Start logging timestamps of rising/falling edges on LA1,LA2
- *
- * @param channels Channels to acquire data from . default ['LA1','LA2']
- * @param modes modes for each channel. Array . default value: [1,1]
- * - EVERY_SIXTEENTH_RISING_EDGE = 5
- * - EVERY_FOURTH_RISING_EDGE = 4
- * - EVERY_RISING_EDGE = 3
- * - EVERY_FALLING_EDGE = 2
- * - EVERY_EDGE = 1
- * - DISABLED = 0
- * @param maximumTime Total time to sample. If total time exceeds 67 seconds, a prescaler will be used in the reference clock
- * @param trigger Bool . Enable rising edge trigger on LA1
- * @param edge 'rising' or 'falling' . trigger edge type for trigger_channels.
- * @param triggerChannel channel to trigger on . Any digital input. default CH1
- */
- public void startTwoChannelLA(ArrayList channels, ArrayList modes, Integer maximumTime, Integer trigger, String edge, String triggerChannel) {
- if (maximumTime == null) maximumTime = 67;
- if (trigger == null) trigger = 0;
- if (edge == null) edge = "rising";
- if (channels == null) {
- channels = new ArrayList<>();
- channels.add("LA1");
- channels.add("LA2");
- }
- if (modes == null) {
- modes = new ArrayList<>();
- modes.add(1);
- modes.add(1);
- }
- int[] chans = new int[]{this.calculateDigitalChannel(channels.get(0)), this.calculateDigitalChannel(channels.get(1))};
- if (triggerChannel == null) triggerChannel = channels.get(0);
- if (trigger != 0) {
- trigger = 1;
- if ("falling".equals(edge)) trigger |= 2;
- trigger |= (this.calculateDigitalChannel(triggerChannel) << 4);
- }
- try {
- this.clearBuffer(0, this.MAX_SAMPLES);
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.START_TWO_CHAN_LA);
- mPacketHandler.sendInt(this.MAX_SAMPLES / 4);
- mPacketHandler.sendByte(trigger);
- mPacketHandler.sendByte((modes.get(1) << 4) | modes.get(0));
- mPacketHandler.sendByte((chans[1] << 4) | chans[0]);
- mPacketHandler.getAcknowledgement();
- for (int i = 0; i < 2; i++) {
- DigitalChannel temp = this.dChannels.get(i);
- temp.prescalar = 0;
- temp.length = this.MAX_SAMPLES / 4;
- temp.dataType = "long";
- temp.maxTime = (int) (maximumTime * 1e6);
- temp.mode = modes.get(i);
- temp.channelNumber = chans[i];
- temp.channelName = channels.get(i);
- }
- this.digitalChannelsInBuffer = 2;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Start logging timestamps of rising/falling edges on LA1,LA2,LA3
- *
- * @param modes modes for each channel. Array. default value: [1,1,1]
- * - EVERY_SIXTEENTH_RISING_EDGE = 5
- * - EVERY_FOURTH_RISING_EDGE = 4
- * - EVERY_RISING_EDGE = 3
- * - EVERY_FALLING_EDGE = 2
- * - EVERY_EDGE = 1
- * - DISABLED = 0
- * @param triggerChannel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- * @param triggerMode same as modes(previously documented keyword argument)
- * default_value : 3
- */
- public void startThreeChannelLA(ArrayList modes, String triggerChannel, Integer triggerMode) {
- if (modes == null) {
- modes = new ArrayList<>();
- modes.add(1);
- modes.add(1);
- modes.add(1);
- }
- if (triggerChannel == null) {
- triggerChannel = "LA1";
- }
- if (triggerMode == null) {
- triggerMode = 3;
- }
- try {
- this.clearBuffer(0, this.MAX_SAMPLES);
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.START_THREE_CHAN_LA);
- mPacketHandler.sendInt(this.MAX_SAMPLES / 4);
- int trChan = this.calculateDigitalChannel(triggerChannel);
- int trMode = triggerMode;
-
- mPacketHandler.sendInt(modes.get(0) | (modes.get(1) << 4) | (modes.get(2) << 8));
- mPacketHandler.sendByte((trChan << 4) | trMode);
- mPacketHandler.getAcknowledgement();
- this.digitalChannelsInBuffer = 3;
-
- for (int i = 0; i < 3; i++) {
- DigitalChannel temp = this.dChannels.get(i);
- temp.prescalar = 0;
- temp.length = this.MAX_SAMPLES / 4;
- temp.dataType = "int";
- temp.maxTime = (int) (1e3);
- temp.mode = modes.get(i);
- temp.channelName = DigitalChannel.digitalChannelNames[i];
- if (trMode == 3 || trMode == 4 || trMode == 5) {
- temp.initialStateOverride = 2;
- } else if (trMode == 2) {
- temp.initialStateOverride = 1;
- }
- }
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Four channel Logic Analyzer.
- * Start logging timestamps from a 64MHz counter to record level changes on LA1,LA2,LA3,LA4.
- * triggerChannel[0] -> LA1
- * triggerChannel[1] -> LA2
- * triggerChannel[2] -> LA3
- *
- * @param trigger Bool. Enable rising edge trigger on LA1.
- * @param maximumTime Maximum delay expected between two logic level changes.
- * If total time exceeds 1 mS, a prescaler will be used in the reference clock.
- * However, this only refers to the maximum time between two successive level changes. If a delay larger
- * than .26 S occurs, it will be truncated by modulo .26 S.
- * If you need to record large intervals, try single channel/two channel modes which use 32 bit counters
- * capable of time interval up to 67 seconds.
- * @param modes modes for each channel. List with four elements\n
- * default values: [1,1,1,1]
- * - EVERY_SIXTEENTH_RISING_EDGE = 5
- * - EVERY_FOURTH_RISING_EDGE = 4
- * - EVERY_RISING_EDGE = 3
- * - EVERY_FALLING_EDGE = 2
- * - EVERY_EDGE = 1
- * - DISABLED = 0
- * @param edge 'rising' or 'falling'. Trigger edge type for trigger_channels.
- * @param triggerChannel ['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- */
- public void startFourChannelLA(Integer trigger, Double maximumTime, ArrayList modes, String edge, ArrayList triggerChannel) {
- if (trigger == null) trigger = 1;
- if (maximumTime == null) maximumTime = 0.001;
- if (modes == null) {
- modes = new ArrayList<>();
- modes.add(1);
- modes.add(1);
- modes.add(1);
- }
- if (edge == null) edge = "0";
- this.clearBuffer(0, this.MAX_SAMPLES);
- int prescale = 0;
- try {
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.START_FOUR_CHAN_LA);
- mPacketHandler.sendInt(this.MAX_SAMPLES / 4);
- mPacketHandler.sendInt(modes.get(0) | (modes.get(1) << 4) | (modes.get(2) << 8) | (modes.get(3) << 12));
- mPacketHandler.sendByte(prescale);
- int triggerOptions = 0;
- if (triggerChannel.get(0)) triggerOptions |= 4;
- if (triggerChannel.get(1)) triggerOptions |= 8;
- if (triggerChannel.get(2)) triggerOptions |= 16;
- if (triggerOptions == 0)
- triggerOptions |= 4; // Select one trigger channel(LA1) if none selected
- if ("rising".equals(edge)) triggerOptions |= 2;
- trigger |= triggerOptions;
- mPacketHandler.sendByte(trigger);
- mPacketHandler.getAcknowledgement();
- this.digitalChannelsInBuffer = 4;
- int i = 0;
- for (DigitalChannel dChan : this.dChannels) {
- dChan.prescalar = prescale;
- dChan.dataType = "int";
- dChan.length = this.MAX_SAMPLES / 4;
- dChan.maxTime = (int) (maximumTime * 1e6);
- dChan.mode = modes.get(i);
- dChan.channelName = DigitalChannel.digitalChannelNames[i];
- i++;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Fetches the initial states of digital inputs that were recorded right before the Logic analyzer was started,
- * and the total points each channel recorded.
- *
- * @return CH1 progress,CH2 progress,CH3 progress,CH4 progress,[LA1,LA2,LA3,LA4]. eg. [1,0,1,1]
- */
- public LinkedHashMap getLAInitialStates() {
- try {
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.GET_INITIAL_DIGITAL_STATES);
- byte[] initialStatesBytes = new byte[13];
- mPacketHandler.read(initialStatesBytes, 13);
- int initial = (initialStatesBytes[0] & 0xff) | ((initialStatesBytes[1] << 8) & 0xff00);
- int A = (((initialStatesBytes[2] & 0xff) | ((initialStatesBytes[3] << 8) & 0xff00)) - initial) / 2;
- int B = (((initialStatesBytes[4] & 0xff) | ((initialStatesBytes[5] << 8) & 0xff00)) - initial) / 2 - MAX_SAMPLES / 4;
- int C = (((initialStatesBytes[6] & 0xff) | ((initialStatesBytes[7] << 8) & 0xff00)) - initial) / 2 - 2 * MAX_SAMPLES / 4;
- int D = (((initialStatesBytes[8] & 0xff) | ((initialStatesBytes[9] << 8) & 0xff00)) - initial) / 2 - 3 * MAX_SAMPLES / 4;
- int s = initialStatesBytes[10];
- int sError = initialStatesBytes[11];
- //mPacketHandler.getAcknowledgement();
-
- if (A == 0) A = this.MAX_SAMPLES / 4;
- if (B == 0) B = this.MAX_SAMPLES / 4;
- if (C == 0) C = this.MAX_SAMPLES / 4;
- if (D == 0) D = this.MAX_SAMPLES / 4;
-
- if (A < 0) A = 0;
- if (B < 0) B = 0;
- if (C < 0) C = 0;
- if (D < 0) D = 0;
-
- LinkedHashMap retData = new LinkedHashMap<>();
- retData.put("A", A);
- retData.put("B", B);
- retData.put("C", C);
- retData.put("D", D);
-
- // putting 1 -> true & 0 -> false
- if ((s & 1) != 0)
- retData.put("LA1", 1);
- else
- retData.put("LA1", 0);
-
- if ((s & 2) != 0)
- retData.put("LA2", 1);
- else
- retData.put("LA2", 0);
-
- if ((s & 4) != 0)
- retData.put("LA3", 1);
- else
- retData.put("LA3", 0);
-
- if ((s & 8) != 0)
- retData.put("LA4", 1);
- else
- retData.put("LA4", 0);
-
- if ((s & 16) != 0)
- retData.put("RES", 1);
- else
- retData.put("RES", 0);
-
- return retData;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Stop any running logic analyzer function.
- */
- public void stopLA() {
- try {
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.STOP_LA);
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Fetches the data stored by DMA. integer address increments
- *
- * @param bytes number of readings(integer) to fetch
- * @param channel channel number (1-4)
- * @return array of integer data fetched from Logic Analyser.
- */
- public int[] fetchIntDataFromLA(Integer bytes, Integer channel) {
- if (channel == null) channel = 1;
- try {
- ArrayList l = new ArrayList<>();
- for (int i = 0; i < bytes / this.dataSplitting; i++) {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER);
- mPacketHandler.sendInt(2500 * (channel - 1) + (i * this.dataSplitting));
- mPacketHandler.sendInt(this.dataSplitting);
- byte[] data = new byte[this.dataSplitting * 2 + 1];
- mPacketHandler.read(data, this.dataSplitting * 2 + 1);
- for (int j = 0; j < data.length - 1; j++)
- l.add((int) data[j] & 0xff);
- }
-
- if ((bytes % this.dataSplitting) != 0) {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.RETRIEVE_BUFFER);
- mPacketHandler.sendInt(bytes - bytes % this.dataSplitting);
- mPacketHandler.sendInt(bytes % this.dataSplitting);
- byte[] data = new byte[2 * (bytes % this.dataSplitting) + 1];
- mPacketHandler.read(data, 2 * (bytes % this.dataSplitting) + 1);
- for (int j = 0; j < data.length - 1; j++)
- l.add((int) data[j] & 0xff);
- }
- if (!l.isEmpty()) {
- StringBuilder stringBuilder = new StringBuilder();
- int[] timeStamps = new int[(int) bytes + 1];
- for (int i = 0; i < (int) (bytes); i++) {
- int t = (l.get(i * 2) | (l.get(i * 2 + 1) << 8));
- timeStamps[i + 1] = t;
- stringBuilder.append(String.valueOf(t));
- stringBuilder.append(" ");
- }
- Log.v("Fetched points : ", stringBuilder.toString());
- //mPacketHandler.getAcknowledgement();
- Arrays.sort(timeStamps);
- timeStamps[0] = 1;
- return timeStamps;
- } else {
- Log.e("Error : ", "Obtained bytes = 0");
- int[] temp = new int[2501];
- Arrays.fill(temp, 0);
- return temp;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Fetches the data stored by DMA. long address increments.
- *
- * @param bytes number of readings(long integers) to fetch
- * @param channel channel number (1-2)
- * @return array of long integers data fetched from Logic Analyser.
- */
- public long[] fetchLongDataFromLA(Integer bytes, Integer channel) {
- if (channel == null) channel = 1;
- try {
- mPacketHandler.sendByte(mCommandsProto.TIMING);
- mPacketHandler.sendByte(mCommandsProto.FETCH_LONG_DMA_DATA);
- mPacketHandler.sendInt(bytes);
- mPacketHandler.sendByte(channel - 1);
- byte[] readData = new byte[bytes * 4];
- mPacketHandler.read(readData, bytes * 4);
- mPacketHandler.getAcknowledgement();
- long[] data = new long[bytes];
- for (int i = 0; i < bytes; i++) {
- data[i] = ByteBuffer.wrap(Arrays.copyOfRange(readData, 4 * i, 4 * i + 4)).order(ByteOrder.LITTLE_ENDIAN).getLong();
- }
- // Trimming array data
- int markerA = 0;
- for (int i = 0; i < data.length; i++) {
- if (data[i] != 0) {
- markerA = i;
- break;
- }
- }
- int markerB = 0;
- for (int i = data.length - 1; i >= 0; i--) {
- if (data[i] != 0) {
- markerB = i;
- break;
- }
- }
- return Arrays.copyOfRange(data, markerA, markerB + 1);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Reads and stores the channels in this.dChannels.
- *
- * @return true if LA channels fetched successfully.
- */
- public boolean fetchLAChannels() {
- LinkedHashMap data = this.getLAInitialStates();
- for (int i = 0; i < 4; i++) {
- if (this.dChannels.get(i).channelNumber < this.digitalChannelsInBuffer) {
- this.fetchLAChannel(i, data);
- }
- }
- return true;
- }
-
- /**
- * @param channelNumber Channel number being used e.g. CH1, CH2, CH3, CH4.
- * @param initialStates State of the digital inputs. returns dictionary with keys 'LA1','LA2','LA3','LA4','RES'
- * @return true if data fetched/loaded successfully.
- */
- public boolean fetchLAChannel(Integer channelNumber, LinkedHashMap initialStates) {
- DigitalChannel dChan = this.dChannels.get(channelNumber);
-
- LinkedHashMap tempMap = new LinkedHashMap<>();
- tempMap.put("LA1", initialStates.get("LA1"));
- tempMap.put("LA2", initialStates.get("LA2"));
- tempMap.put("LA3", initialStates.get("LA3"));
- tempMap.put("LA4", initialStates.get("LA4"));
- tempMap.put("RES", initialStates.get("RES"));
-
- // Used LinkedHashMap above (initialStates) in which iteration is done sequentially as were inserted
- int i = 0;
- for (Map.Entry entry : initialStates.entrySet()) {
- if (dChan.channelNumber == i) {
- i = entry.getValue();
- break;
- }
- i++;
- }
-
- int[] temp = this.fetchIntDataFromLA(i, dChan.channelNumber + 1);
- double[] data = new double[temp.length - 1];
- if (temp[0] == 1) {
- for (int j = 1; j < temp.length; j++) {
- data[j - 1] = temp[j];
- }
- } else {
- Log.e("Error : ", "Can't load data");
- return false;
- }
- dChan.loadData(tempMap, data);
-
- dChan.generateAxes();
- return true;
- }
-
- public double fetchLAChannelFrequency(Integer channelNumber, LinkedHashMap initialStates) {
- DigitalChannel dChan = this.dChannels.get(channelNumber);
-
- LinkedHashMap tempMap = new LinkedHashMap<>();
- tempMap.put("LA1", initialStates.get("LA1"));
- tempMap.put("LA2", initialStates.get("LA2"));
- tempMap.put("LA3", initialStates.get("LA3"));
- tempMap.put("LA4", initialStates.get("LA4"));
- tempMap.put("RES", initialStates.get("RES"));
-
- // Used LinkedHashMap above (initialStates) in which iteration is done sequentially as were inserted
- int i = 0;
- for (Map.Entry entry : initialStates.entrySet()) {
- if (dChan.channelNumber == i) {
- i = entry.getValue();
- break;
- }
- i++;
- }
-
- int[] temp = this.fetchIntDataFromLA(i, dChan.channelNumber + 1);
- double[] data = new double[temp.length - 1];
- if (temp[0] == 1) {
- for (int j = 1; j < temp.length; j++) {
- data[j - 1] = temp[j];
- }
- } else {
- Log.e("Error : ", "Can't load data");
- return -1;
- }
- dChan.loadData(tempMap, data);
-
- dChan.generateAxes();
- int count = 0;
- double[] yAxis = dChan.getYAxis();
- for (int j = 1; j < yAxis.length; j++) {
- if (yAxis[i] != yAxis[i - 1]) {
- count++;
- }
- }
- if (count == this.MAX_SAMPLES / 2 - 2) {
- LAChannelFrequency = 0;
- } else if (count != 0 && count != this.MAX_SAMPLES / 2 - 2 && LAChannelFrequency != count) {
- LAChannelFrequency = count;
- }
- return LAChannelFrequency;
- }
-
- public DigitalChannel getDigitalChannel(int i) {
- return dChannels.get(i);
- }
-
- /**
- * Gets the state of the digital inputs.
- *
- * @return dictionary with keys 'LA1','LA2','LA3','LA4'.
- */
- public Map getStates() {
- try {
- mPacketHandler.sendByte(mCommandsProto.DIN);
- mPacketHandler.sendByte(mCommandsProto.GET_STATES);
- byte state = mPacketHandler.getByte();
- mPacketHandler.getAcknowledgement();
- Map states = new LinkedHashMap<>();
- states.put("LA1", ((state & 1) != 0));
- states.put("LA2", ((state & 2) != 0));
- states.put("LA3", ((state & 4) != 0));
- states.put("LA4", ((state & 8) != 0));
- return states;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Fetch the state of given input ID.
- *
- * @param inputID the input channel
- * 'LA1' -> state of LA1
- * 'LA4' -> state of LA4
- * @return the logic level on the specified input (LA1,LA2,LA3, or LA4)
- */
- public Boolean getState(String inputID) {
- return this.getStates().get(inputID);
- }
-
- /**
- * set the logic level on digital outputs SQR1,SQR2,SQR3,SQR4.
- *
- * @param args SQR1,SQR2,SQR3,SQR4
- * states(0 or 1)
- */
- public void setState(Map args) {
- int data = 0;
- if (args.containsKey("SQR1")) {
- data |= (0x10 | args.get("SQR1"));
- }
- if (args.containsKey("SQR2")) {
- data |= (0x20 | (args.get("SQR2") << 1));
- }
- if (args.containsKey("SQR3")) {
- data |= (0x40 | (args.get("SQR3") << 2));
- }
- if (args.containsKey("SQR4")) {
- data |= (0x80 | (args.get("SQR4") << 3));
- }
- try {
- mPacketHandler.sendByte(mCommandsProto.DOUT);
- mPacketHandler.sendByte(mCommandsProto.SET_STATE);
- mPacketHandler.sendByte(data);
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- }
-
- /**
- * Count pulses on a digital input. Retrieve total pulses using readPulseCount.
- *
- * @param channel The input pin to measure rising edges on : ['LA1','LA2','LA3','LA4','RES','EXT','FRQ']
- */
- public void countPulses(String channel) {
- if (channel == null) channel = "RES";
- try {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.START_COUNTING);
- mPacketHandler.sendByte(this.calculateDigitalChannel(channel));
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Read pulses counted using a digital input. Call countPulses before using this.
- *
- * @return number of pulse.
- */
- public int readPulseCount() {
- try {
- mPacketHandler.sendByte(mCommandsProto.COMMON);
- mPacketHandler.sendByte(mCommandsProto.FETCH_COUNT);
- int count = mPacketHandler.getVoltageSummation();
- return 10 * count;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return -1;
- }
-
- public void setCapacitorState(int state, int t) {
- try {
- mPacketHandler.sendByte(mCommandsProto.ADC);
- mPacketHandler.sendByte(mCommandsProto.SET_CAP);
- mPacketHandler.sendByte(state);
- mPacketHandler.sendInt(t);
- mPacketHandler.getAcknowledgement();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public double[] captureCapacitance(int samples, int timeGap) {
- AnalyticsClass analyticsClass = new AnalyticsClass();
- this.setCapacitorState(1, 50000);
- Map data = this.captureFullSpeedHr("CAP", samples, timeGap, Arrays.asList("READ_CAP"));
- double[] x = data.get("x");
- double[] y = data.get("y");
- for (int i = 0; i < x.length; i++) {
- x[i] = x[i] * 1e-6;
- }
- ArrayList