package android_serialport_api;

import android.app.Application;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;

/**
 * Created by Administrator on 2019/12/17.
 */

public class SerialApp extends Application {
    private static final String TAG = "serial_port";

    public SerialPortFinder mSerialPortFinder = new SerialPortFinder();
    private SerialPort mSerialPort = null;

    static int app_baudrate;
    static String app_device;

    /*loading the usart*/
    public SerialPort getSerialPort() throws SecurityException, IOException, InvalidParameterException {
        if (mSerialPort == null) {
			/* Read serial port parameters */
            //SharedPreferences sp = getSharedPreferences("android_serialport_api.sample_preferences", MODE_PRIVATE);
            //String path = sp.getString("DEVICE", "");
            //int baudrate = Integer.decode(sp.getString("BAUDRATE", "-1"));

            int baudrate = get_baudrate();
            String path = get_device();

            Log.v(TAG,"path:"+path);
            Log.v(TAG,"baudrate:"+baudrate);

			/* Check parameters */
            if ( (path.length() == 0) || (baudrate == -1)) {
                throw new InvalidParameterException();
            }

			/* Open the serial port */
            mSerialPort = new SerialPort(new File(path), baudrate, 0);
        }
        return mSerialPort;
    }

    public void set_baudrate(int baudrate)
    {
        app_baudrate = baudrate;
    }

    public int get_baudrate()
    {
        return app_baudrate ;
    }

    public void set_device(String device)
    {
        app_device = device;
    }

    public String get_device()
    {
        return app_device;
    }

    public void closeSerialPort() {
        if (mSerialPort != null) {
            mSerialPort.close();
            mSerialPort = null;
        }
    }
}
