Android Open Source - voc Sensor Curve






From Project

Back to project page voc.

License

The source code is released under:

GNU General Public License

If you think the Android project voc listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package processing;
/*w w  w.  j  ava  2s .  c  om*/
/**
 * Created with IntelliJ IDEA.
 * User: linyaoli
 * Date: 11/19/13
 * Time: 3:31 PM
 * Sqlite saver(need to relocate), find the concentration data.
 */

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import au.com.bytecode.opencsv.CSVWriter;
import com.androidplot.xy.*;
import display.DynamicPlotSeries;
import transmission.LocalProfile;
import java.io.IOException;
import android.text.format.Time;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;

@SuppressLint("NewApi")
public class SensorCurve {

    private static final String TAG = "EnviroSensor";

    private static float[] fPd;
    private static float[] fPdLog;
    private static int iFan;
    //private static float[][] fCount30; // Store latest 30 points.
    private static Queue<Float> qfCount30_pd1 = new LinkedBlockingDeque<Float>();
    private static Queue<Float> qfCount30_pd2 = new LinkedBlockingDeque<Float>();
    private static Queue<Float> qfCount30_pd3 = new LinkedBlockingDeque<Float>();
    private static LinearRegression linearRegression;

    private static float[] fStackPoints;
    private static LinearRegression.LinearParams fLinearParamsSensor;

    private final static  short START = 12345;
    private final static  short END = 31793;
    private static byte last_byte = -111;

    private Queue<Character> dataQueueBuffer;

    private static boolean isPurging = false;
    private static XYPlot plot;
    private static DynamicPlotSeries sine1Series;
    private static LineAndPointFormatter series1Format;
    private static LocalProfile db;
    private static char[] oneMessage = new char[10];
    private static SQLiteDatabase sqlite;
    private static SQLiteDatabase sqlite_read;
    private static ContentValues cv;

    private static char[] sample30Points = new char[30];
    private static Queue<Character> pointsQueue = new LinkedList<Character>();

    private static char difference = 0;
    private static char lastSamplePoint = 0;
    private static char concentration = 0;

    private static LinearRegression.LinearParams saber;
    private static int counter = 29;

    private static ArrayList<Character> ppbArrayList = new ArrayList<Character>();

    private static Character largestRaw = 0;
    private static Character smallestRaw = 50000;

    private static String today;
    private static CSVWriter writer;
    private static CSVWriter writer_ppb;

    private Time now;

    /**
     *
     * @param dataQueueBuffer
     * @param plot
     * @param db
     */
    public SensorCurve(Queue<Character> dataQueueBuffer, XYPlot plot, LocalProfile db){
        // TODO Auto-generated constructor stub
        fPd = new float[4];
        fPdLog = new float[3];
        this.dataQueueBuffer = dataQueueBuffer;
        iFan = 0;
        fStackPoints = new float[120];//30s/0.25s = 120 points.
        linearRegression = new LinearRegression();
        this.plot = plot;
        ////////////////////
        ////////// Create DB helper
        this.db = db;
        initialDatabase();

        now = new Time();
        now.setToNow();
        today = now.toString();
        try {
            writer = db.initializeCSV( today );
            writer_ppb = db.initializeCSV_ppb( today );
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 10; i++)
            ppbArrayList.add((char)0);
    }

    /**
     *  Destructor.
     */
    protected void finalize () {
        // Destructor method
        sqlite.close();
        try {
            writer.close();
            writer_ppb.close();
        }
        catch (Exception e)  {
            e.printStackTrace();
        }

    }
//
//    /**
//     * Used to invoke the update of curve, not used anymore.
//     * @param fPd1
//     * @param fPd2
//     * @param fPd3
//     * @param iFan
//     */
//    public void updateSensorValue (float fPd1, float fPd2,
//                                   float fPd3, int iFan) {
//        fPd[0] = fPd1;
//        fPd[1] = fPd2;
//        fPd[2] = fPd3;
//        //get log base e.
//        fPdLog[0] = getCoordinate(0);
//        fPdLog[1] = getCoordinate(1);
//        fPdLog[2] = getCoordinate(2);
//        //Store latest 30 points.
//        if (qfCount30_pd1.size() == 30)
//            qfCount30_pd1.remove();
//        if (qfCount30_pd2.size() == 30)
//            qfCount30_pd2.remove();
//        if (qfCount30_pd3.size() == 30)
//            qfCount30_pd3.remove();
//        qfCount30_pd1.add(fPdLog[0]);
//        qfCount30_pd2.add(fPdLog[1]);
//        qfCount30_pd3.add(fPdLog[2]);
//
//        //Check if fan status is changed.
//        if(isFanChanged(iFan) &&
//                qfCount30_pd1.size() == 30 &&
//                qfCount30_pd2.size() == 30 &&
//                qfCount30_pd3.size() == 30) {
//            fLinearParamsSensor = linearRegression.getLinearParams(qfCount30_pd1);
//
//        }
//        else
//            return;
//    }

    /**
     * get corresponding coordinates by log.
     * @param graphIndex
     * @return
     */
    private float getCoordinate(int graphIndex) {
        float fCoordinate = getLog(fPd[graphIndex]);
        return fCoordinate;
    }
    /**
     *
     * @param pdx
     * @return
     */
    private float getLog(float pdx) {
        // Get -log(PDx/PD4)
        return (float) -Math.log(pdx/fPd[3]);
    }

    /*
        @function: set fan status.
     */

    /**
     *
     * @param fan
     * @return
     */
    private boolean isFanChanged (int fan) {

        if (iFan != fan){
            iFan = fan;
            return true;
        }
        else{
            iFan = fan;
            return false;
        }
    }
    /*
        @function: core function, linear fit for the sampling points.
     */

    /**
     *
     * @param pointsQueue
     * @return
     */
    private LinearRegression.LinearParams getLineParams(Queue<Character> pointsQueue) {

        int size = pointsQueue.size();
        for (int i = 0;i < size;i++)
            sample30Points[i] = pointsQueue.poll();

        saber = linearRegression.lineFit(sample30Points);
        return saber;

    }

    /*
        @function: core function, update the point reading in queue buffer. All output data comes from here.
     */

    /**
     *
     * @param msgQueueBuffer
     * @throws IOException
     */
    public void update (Queue<Byte> msgQueueBuffer) throws IOException {

        if (msgQueueBuffer.size() >= 20) {

            int i = 0;   //FIXME
            byte low, high;

            while ( i < 10 ) {
                low = msgQueueBuffer.poll();
                high = msgQueueBuffer.poll();

                if (last_byte == -111)
                    last_byte = high;

                char to = (char)(((high<<8)&0xff00) + ((low<<0)&0x00ff));
               // Log.d(TAG, Integer.toString((int)low) + " " + Integer.toString((int)high) + ">" + Integer.toString((int)to));

                oneMessage[i] = to;

                if (i == 1) {
                    this.dataQueueBuffer.offer((to));
                    pointsQueue.offer(to);
                    if (pointsQueue.size() > 30)
                        pointsQueue.poll();

                    lastSamplePoint = to;
                    if (to > largestRaw)
                        largestRaw = to;

                    if (to < smallestRaw)
                        smallestRaw = to;
                }
                if ((i == 8) && (to == (char)1) &&
                        (isFanChanged(to))) {
                    isPurging = true;
                    fLinearParamsSensor = getLineParams(pointsQueue);
                    concentration = findTheLargestDifference(lastSamplePoint);
                }
                else if ((i == 8) && (to == (char)1)){
                    isPurging = true;
                    concentration = findTheLargestDifference(lastSamplePoint);
                }
                else if ((i == 8) && (to == (char)0) && (isFanChanged(to))) {
                    ppbArrayList.remove(ppbArrayList.size()-1);
                    /*
                    apply the scenario and mode.
                     */
                    concentration = (char) (100 * getScenarioValue() * getModeValue() *
                            (double)concentration / Math.abs(10352 - (double)concentration));
                    addppb(concentration);
                    ppbArrayList.add(0, concentration);
                    concentration = 0;
                    difference = 0;
                }
                else {
                    counter = 29;

                }

                if ((i == 8) && (to != (char)1)) isPurging = false;

                i++;
                Log.d(TAG, Integer.toString((int)to));
            }
            Log.d(TAG, "________");
            // Writing to database.
            add(oneMessage);
        }

    }
    private String scenario, mode;

    /**
     *
     * @param scenario
     * @param mode
     */
    public void setScenarioAndMode(String scenario, String mode) {

        this.scenario = scenario;
        this.mode = mode;
    }

    private String rawQR;
    private ArrayList<Double> qrValue = new ArrayList<Double>();

    /**
     *
     */
    private void parseRawQR () {
        String tmp = "";
        int i = 0;
        while (i < rawQR.length()) {
            if (rawQR.charAt(i) != '\n')
                tmp += rawQR.charAt(i);
            else {
                qrValue.add(Double.parseDouble(tmp));
                tmp = "";
            }
            i++;
        }

        qrValue.add(Double.parseDouble(tmp));

    }

    /**
     *
     */
    private void queryQR() {
        String sql = " SELECT _CODE FROM QR ORDER BY _ID DESC LIMIT 1;";

        Cursor cursor = sqlite_read.rawQuery(sql, null);

        if (cursor != null) {
            cursor.moveToFirst();
            rawQR = cursor.getString(0);
            parseRawQR();
        }
        cursor.close();
        sqlite_read.close();
    }

    /**
     *
     * @return
     */
    private double getScenarioValue() {

        if (scenario.equals("Default"))
            return 6.518;
        else if (scenario.equals("Industry"))
            return 6.518;
        else if (scenario.equals("Indoor"))
            return 6.518;
        else if (scenario.equals("Environment"))
            return 6.518;
        else
            return 0;
    }

    /**
     *
     * @return
     */
    private double getModeValue() {

        if (mode.equals("Singleton"))
            return 254;
        else if (mode.equals("Continuous"))
            return 254;
        else
            return 254;
    }

    /**
     *
     * @return
     */
    public Queue<Character> syncData() {
        return this.dataQueueBuffer;
    }
    /**
     *
     * @return
     */
    public static boolean getPurgingStatus() {
        return isPurging;
    }

    /**
     *
     * @return
     */
    public XYPlot getPlot() {
        return plot;
    }

    /**
     *
     * @return
     */
    public DynamicPlotSeries getSeries() {
        return sine1Series;
    }

    /**
     *
     * @return
     */
    public LineAndPointFormatter getFormat() {
        return series1Format;
    }

    /**
     *
     * @param message
     */
    private void add(char[] message) {

//        cv = new ContentValues();
//        cv.put("_VALUE1", Integer.toString((int)message[0]));
//        cv.put("_VALUE2", Integer.toString((int)message[1]));
//        cv.put("_VALUE3", Integer.toString((int)message[2]));
//        cv.put("_VALUE4", Integer.toString((int)message[3]));
//        cv.put("_VALUE5", Integer.toString((int)message[4]));
//        cv.put("_VALUE6", Integer.toString((int)message[5]));
//        cv.put("_VALUE7", Integer.toString((int)message[6]));
//        cv.put("_VALUE8", Integer.toString((int)message[7]));
//        cv.put("_VALUE9", Integer.toString((int)message[8]));
//        cv.put("_VALUE10", Integer.toString((int)message[9]));
//
//        sqlite.insert("VOC",
//                null,
//                cv);
        now.setToNow();
        String tmp[] = { (now.toString().substring(0, 15)) + '\t',
                        Integer.toString((int)message[0]) + '\t' ,
                        Integer.toString((int)message[1]) + '\t' ,
                        Integer.toString((int)message[2]) + '\t' ,
                        Integer.toString((int)message[3]) + '\t' ,
                        Integer.toString((int)message[4]) + '\t' ,
                        Integer.toString((int)message[5]) + '\t' ,
                        Integer.toString((int)message[6]) + '\t' ,
                        Integer.toString((int)message[7]) + '\t' ,
                        Integer.toString((int)message[8]) + '\t' ,
                        Integer.toString((int)message[9])
        };
        try {
            db.saveCSVLine(writer, tmp);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    private Calendar calendar;

    /**
     *
     * @param message
     */
    private void addppb(char message) {
        ContentValues tcv = new ContentValues();
        tcv.put("_VALUE1", Integer.toString((int)message));
        tcv.put("_VALUE2", Integer.toString((int)0));

        try {
            sqlite.insert("CONC",
                null,
                tcv);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        now.setToNow();
        String tmp[] = { (now.toString().substring(0, 15)) + '\t',
                Integer.toString((int)message) + '\t',
                Integer.toString((int)0)
        };
        try {
            db.saveCSVLine(writer_ppb, tmp);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     *  Initialize the database handler.
     */
    private void initialDatabase() {
        try {
            sqlite_read = db.getReadableDatabase();
            queryQR();
            sqlite_read.close();
            sqlite = db.getWritableDatabase();

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * return the concentration, actual data by finding the largest difference in purging procedure.
     * @param currentTrueReading
     * @return
     */
    private static char findTheLargestDifference(char currentTrueReading) {

        double lineReading = (fLinearParamsSensor.beta0 * (++counter) + fLinearParamsSensor.beta1);
        double current = (double)currentTrueReading;

        //Has to be positive, otherwise this app goes shit.
        assert (current-lineReading>0) : "The difference should not be negative";
        Log.d(TAG, "Conc : " + Integer.toString((int)concentration));
        if (Math.abs(current - lineReading) > difference) {
            difference = (char)Math.abs(current - lineReading);
        }
        return difference;
    }


    /**
     * return the concentration, which is actually the largest difference.
     * @return
     */
    public char getConcentration() {
        return difference;
    }

    /**
     * return the ppb arraylist, should be displayed in dynamicplotdatasource, 30 points.
     * @return
     */
    public ArrayList<Character> getPpbArrayList()  {
        return ppbArrayList;
    }

    /**
     * find the largest value of concentration arraylist.
     * @return
     */
    public char getLargestConcentration( )  {
        char tmp = 0;
        for (int i=0; i<ppbArrayList.size();i++) {
            if(ppbArrayList.get(i) > tmp)
                tmp = ppbArrayList.get(i);
        }
        return tmp;
    }

    /**
     *
     * @return
     */
    public char getLargestRaw () {

        return largestRaw;
    }

    /**
     *
     * @return
     */
    public char getSmallestRaw () {

        return smallestRaw;
    }

    /**
     *
     * @return
     */
    public CSVWriter getWriter() {
        return writer;
    }

    /**
     *
     * @return
     */
    public  CSVWriter getWriter_ppb() {
        return writer_ppb;
    }


}




Java Source Code List

cleanup.DrawGraph.java
cleanup.Instructions.java
cleanup.PositionService.java
cleanup.QRcodeFromFile.java
cleanup.QRcodeParse.java
cleanup.SaveQRFile.java
display.DynamicPlotDataSource.java
display.DynamicPlotSeries.java
processing.LinearRegression.java
processing.SensorCurve.java
transmission.BluetoothChatService.java
transmission.LocalProfile.java
transmission.thirdlib.capture.CaptureActivityHandler.java
transmission.thirdlib.capture.CaptureActivity.java
transmission.thirdlib.capture.DecodeFormatManager.java
transmission.thirdlib.capture.DecodeHandler.java
transmission.thirdlib.capture.DecodeThread.java
transmission.thirdlib.capture.FinishListener.java
transmission.thirdlib.capture.InactivityTimer.java
transmission.thirdlib.capture.IntentSource.java
transmission.thirdlib.capture.Intents.java
transmission.thirdlib.capture.PlanarYUVLuminanceSource.java
transmission.thirdlib.capture.PreferencesActivity.java
transmission.thirdlib.capture.ViewfinderResultPointCallback.java
transmission.thirdlib.capture.ViewfinderView.java
transmission.thirdlib.manager.AutoFocusCallback.java
transmission.thirdlib.manager.CameraConfigurationManager.java
transmission.thirdlib.manager.CameraManager.java
transmission.thirdlib.manager.PreviewCallback.java
userinterface.BluetoothViewer.java
userinterface.ConfigActivity.java
userinterface.DeviceListActivity.java
userinterface.GuideActivity.java
userinterface.HistoryActivity.java
userinterface.SlidingDrawerActivity.java
userinterface.Welcome.java