Рисование графика с использованием данных, полученных через Bluetooth, с использованием библиотеки MPAndroid Chart - PullRequest
0 голосов
/ 29 января 2019

Я пытаюсь создать приложение для Android для построения графика с использованием значений, полученных Arduino, отправленным через Bluetooth с помощью модуля HC-06 с использованием библиотеки MPAndroid Chart.Я сделал два действия, одно для подключения к модулю HC-06, а другое для построения графика.Упражнение одно включает кнопки для включения и выключения Bluetooth, включения возможности обнаружения, обнаружения устройств, сопряжения с устройством и кнопку для перехода ко второму занятию (которое включает график).Все эти функции работают без ошибок.Я хочу знать, как нарисовать график, используя полученные данные через Bluetooth на втором занятии.Я знаю, как нарисовать график со случайными точками, используя библиотеку MPAndroid Chart, но не знаю, как поступить с моим делом.Ниже приведен код второго упражнения, которое рисует график со случайными точками.Я попытался добавить некоторые коды к этому коду из документации по Android Bluetooth, и это тоже включено в приведенный ниже код, и, возможно, то, что я добавил, неверно, поэтому любые советы по коду высоко ценятся.(Я думаю, что я не понимаю, как получить доступ к данным, полученным через Bluetooth). Любая помощь по этому вопросу будет принята с благодарностью.

public class BluetoothGraph extends AppCompatActivity {

//BluetoothAdapter mBluetoothAdapter;
public ConstraintLayout blgr;
private LineChart mChart;

private static final String TAG = "MY_APP_DEBUG_TAG";
private Handler mHandler; // handler that gets info from Bluetooth service



private interface MessageConstants {
    public static final int MESSAGE_READ = 0;
    public static final int MESSAGE_WRITE = 1;
    public static final int MESSAGE_TOAST = 2;

    // ... (Add other message types here as needed.)
 }

// private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;
    private byte[] mmBuffer; // mmBuffer store for the stream

   // public ConnectedThread(BluetoothSocket socket) {
    public BluetoothGraph(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams; using temp objects because
        // member streams are final.
        try {
            tmpIn = socket.getInputStream();
        } catch (IOException e) {
            Log.e(TAG, "Error occurred when creating input stream", e);
        }
        try {
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "Error occurred when creating output stream", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        mmBuffer = new byte[1024];
        int numBytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs.
        while (true) {
            try {
                // Read from the InputStream.
                numBytes = mmInStream.read(mmBuffer);
                // Send the obtained bytes to the UI activity.
                Message readMsg = mHandler.obtainMessage(MessageConstants.MESSAGE_READ, numBytes, -1, mmBuffer);
                readMsg.sendToTarget();
            } catch (IOException e) {
                Log.d(TAG, "Input stream was disconnected", e);
                break;
            }
        }
    }


    // Call this method from the main activity to shut down the connection.
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "Could not close the connect socket", e);
        }
    }
// }





@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent next = getIntent();
    setContentView(R.layout.activity_bluetooth_graph);

    blgr = (ConstraintLayout) findViewById(R.id.blGr);


    //create line Chart
    mChart = new LineChart(this);
    //add to mainLayout
    blgr.addView(mChart, new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.MATCH_PARENT));

    //customize line chart this requires earlier version of the library
    mChart.setDescription("");
    mChart.setNoDataTextDescription("No Data at the moment");

    //enable value highlighting
    //Set this to true on your Chart to allow highlighting per dragging over the chart surface when it is fully zoomed out. Default: true
    mChart.setHighlightPerDragEnabled(true);

    // enable touch gestures
    //Allows to enable/disable all possible touch-interactions with the chart.
    mChart.setTouchEnabled(true);

    // Enables/disables dragging (panning) for the chart
    mChart.setDragEnabled(true);

    // Enables/disables scaling for the chart on both axes.
    mChart.setScaleEnabled(true);

    // enough to disable grid lines
    mChart.setDrawGridBackground(false);

    //If set to true, pinch-zooming is enabled. If disabled, x- and y-axis can be zoomed separately.
    mChart.setPinchZoom(true);

    //alternative BackgroundColor //LTGRAY
    mChart.setBackgroundColor(Color.WHITE);

    //working on data
    LineData dat1 = new LineData();
    dat1.setValueTextColor(Color.WHITE);

    //add data to line chart
    mChart.setData(dat1);

    //get Legend object
    //By default, all chart types support legends and will automatically
    // generate and draw a legend after setting data for the chart. The Legend usually consists of
    // multiple entries each represented by a label an a form/shape.
    Legend Legend1 = mChart.getLegend();

    //customize legend
    Legend1.setForm(Legend.LegendForm.LINE);
    Legend1.setTextColor(Color.WHITE);

    XAxis x1 = mChart.getXAxis();
    x1.setTextColor(Color.WHITE);
    x1.setDrawGridLines(false);

    // if set to true, the chart will avoid that the first and last label entry
    //     * in the chart "clip" off the edge of the chart
    x1.setAvoidFirstLastClipping(true);

    YAxis y1 = mChart.getAxisLeft();
    y1.setTextColor(Color.WHITE);
    y1.setDrawGridLines(true);
    y1.setAxisMaxValue(120f);

    YAxis y2 = mChart.getAxisRight();
    y2.setEnabled(false);

}

@Override
protected void onResume() {
    super.onResume();

    //
    new Thread(new Runnable() {
        @Override
        public void run() {
            // add entries
            for (int i = 0; i < 75; i++) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        addEntry();
                    }
                });
                // pause between adds
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    //manage error
                }

            }
        }
    }).start();
}

//we need to create method to add entry to the line data

private void addEntry(){
    LineData data =mChart.getData();

    if (data!=null){
        LineDataSet set= (LineDataSet) data.getDataSetByIndex(0);

        if(set==null){
            //creation if null
            set= createSet();
            data.addDataSet(set);
        }
        //add a new random value
        data.addXValue("");
        data.addEntry(new Entry((float)(Math.random()*125)+5f,set.getEntryCount()),0);
        //data.addEntry(new Entry(set.getEntryCount(),0);

        //notify chart data have changed
        mChart.notifyDataSetChanged();

        //limit number of visible entries
        mChart.setVisibleXRange(0,100);

        //scroll to the last entry
        mChart.moveViewToX(data.getXValCount()-7);

    }

}


// method to create set
private LineDataSet createSet(){
    LineDataSet set=new LineDataSet(null,"spl Db");
    set.setDrawCubic(true);
    set.getCubicIntensity();
    set.setAxisDependency(YAxis.AxisDependency.LEFT);
    set.setColor(ColorTemplate.getHoloBlue());
    set.setLineWidth(2f);
    set.setCircleSize(4f);
    set.setFillAlpha(65);
    set.setFillColor(ColorTemplate.getHoloBlue());
    set.setHighLightColor(Color.rgb(244,177,117));
    set.setHighLightColor(Color.WHITE);
    set.setValueTextSize(10f);


    return set;


}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...