package com.wdkl.ncs.s433.transbox;

import android.content.Context;
import android.content.SharedPreferences;
import android.serialport.SerialPort;
import android.serialport.SerialPortFinder;
import android.util.Log;

import androidx.preference.PreferenceManager;

import com.wdkl.ncs.s433.transbox.utils.AnrFcExceptionUtil;

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

public class Application extends android.app.Application {

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

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

        AnrFcExceptionUtil.getInstance(this).initFCException();
    }

    /**
     * 获取全局上下文
     */
    public static Context getContext() {
        return context;
    }

    public SerialPort getSerialPort()
            throws SecurityException, IOException, InvalidParameterException {
        if (mSerialPort == null) {
            /* Read serial port parameters */
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            Log.i("Application", "getSerialPort: "+sp.getString("serialDeivce","/dev/ttyS2"));
            String path = sp.getString("serialDeivce","/dev/ttyS2"); //sp.getString("DEVICE", "");
            int baudrate = Integer.decode(sp.getString("baudRate", "115200")); //Integer.decode(sp.getString("BAUDRATE", "-1"));
            int parity = Integer.decode(sp.getString("parity", "0"));
            int dataBits = Integer.decode(sp.getString("dataBits", "8"));
            int stopBits = Integer.decode(sp.getString("stopBits", "1"));
            /* Check parameters */
            if ((path.length() == 0) || (baudrate == -1)) {
                throw new InvalidParameterException();
            }

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

            SerialPort serialPort = SerialPort //
                    .newBuilder(path, baudrate) // 串口地址地址，波特率
                    .parity(parity) // 校验位；0:无校验位(NONE，默认)；1:奇校验位(ODD);2:偶校验位(EVEN)
                    .dataBits(dataBits) // 数据位,默认8；可选值为5~8
                    .stopBits(stopBits) // 停止位，默认1；1:1位停止位；2:2位停止位
                    .build();

            mSerialPort = serialPort;
        }
        return mSerialPort;
    }

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