Пример #1
0
  /** DESCRIPTION: Performs the steps required to display the data in the plot widget. */
  private void drawPlot() {

    // adjust fonts to reflect preferences
    setPlotFontSizes();

    // add series of data points to plot (x,y)
    plot.addSeries(getPlotSeries(), plotFormatter);

    // set the boundaries for the X and Y-axis based on the data values
    setPlotAxisBoundaries();

    // add a line reflecting data average
    if (average > 0) {
      plot.addSeries(getAverageSeries(), avgFormatter);

      // specify format of the average point label
      avgFormatter.setPointLabeler(
          new PointLabeler() {
            @Override
            public String getLabel(XYSeries series, int index) {
              return (index == 0) ? ylabels.format(series.getY(index)) : "";
            }
          });
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.data_layout);

    d_pb_ll = (LinearLayout) findViewById(R.id.data_progressbar_ll);
    dataUsedText = (TextView) findViewById(R.id.dataUsedText);
    mProgress = (ProgressBar) findViewById(R.id.percentDataUsed);
    dell = (LinearLayout) findViewById(R.id.data_error);
    detv = (TextView) findViewById(R.id.tv_failure);
    deb = (Button) findViewById(R.id.button_send_data);
    actionbar = getSupportActionBar();
    actionbar.setTitle("Data Usage");
    actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionbar.setHomeButtonEnabled(true);
    actionbar.setDisplayHomeAsUpEnabled(true);

    graph = (XYPlot) findViewById(R.id.mySimpleXYPlot);
    graph.setOnTouchListener(this);
    graph.setMarkupEnabled(false);

    labels = new Long[288];
    downdata = new Float[288];
    totaldata = new Float[288];

    httpclient = ConnectionHelper.getThreadSafeClient();
    httpclient.getCookieStore().clear();
    BasicClientCookie cookie =
        new BasicClientCookie("AUTHCOOKIE", ConnectionHelper.getPNAAuthCookie(this, httpclient));
    cookie.setDomain(".pna.utexas.edu");
    httpclient.getCookieStore().addCookie(cookie);
    new fetchDataTask(httpclient).execute();
    new fetchProgressTask(httpclient).execute();
  }
    /**
     * sectionalFFT takes an array with size greater than HISTORY_SIZE and creates FFT frames to
     * graph. The graph's domain is equal to HISTORY_SIZE
     *
     * @param input
     */
    private void sectionalFFT(double[] input) {
      AppLog.APP_TAG = "sectionalFFT";
      // Split this data into pieces that are HISTORY_SIZE elements in size
      int nFrames = input.length / HISTORY_SIZE; // Number of frames we will create from a mic read
      Number[] graphable = new Number[HISTORY_SIZE];
      double[] section = new double[HISTORY_SIZE];

      AppLog.logString("input.length: " + input.length + " nFrames: " + nFrames);

      // for the number of sections
      for (int j = 1; j < nFrames + 1; j++) {
        // Get the section
        for (int i = 0; i < HISTORY_SIZE; i++)
          section[i] = input[i * j]; // get the fft magnitude of 64 value frame
        graphable = fft_mag(section);
        audioHist.clear();
        for (int i = 0; i < graphable.length; i++) audioHist.add(i, graphable[i]);

        // adjust the Range (y axis) to be as long as it needs to be.
        // plot.setRangeBoundaries(0, max(graphable), BoundaryMode.FIXED);
        plot.setRangeBoundaries(30, 100, BoundaryMode.FIXED);
        // update the graph.
        audioHistSeries.setModel(audioHist, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY);
        plot.setDomainBoundaries(0, graphable.length, BoundaryMode.FIXED);
        try {
          dynamicPlot.postRedraw();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
 private void onS2CheckBoxClicked(boolean checked) {
   if (checked) {
     plot.addSeries(series2, formatter2);
   } else {
     plot.removeSeries(series2);
   }
   plot.redraw();
 }
Пример #5
0
 @Override
 public void onStart() {
   super.onStart();
   // default display
   //		displayData( SystemInfo.PLOT_BATTERY_COMMENT, SystemInfo.DB_TABLENAME_BATTERY );
   XYPlot plot = (XYPlot) findViewById(R.id.xyplot);
   plot.setTitle("EMPTY");
 }
Пример #6
0
 private void plotAltitudeHistory() {
   SensorHistory altitudeLongHistory =
       new SensorHistory(
           Environment.getExternalStorageDirectory().getPath() + "/Sensors/altitude.dat");
   longHistoryPlot.setRangeLabel("Altitude (m)");
   longHistoryPlot.getRangeLabelWidget().pack();
   longHistorySeries.setModel(altitudeLongHistory, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY);
   longHistoryPlot.redraw();
 }
Пример #7
0
 private void plotTemperatureHistory() {
   SensorHistory temperatureLongHistory =
       new SensorHistory(
           Environment.getExternalStorageDirectory().getPath() + "/Sensors/temperature.dat");
   longHistoryPlot.setRangeLabel("Temperature (ºC)");
   longHistoryPlot.getRangeLabelWidget().pack();
   longHistorySeries.setModel(temperatureLongHistory, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY);
   longHistoryPlot.redraw();
 }
  private void onPlotClicked(PointF point) {

    // make sure the point lies within the graph area.  we use gridrect
    // because it accounts for margins and padding as well.
    if (plot.containsPoint(point.x, point.y)) {
      Number x = plot.getXVal(point);
      Number y = plot.getYVal(point);

      selection = null;
      double xDistance = 0;
      double yDistance = 0;

      // find the closest value to the selection:
      for (SeriesBundle<XYSeries, ? extends XYSeriesFormatter> sfPair :
          plot.getRegistry().getSeriesAndFormatterList()) {
        XYSeries series = sfPair.getSeries();
        for (int i = 0; i < series.size(); i++) {
          Number thisX = series.getX(i);
          Number thisY = series.getY(i);
          if (thisX != null && thisY != null) {
            double thisXDistance = Region.measure(x, thisX).doubleValue();
            double thisYDistance = Region.measure(y, thisY).doubleValue();
            if (selection == null) {
              selection = new Pair<>(i, series);
              xDistance = thisXDistance;
              yDistance = thisYDistance;
            } else if (thisXDistance < xDistance) {
              selection = new Pair<>(i, series);
              xDistance = thisXDistance;
              yDistance = thisYDistance;
            } else if (thisXDistance == xDistance
                && thisYDistance < yDistance
                && thisY.doubleValue() >= y.doubleValue()) {
              selection = new Pair<>(i, series);
              xDistance = thisXDistance;
              yDistance = thisYDistance;
            }
          }
        }
      }

    } else {
      // if the press was outside the graph area, deselect:
      selection = null;
    }

    if (selection == null) {
      selectionWidget.setText(NO_SELECTION_TXT);
    } else {
      selectionWidget.setText(
          "Selected: "
              + selection.second.getTitle()
              + " Value: "
              + selection.second.getY(selection.first));
    }
    plot.redraw();
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {

    // android boilerplate stuff
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dynamicxyplot_example);

    // get handles to our View defined in layout.xml:
    dynamicPlot = (XYPlot) findViewById(R.id.dynamicXYPlot);

    plotUpdater = new MyPlotUpdater(dynamicPlot);

    // only display whole numbers in domain labels
    dynamicPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("0"));

    // getInstance and position datasets:
    data = new SampleDynamicXYDatasource();
    SampleDynamicSeries sine1Series = new SampleDynamicSeries(data, 0, "Sine 1");
    SampleDynamicSeries sine2Series = new SampleDynamicSeries(data, 1, "Sine 2");

    LineAndPointFormatter formatter1 =
        new LineAndPointFormatter(Color.rgb(0, 0, 0), null, null, null);
    formatter1.getLinePaint().setStrokeJoin(Paint.Join.ROUND);
    formatter1.getLinePaint().setStrokeWidth(10);
    dynamicPlot.addSeries(sine1Series, formatter1);

    LineAndPointFormatter formatter2 =
        new LineAndPointFormatter(Color.rgb(0, 0, 200), null, null, null);
    formatter2.getLinePaint().setStrokeWidth(10);
    formatter2.getLinePaint().setStrokeJoin(Paint.Join.ROUND);

    // formatter2.getFillPaint().setAlpha(220);
    dynamicPlot.addSeries(sine2Series, formatter2);

    // hook up the plotUpdater to the data model:
    data.addObserver(plotUpdater);

    // thin out domain tick labels so they dont overlap each other:
    dynamicPlot.setDomainStepMode(XYStepMode.INCREMENT_BY_VAL);
    dynamicPlot.setDomainStepValue(5);

    dynamicPlot.setRangeStepMode(XYStepMode.INCREMENT_BY_VAL);
    dynamicPlot.setRangeStepValue(10);

    dynamicPlot.setRangeValueFormat(new DecimalFormat("###.#"));

    // uncomment this line to freeze the range boundaries:
    dynamicPlot.setRangeBoundaries(-100, 100, BoundaryMode.FIXED);

    // create a dash effect for domain and range grid lines:
    DashPathEffect dashFx =
        new DashPathEffect(new float[] {PixelUtils.dpToPix(3), PixelUtils.dpToPix(3)}, 0);
    dynamicPlot.getGraphWidget().getDomainGridLinePaint().setPathEffect(dashFx);
    dynamicPlot.getGraphWidget().getRangeGridLinePaint().setPathEffect(dashFx);
  }
Пример #10
0
  /**
   * DESCRIPTION: Called when one or more plot preferences have changed.
   *
   * @see
   *     android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences,
   *     java.lang.String)
   */
  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    if (key.equals(Settings.KEY_PLOT_DATE_RANGE)) {
      // plot date range changed
      redrawPlot();
    }

    if (key.equals(Settings.KEY_PLOT_FONT_SIZE)) {
      // plot font size changed
      redrawPlot();
    }

    if (key.equals(Settings.KEY_UNITS)) {

      // get new units of measurement
      units = new Units(Settings.KEY_UNITS);

      // update the plot to reflect new units
      plot.setRangeLabel(units.getLiquidVolumeLabel());

      // redraw the plot
      redrawPlot();
    }
  }
Пример #11
0
  public void onSensorChanged(SensorEvent event) {
    String valuesString = "";
    int counter = 0;
    for (float value : event.values) {
      valuesString += String.format("%d) %f ", counter++, value);
    }
    valuesString += " , " + pressureHistory.size();
    textViewPressure.setText(valuesString);

    double value = pressureSmoothingWin.push((double) event.values[0]);
    // Number[] series1Numbers = {event.values[0], event.values[1],
    // event.values[2]};
    // get rid the oldest sample in history:
    if (pressureHistory.size() > HISTORY_SIZE) {
      pressureHistory.removeFirst();
    }
    // add the latest history sample:
    pressureHistory.addLast(value); // event.values[0]);

    value = altitudeSmoothingWin.push((double) event.values[1]);
    if (altitudeHistory.size() > HISTORY_SIZE) {
      altitudeHistory.removeFirst();
    }
    altitudeHistory.addLast(value); // event.values[0]);

    value = tempSmoothingWin.push((double) event.values[2]);
    if (tempHistory.size() > HISTORY_SIZE) {
      tempHistory.removeFirst();
    }
    tempHistory.addLast(value);
    if (cooler++ % 2 == 0) return;
    // update the plot with the updated history Lists:
    if (sensorId == 0) {
      pressureHistorySeries.setModel(pressureHistory, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY);
      preHistoryPlot.setRangeLabel("Pressure (hPa)");
    } else if (sensorId == 1) {
      pressureHistorySeries.setModel(altitudeHistory, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY);
      preHistoryPlot.setRangeLabel("Altitude (m)");
    } else {
      pressureHistorySeries.setModel(tempHistory, SimpleXYSeries.ArrayFormat.Y_VALS_ONLY);
      preHistoryPlot.setRangeLabel("Temperature (ºC)");
    }

    // redraw the Plots:
    preHistoryPlot.redraw();
  }
  private void scroll(float pan) {
    final double domainSpan = maxXY.x - minXY.x;
    final double step = domainSpan / graph.getWidth();
    final double offset = pan * step;
    minXY.x += offset;
    maxXY.x += offset;

    if (minXY.x < absMinX) {
      minXY.x = absMinX;
      maxXY.x -= offset; // (absMinX-minXY.x);
    } else if (minXY.x > maxNoError) minXY.x = maxNoError;
    if (maxXY.x > absMaxX) {
      maxXY.x = absMaxX; // (maxXY.x-absMaxX);
      minXY.x -= offset; // (maxXY.x-absMaxX);
    } else if (maxXY.x < minNoError) maxXY.x = minNoError;
    if (maxXY.x - minXY.x < minDif) maxXY.x = maxXY.x + (double) (minDif - (maxXY.x - minXY.x));

    graph.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.FIXED);
  }
  public boolean onTouch(View arg0, MotionEvent event) {
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
      case MotionEvent.ACTION_DOWN: // Start gesture
        firstFinger = new PointF(event.getX(), event.getY());
        mode = ONE_FINGER_DRAG;
        break;
      case MotionEvent.ACTION_UP:
      case MotionEvent.ACTION_POINTER_UP:
        // When the gesture ends, a thread is created to give inertia to the scrolling and zoom
        final Timer t = new Timer();
        t.schedule(
            new TimerTask() {
              @Override
              public void run() {
                while (Math.abs(lastScrolling) > 1f || Math.abs(lastZooming - 1) > 1.01) {
                  lastScrolling *= .8; // speed of scrolling damping
                  scroll(lastScrolling);
                  lastZooming += (1 - lastZooming) * .2; // speed of zooming damping
                  zoom(lastZooming);
                  graph.redraw();
                }
              }
            },
            0);
        break;

      case MotionEvent.ACTION_MOVE:
        if (mode == ONE_FINGER_DRAG) {
          final PointF oldFirstFinger = firstFinger;
          firstFinger = new PointF(event.getX(), event.getY());
          lastScrolling = oldFirstFinger.x - firstFinger.x;
          scroll(lastScrolling);
          lastZooming = (firstFinger.y - oldFirstFinger.y) / graph.getHeight();
          if (lastZooming < 0) lastZooming = 1 / (1 - lastZooming);
          else lastZooming += 1;
          zoom(lastZooming);

          graph.redraw();
        }
        break;
    }
    return true;
  }
 private void checkBoundaries() {
   // Make sure the proposed domain boundaries will not cause plotting issues
   if (minXY.x < absMinX || ((Double) minXY.x).equals(Double.NaN)) minXY.x = absMinX;
   else if (minXY.x > maxNoError) minXY.x = maxNoError;
   if (maxXY.x > absMaxX || ((Double) maxXY.x).equals(Double.NaN)) maxXY.x = absMaxX;
   else if (maxXY.x < minNoError) maxXY.x = minNoError;
   if (maxXY.x - minXY.x < minDif) maxXY.x = maxXY.x + (double) (minDif - (maxXY.x - minXY.x));
   else if (maxXY.x - minXY.x > maxDif)
     maxXY.x = maxXY.x + (double) (maxDif - (maxXY.x - minXY.x));
   graph.setDomainBoundaries(minXY.x, maxXY.x, BoundaryMode.FIXED);
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.zoomscrollgraph);
    mySimpleXYPlot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
    mySimpleXYPlot.setOnTouchListener(this);

    // Plot layout configurations
    mySimpleXYPlot.getGraphWidget().setTicksPerRangeLabel(1);
    mySimpleXYPlot.getGraphWidget().setTicksPerDomainLabel(1);
    mySimpleXYPlot.getGraphWidget().setRangeValueFormat(new DecimalFormat("#####.##"));
    mySimpleXYPlot.getGraphWidget().setDomainValueFormat(new DecimalFormat("#####.##"));
    mySimpleXYPlot.getGraphWidget().setRangeLabelWidth(25);
    mySimpleXYPlot.setRangeLabel("");
    mySimpleXYPlot.setDomainLabel("");
    mySimpleXYPlot.disableAllMarkup();

    // Creation of the series
    final Vector<Double> vector = new Vector<Double>();
    for (double x = 0.0; x < Math.PI * 5; x += Math.PI / 20) {
      vector.add(x);
      vector.add(Math.sin(x));
    }
    mySeries = new SimpleXYSeries(vector, ArrayFormat.Y_VALS_ONLY, "Series Name");

    // colors: (line, vertex, fill)
    mySimpleXYPlot.addSeries(
        mySeries,
        LineAndPointRenderer.class,
        new LineAndPointFormatter(
            Color.rgb(0, 200, 0), Color.rgb(200, 0, 0), Color.argb(100, 0, 0, 100)));

    // Enact all changes
    mySimpleXYPlot.redraw();

    // Set of internal variables for keeping track of the boundaries
    mySimpleXYPlot.calculateMinMaxVals();
    m_viewPort = new Viewport(mySimpleXYPlot);
  }
Пример #16
0
  public GraphUpdater(Activity activity) {
    this.activity = activity;
    wifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
    plot = (XYPlot) activity.findViewById(R.id.graph);
    hash = new HashMap<String, WifiStrengthXYSeries>();

    plot.setTitle("");
    plot.setTicksPerRangeLabel(2);
    plot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
    plot.setDomainBoundaries(-1, 15, BoundaryMode.FIXED);
    plot.setDomainLabel("Channel");
    DecimalFormat df = new DecimalFormat("#0");
    df.setParseIntegerOnly(true);
    plot.setDomainValueFormat(df);
    plot.setRangeBoundaries(-100, -20, BoundaryMode.FIXED);
    plot.setRangeLabel("Strength");
    plot.getLegendWidget().setVisible(false);
  }
Пример #17
0
  @Override
  public void run() {

    try {
      while (true) {
        Log.d("graph", "foi");
        if (wifi.isWifiEnabled()) {
          WifiInfo wifiINFO = wifi.getConnectionInfo();
          Log.d("MyDebug", "" + wifiINFO.getIpAddress());
          wifi.startScan();
          List<ScanResult> sr = wifi.getScanResults();

          for (WifiStrengthXYSeries s : hash.values()) {
            plot.removeSeries(s);
          }
          plot.removeMarkers();

          for (ScanResult r : sr) {
            WifiStrengthXYSeries series = hash.get(r.SSID);
            if (series == null) {
              series =
                  new WifiStrengthXYSeries(
                      r.SSID,
                      (r.frequency - 2407) / 5,
                      r.level,
                      ColorPool.getColor(hash.size()),
                      ColorPool.getTransparentColor(hash.size()));
              hash.put(r.SSID, series);

            } else {
              series.setChannel((r.frequency - 2407) / 5);
              series.setStrength(r.level);
              series.update();
            }

            plot.addSeries(series, series.getFormatter());
            plot.addMarker(
                series.getMarker(activity.getResources().getConfiguration().orientation));
          }

          plot.redraw();
        }
        Thread.sleep(1000);
      }

    } catch (InterruptedException e) {

      for (WifiStrengthXYSeries s : hash.values()) {
        plot.removeSeries(s);
      }
    }
  }
Пример #18
0
  /** DESCRIPTION: Adjust font sizes used for plot labels to reflect shared preferences. */
  private void setPlotFontSizes() {
    PlotFontSize size = new PlotFontSize(activity, Settings.KEY_PLOT_FONT_SIZE);

    // plot title label
    PaintUtils.setFontSizeDp(plot.getTitleWidget().getLabelPaint(), size.getSizeDp());
    plot.getTitleWidget().pack();

    // axis step value labels
    PaintUtils.setFontSizeDp(plot.getGraphWidget().getRangeLabelPaint(), size.getSizeDp());
    PaintUtils.setFontSizeDp(plot.getGraphWidget().getDomainLabelPaint(), size.getSizeDp());

    // axis origin value labels
    PaintUtils.setFontSizeDp(plot.getGraphWidget().getRangeOriginLabelPaint(), size.getSizeDp());
    PaintUtils.setFontSizeDp(plot.getGraphWidget().getDomainOriginLabelPaint(), size.getSizeDp());

    // axis title labels
    PaintUtils.setFontSizeDp(plot.getRangeLabelWidget().getLabelPaint(), size.getSizeDp());
    PaintUtils.setFontSizeDp(plot.getDomainLabelWidget().getLabelPaint(), size.getSizeDp());
    plot.getRangeLabelWidget().pack();
    plot.getDomainLabelWidget().pack();

    // average point label
    avgLabelFormatter.getTextPaint().setTextSize(PixelUtils.dpToPix(size.getSizeDp()));
  }
Пример #19
0
  /** DESCRIPTION: Sets the boundaries for the X and Y-axis based on the data values. */
  private void setPlotAxisBoundaries() {

    // set y-axis boundaries
    long boundy = 25;
    while (maxy >= boundy) boundy *= 2;
    plot.setRangeBoundaries(0, (float) boundy, BoundaryMode.FIXED);

    // set y-axis steps
    double stepy = ((double) boundy) / 10;
    plot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, stepy);
    plot.setTicksPerRangeLabel(2);

    // set x-axis boundaries
    lowerboundx = minx - 1;
    upperboundx = maxx + 1;
    plot.setDomainBoundaries(lowerboundx, upperboundx, BoundaryMode.FIXED);

    // set x-axis steps
    plot.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
    plot.setTicksPerDomainLabel(1);

    // determine the number of months being plotted
    long months = maxx - minx + 1;

    // adjust bar thickness based on number of months being plotted
    BarRenderer<?> barRenderer = (BarRenderer<?>) plot.getRenderer(BarRenderer.class);
    if (barRenderer != null) {
      Display display = activity.getWindowManager().getDefaultDisplay();
      float displayWidth = Utilities.convertPixelsToDp(display.getWidth());
      float plotWidth = displayWidth * 0.75f;
      float barWidth = plotWidth / months;
      barRenderer.setBarWidth(barWidth);
    }

    // adjust label size based on number of months being plotted
    xlabels.setAbbreviate(months > 6);
  }
Пример #20
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pressure_monitor);
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    pressuremeter = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
    textViewPressure = (TextView) findViewById(R.id.textViewPressure);
    radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
    radioGroup.setOnCheckedChangeListener(
        new OnCheckedChangeListener() {

          @Override
          public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (checkedId == R.id.preasure) sensorId = 0;
            else if (checkedId == R.id.altitude) sensorId = 1;
            else sensorId = 2;
            plotLongHistory();
          }
        });
    setTitle("Pressure");

    // setup the APR History plot:
    preHistoryPlot = (XYPlot) findViewById(R.id.pressurePlot);
    preHistoryPlot.setRangeBoundaries(900, 1300, BoundaryMode.AUTO);
    preHistoryPlot.setDomainBoundaries(0, 100, BoundaryMode.AUTO); // FIXED);
    preHistoryPlot.addSeries(
        pressureHistorySeries,
        new LineAndPointFormatter(
            Color.BLACK, Color.RED, null, new PointLabelFormatter(Color.TRANSPARENT)));
    preHistoryPlot.setDomainStepValue(5);
    preHistoryPlot.setTicksPerRangeLabel(3);
    // preHistoryPlot.setDomainLabel("Sample Index");
    preHistoryPlot.getDomainLabelWidget().pack();
    preHistoryPlot.setRangeLabel("Temperature (ºC)");
    preHistoryPlot.getRangeLabelWidget().pack();
    preHistoryPlot.setRangeLabel("Pressure (hPa)");

    longHistoryPlot = (XYPlot) findViewById(R.id.longHistoryPlot);
    longHistoryPlot.setRangeBoundaries(900, 1300, BoundaryMode.AUTO);
    longHistoryPlot.setDomainBoundaries(0, 100, BoundaryMode.AUTO); // FIXED);
    longHistoryPlot.addSeries(
        longHistorySeries,
        new LineAndPointFormatter(
            Color.BLACK, Color.BLUE, null, new PointLabelFormatter(Color.TRANSPARENT)));
    longHistoryPlot.setDomainStepValue(5);
    longHistoryPlot.setTicksPerRangeLabel(3);
    longHistoryPlot.getDomainLabelWidget().pack();
    longHistoryPlot.setRangeLabel("Temperature (ºC)");
    longHistoryPlot.getRangeLabelWidget().pack();
    longHistoryPlot.setRangeLabel("Pressure (hPa)");

    // TEST
    if (!SamplingService.isRunning(this)) {
      SamplingAlarm.SetAlarm(this);
    }
  }
Пример #21
0
  private void ShowPlot() {
    mySimpleXYPlot = (XYPlot) findViewById(R.id.chartPlot);
    mySimpleXYPlot.setTitle("Weight");

    if (plotLine != null) mySimpleXYPlot.removeSeries(plotLine);

    mySimpleXYPlot.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);
    mySimpleXYPlot.getGraphWidget().getGridLinePaint().setColor(Color.BLACK);
    mySimpleXYPlot
        .getGraphWidget()
        .getGridLinePaint()
        .setPathEffect(new DashPathEffect(new float[] {1, 1}, 1));
    mySimpleXYPlot.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK);
    mySimpleXYPlot.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK);

    mySimpleXYPlot.setBorderStyle(Plot.BorderStyle.SQUARE, null, null);
    mySimpleXYPlot.getBorderPaint().setStrokeWidth(1);
    mySimpleXYPlot.getBorderPaint().setAntiAlias(false);
    mySimpleXYPlot.getBorderPaint().setColor(Color.WHITE);
    mySimpleXYPlot.getGraphWidget().setPaddingRight(5);

    // Create a formatter to use for drawing a series using LineAndPointRenderer:
    LineAndPointFormatter series1Format =
        new LineAndPointFormatter(
            Color.rgb(0, 100, 0), // line color
            Color.rgb(0, 100, 0), // point color
            Color.rgb(100, 200, 0)); // fill color

    // setup our line fill paint to be a slightly transparent gradient:
    Paint lineFill = new Paint();
    lineFill.setAlpha(200);
    lineFill.setShader(
        new LinearGradient(0, 0, 0, 250, Color.WHITE, Color.GREEN, Shader.TileMode.MIRROR));

    LineAndPointFormatter formatter =
        new LineAndPointFormatter(Color.rgb(0, 0, 0), Color.BLUE, Color.RED);
    formatter.setFillPaint(lineFill);

    plotLine = new SimpleXYSeries(Arrays.asList(dates), Arrays.asList(weights), "Weight over time");
    mySimpleXYPlot.addSeries(plotLine, formatter);
    mySimpleXYPlot.redraw();

    // draw a domain tick for each year:
    int min = DomainMin();
    int max = DomainMax();
    int domainStep = domainStep(min, max);
    mySimpleXYPlot.setDomainStep(XYStepMode.SUBDIVIDE, domainStep);
    // mySimpleXYPlot.setDomainBoundaries(min, max, BoundaryMode.AUTO);

    // customize our domain/range labels
    mySimpleXYPlot.setDomainLabel("Date");
    mySimpleXYPlot.setRangeLabel("Weight");

    Double minimum = FindMinimum();
    Double maximum = FindMaximum();
    Double stepSize = FindStep(maximum, minimum);
    mySimpleXYPlot.setRangeBoundaries(minimum, maximum, BoundaryMode.FIXED);
    mySimpleXYPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, stepSize);

    mySimpleXYPlot.setDomainValueFormat(
        new Format() {
          private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM");

          @Override
          public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {

            // because our timestamps are in seconds and SimpleDateFormat expects milliseconds
            // we multiply our timestamp by 1000:
            long timestamp = ((Number) obj).longValue() * 1000;
            Date date = new Date(timestamp);
            return dateFormat.format(date, toAppendTo, pos);
          }

          @Override
          public Object parseObject(String source, ParsePosition pos) {
            return null;
          }
        });

    // by default, AndroidPlot displays developer guides to aid in laying out your plot.
    // To get rid of them call disableAllMarkup():
    mySimpleXYPlot.disableAllMarkup();
  }
Пример #22
0
  /**
   * DESCRIPTION: Creates the graph.
   *
   * @see android.app.Activity#onCreate(android.os.Bundle)
   */
  public void onCreate(Bundle savedInstanceState, Activity parent, XYPlot xyplot) {
    this.activity = parent;
    this.plot = xyplot;

    // get current units of measurement
    units = new Units(Settings.KEY_UNITS);

    // create a formatter to use for drawing the plot series
    plotFormatter =
        new BarFormatter(
            activity.getResources().getColor(R.color.plot_fill_color),
            activity.getResources().getColor(R.color.plot_line_color));

    // create a formatter for average label
    float hOffset = 50f;
    float vOffset = -10f;
    avgLabelFormatter =
        new PointLabelFormatter(
            activity.getResources().getColor(R.color.plot_avgline_color), hOffset, vOffset);

    // create a formatter to use for drawing the average line
    avgFormatter =
        new LineAndPointFormatter(
            activity.getResources().getColor(R.color.plot_avgline_color),
            null,
            null,
            avgLabelFormatter);

    // white background for the plot
    plot.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);

    // remove the series legend
    plot.getLayoutManager().remove(plot.getLegendWidget());

    // make room for bigger labels
    // TODO: is there a better way to do this?
    float width = plot.getGraphWidget().getRangeLabelWidth() * 2f;
    plot.getGraphWidget().setRangeLabelWidth(width);
    width = plot.getGraphWidget().getDomainLabelWidth() * 1.5f;
    plot.getGraphWidget().setDomainLabelWidth(width);
    float margin = plot.getGraphWidget().getMarginTop() * 3f;
    plot.getGraphWidget().setMarginTop(margin);
    margin = plot.getGraphWidget().getMarginBottom() * 3f;
    plot.getGraphWidget().setMarginBottom(margin);

    // define plot axis labels
    plot.setRangeLabel(units.getLiquidVolumeLabel());
    plot.setDomainLabel(activity.getString(R.string.months_label));

    // specify format of axis value labels
    plot.setRangeValueFormat(ylabels);
    plot.setDomainValueFormat(xlabels);

    // plot the data
    drawPlot();
  }
Пример #23
0
  @SuppressWarnings("deprecation")
  public void drawGraph(
      XYPlot plot, List<Number> xseries, List<Number> yseries, String datatitle, String title) {
    //		Log.d(SystemInfo.TIG, TAG + "::drawGraph()");

    // set up data series
    plot.removeSeries(series);

    series = new SimpleXYSeries(xseries, yseries, datatitle);

    // create a formatter
    // TODO solve deprecation waring
    LineAndPointFormatter format =
        new LineAndPointFormatter(
            Color.rgb(0, 200, 0) // line color
            ,
            Color.rgb(0, 100, 0) // point color
            ,
            Color.rgb(150, 190, 150)); // fill color (optional)

    // add series1 and series2 to the XYPlot
    plot.addSeries(series, format);

    // Reduce the number of range labels
    plot.setTicksPerRangeLabel(3);
    plot.getBackgroundPaint().setAlpha(0);
    plot.getGraphWidget().getBackgroundPaint().setAlpha(0);
    plot.getGraphWidget().getGridBackgroundPaint().setAlpha(0);

    // TODO implement an on-the-fly refresh of the plot
    // this is just a small "stubbed" redraw for demonstration purposes
    plot.setDomainStepMode(XYStepMode.SUBDIVIDE);
    plot.setDomainStepValue(1);
    plot.setGridPadding(0, 5, 0, 5);

    plot.setDomainLabel("Time [s]");
    if (title.equals(SystemInfo.DB_TABLENAME_BATTERY)) {
      plot.setTitle(SystemInfo.DB_TABLENAME_BATTERY);
      plot.setRangeLabel("[%]");
      plot.setRangeBoundaries(0, 100, BoundaryMode.FIXED);

    } else if (title.equals(SystemInfo.DB_TABLENAME_WIFI)) {
      plot.setTitle(SystemInfo.DB_TABLENAME_WIFI);
      plot.setRangeLabel("[~mW]");
      plot.setRangeBoundaries(0, 500, BoundaryMode.FIXED);

    } else if (title.equals(SystemInfo.DB_TABLENAME_THREEG)) {
      plot.setTitle(SystemInfo.DB_TABLENAME_THREEG);
      plot.setRangeLabel("[~mW]");
      plot.setRangeBoundaries(0, 500, BoundaryMode.FIXED);

    } else if (title.equals(SystemInfo.DB_TABLENAME_BLUETOOTH)) {
      plot.setTitle(SystemInfo.DB_TABLENAME_BLUETOOTH);
      plot.setRangeLabel("[~mW]");
      plot.setRangeBoundaries(0, 500, BoundaryMode.FIXED); // XXX scale
    }
    plot.redraw();
  }
Пример #24
0
 /** DESCRIPTION: Clears the plot widget, then plots the data again. */
 private void redrawPlot() {
   plot.clear();
   drawPlot();
   plot.redraw();
 }
Пример #25
0
 /**
  * DESCRIPTION: Sets the height of the plot view.
  *
  * @param height - the height in pixels.
  */
 public void setHeight(int height) {
   ViewGroup.LayoutParams params = plot.getLayoutParams();
   params.height = height;
   plot.setLayoutParams(params);
   plot.redraw();
 }
 private void checkBoundaries() {
   // Make sure the proposed domain boundaries will not cause plotting issues
   m_viewPort.updateBoudaries();
   mySimpleXYPlot.setDomainBoundaries(m_viewPort.minXY.x, m_viewPort.maxXY.x, BoundaryMode.AUTO);
 }
Пример #27
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.poincare);

    // Rellenar vector RR1
    for (int i = 1; i < Representar.RR.size(); i++) {
      RR1.add(Representar.RR.get(i));
    }
    // Rellenar vector RRaux
    for (int i = 0; i < Representar.RR.size() - 1; i++) {
      RRaux.add(Representar.RR.get(i));

      Log.i("RRaux", String.valueOf(Representar.RR.get(i)));
    }

    // Declarar el Plot
    mySimpleXYPlot = (XYPlot) findViewById(R.id.plotPoincare);

    // Configurar el Plot
    XYSeries series1 =
        new SimpleXYSeries(
            RRaux, // Vector a representar en el eje X
            RR1, // Vector a representar en el eje Y
            "Poincaré"); // Etiqueta

    LineAndPointFormatter series1Format =
        new LineAndPointFormatter(
            Color.TRANSPARENT, // Color de la línea
            Color.rgb(
                Representar.color0, Representar.color1, Representar.color2), // Color de los puntos
            null); // Color de relleno

    // Propiedades para configurar el Plot
    mySimpleXYPlot.addSeries(series1, series1Format);
    mySimpleXYPlot.setTicksPerRangeLabel(4);
    mySimpleXYPlot.disableAllMarkup();
    mySimpleXYPlot.getBackgroundPaint().setAlpha(0);
    mySimpleXYPlot.getGraphWidget().getBackgroundPaint().setAlpha(0);
    mySimpleXYPlot.getGraphWidget().getGridBackgroundPaint().setAlpha(0);
    // Redibujar el Plot
    mySimpleXYPlot.redraw();

    // Configuración boundaries
    mySimpleXYPlot.calculateMinMaxVals();
    // Cálculo del valor mínimo y máximo
    minXY =
        new PointF(
            mySimpleXYPlot.getCalculatedMinX().floatValue(),
            mySimpleXYPlot.getCalculatedMinY().floatValue());
    maxXY =
        new PointF(
            mySimpleXYPlot.getCalculatedMaxX().floatValue(),
            mySimpleXYPlot.getCalculatedMaxY().floatValue());
    mySimpleXYPlot.setScrollbarFadingEnabled(true);
    mySimpleXYPlot.setScrollContainer(true);

    mySimpleXYPlot.getLayoutManager().remove(mySimpleXYPlot.getLegendWidget());
    // Etiquetas vertical y horizontal
    mySimpleXYPlot.setRangeLabel("RR N+1");
    mySimpleXYPlot.setDomainLabel("RR N");
    mySimpleXYPlot.getLayoutManager().remove(mySimpleXYPlot.getTitleWidget());
    // Márgenes del Plot
    mySimpleXYPlot.setPlotMargins(10, 10, 10, 10);
    mySimpleXYPlot.setPlotPadding(10, 10, 10, 10);
    // Comienzo y fin del plot
    mySimpleXYPlot.setDomainBoundaries(
        mySimpleXYPlot.getCalculatedMinX().floatValue() - 10.0,
        mySimpleXYPlot.getCalculatedMaxX().floatValue() + 10.0,
        BoundaryMode.FIXED);
    mySimpleXYPlot.setRangeBoundaries(
        mySimpleXYPlot.getCalculatedMinY().floatValue() - 10.0,
        mySimpleXYPlot.getCalculatedMaxY().floatValue() + 10.0,
        BoundaryMode.FIXED);
  }
Пример #28
0
  // Función a la que se salta después de la introducción de datos en otros Activities
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // Si el código es cero, se trata de exportar la imagen en formato JPEG
    if (requestCode == 0) {

      if (resultCode == RESULT_OK) {
        String nombre = data.getStringExtra("nombre");

        mySimpleXYPlot.setDrawingCacheEnabled(true);
        int width = mySimpleXYPlot.getWidth();
        int height = mySimpleXYPlot.getHeight();
        mySimpleXYPlot.measure(width, height);
        Bitmap bmp = Bitmap.createBitmap(mySimpleXYPlot.getDrawingCache());
        // Acceso a SDCard
        String path = Environment.getExternalStorageDirectory().toString();
        OutputStream fOut = null;
        File file = new File(path + "/FC_aplication/", nombre + ".JPEG");
        try {
          fOut = new FileOutputStream(file);
          bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
          fOut.flush();
          fOut.close();
          MediaStore.Images.Media.insertImage(
              getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());

          Toast.makeText(Poincare.this, "Señal exportada en formato JPEG", Toast.LENGTH_LONG)
              .show();

        } catch (Exception e) {
        }
      }
    }

    // Si el código es cero, se trata de exportar la imagen en formato PNG
    else if (requestCode == 1) {

      if (resultCode == RESULT_OK) {
        String nombre = data.getStringExtra("nombre");

        mySimpleXYPlot.setDrawingCacheEnabled(true);
        int width1 = mySimpleXYPlot.getWidth();
        int height1 = mySimpleXYPlot.getHeight();
        mySimpleXYPlot.measure(width1, height1);
        // Acceso a SDCard
        Bitmap bmp1 = Bitmap.createBitmap(mySimpleXYPlot.getDrawingCache());
        String path1 = Environment.getExternalStorageDirectory().toString();
        OutputStream fOut1 = null;
        File file1 = new File(path1 + "/FC_aplication/", nombre + ".PNG");
        try {
          fOut1 = new FileOutputStream(file1);
          bmp1.compress(Bitmap.CompressFormat.PNG, 100, fOut1);
          fOut1.flush();
          fOut1.close();
          MediaStore.Images.Media.insertImage(
              getContentResolver(), file1.getAbsolutePath(), file1.getName(), file1.getName());
          Toast.makeText(Poincare.this, "Señal exportada en formato PNG", Toast.LENGTH_LONG).show();

        } catch (Exception e) {
        }
      }
    }
  }
    // Constructor sets up the series
    public mPlotUpdater(XYPlot plot) {
      this.plot = plot;
      // only display whole numbers in domain labels
      plot.getGraphWidget().setDomainValueFormat(new DecimalFormat("0"));

      // Line plot
      if (dispForm == "WAVE") {
        LineAndPointFormatter maxFormat =
            new LineAndPointFormatter(
                Color.rgb(0, 25, 250), // line color
                Color.rgb(0, 25, 250), // point color
                null); // fill color (optional)

        LineAndPointFormatter minFormat =
            new LineAndPointFormatter(
                Color.rgb(250, 25, 0), // line color
                Color.rgb(250, 25, 0), // point color
                null); // fill color (optional)

        LineAndPointFormatter audioFormat =
            new LineAndPointFormatter(
                Color.rgb(25, 250, 0), // line color
                Color.rgb(25, 250, 0), // point color
                null); // fill color (optional)

        plot.addSeries(audioHistSeries, audioFormat);
        plot.addSeries(maxSeries, maxFormat);
        plot.addSeries(minSeries, minFormat);
      }
      // Bar plot
      if (dispForm == "FFT") {
        plot.addSeries(
            audioHistSeries,
            BarRenderer.class,
            new BarFormatter(Color.argb(100, 0, 200, 0), Color.rgb(0, 80, 0)));
      }

      // thin out domain/range tick labels so they don't overlap each other:
      plot.setGridPadding(5, 0, 5, 0);
      plot.setTicksPerDomainLabel(5);
      plot.setTicksPerRangeLabel(3);
      plot.disableAllMarkup();

      // freeze the range boundaries:
      plot.setDomainStepMode(XYStepMode.INCREMENT_BY_VAL);
      plot.setDomainStepValue(1);
      plot.setTicksPerRangeLabel(6);
      if (dispForm == "WAVE") plot.setDomainLabel("Time");
      if (dispForm == "FFT ") plot.setDomainLabel("Frequency");
      plot.getDomainLabelWidget().pack();
      plot.setRangeLabel("Amplitude");
      plot.getRangeLabelWidget().pack();
      plot.disableAllMarkup();
    }
  @Override
  public boolean onTouch(View arg0, MotionEvent event) {
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
      case MotionEvent.ACTION_DOWN: // Start gesture
        firstFinger = new PointF(event.getX(), event.getY());
        mode = ONE_FINGER_DRAG;
        break;
      case MotionEvent.ACTION_UP:
      case MotionEvent.ACTION_POINTER_UP:
        // When the gesture ends, a thread is created to give inertia to the scrolling and zoom
        final Timer t = new Timer();
        t.schedule(
            new TimerTask() {
              @Override
              public void run() {
                while (Math.abs(lastScrolling) > 1f || Math.abs(lastZooming - 1) < 1.01) {
                  lastScrolling *= .8; // speed of scrolling damping
                  m_viewPort.scroll(lastScrolling);
                  lastZooming += (1 - lastZooming) * .2; // speed of zooming damping
                  m_viewPort.zoom(lastZooming);
                  checkBoundaries();
                  try {
                    mySimpleXYPlot.postRedraw();
                  } catch (final InterruptedException e) {
                    e.printStackTrace();
                  }
                  // the thread lives until the scrolling and zooming are imperceptible
                }
              }
            },
            0);

      case MotionEvent.ACTION_POINTER_DOWN: // second finger
        distBetweenFingers = spacing(event);
        // the distance check is done to avoid false alarms
        if (distBetweenFingers > 5f) mode = TWO_FINGERS_DRAG;
        break;
      case MotionEvent.ACTION_MOVE:
        if (mode == ONE_FINGER_DRAG) {
          final PointF oldFirstFinger = firstFinger;
          firstFinger = new PointF(event.getX(), event.getY());
          lastScrolling = oldFirstFinger.x - firstFinger.x;
          m_viewPort.scroll(lastScrolling);
          lastZooming = (firstFinger.y - oldFirstFinger.y) / mySimpleXYPlot.getHeight();
          if (lastZooming < 0) lastZooming = 1 / (1 - lastZooming);
          else lastZooming += 1;
          m_viewPort.zoom(lastZooming);
          checkBoundaries();
          mySimpleXYPlot.redraw();
        }
        //					else if (mode == TWO_FINGERS_DRAG) {
        //						final float oldDist = distBetweenFingers;
        //						distBetweenFingers = spacing(event);
        //						lastZooming = oldDist / distBetweenFingers;
        //						m_viewPort.zoom(lastZooming);
        //						checkBoundaries();
        //						mySimpleXYPlot.redraw();
        //					}
        break;
    }
    return true;
  }