package com.bonait.bnframework.modules.home.fragment.mode;

import android.hardware.usb.UsbManager;
import android.serialport.SerialPort;
import android.util.Log;

import com.serotonin.modbus4j.serial.SerialMessage;
import com.serotonin.modbus4j.sero.util.ArrayUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import kotlin.text.UStringsKt;

/**
 *
 */
public class ShaoMaSave implements Runnable{

    private static  final String Tag = "串口处理类";
    private String path="";//串口地址
    private SerialPort sp;//串口对象
    private InputStream inputStream;//串口输入流对象
    private BufferedInputStream bufferedInputStream;//监听硬件返回信息
    private SerialInter serialInter;//串口回调接口
    private OutputStream outputStream;//串口输出流对象 用于发送指令
    private ScheduledFuture readTask;//串口读取任务

    private boolean isRead = true;//是否循环读取


    /**
     * 回调接口
     * @param serialInter
     */
    public void addSerialInter(SerialInter serialInter){
        this.serialInter = serialInter;
    }

    /**
     * @param devicePath 串口地址
     * @param baudrate 波特率
     * @param isRead 是否持续监听返回数据
     * @return 是否打开串口成功
     */
    public boolean Open(String devicePath,int baudrate,boolean isRead){
        return Open(devicePath,baudrate,8,1,0,isRead);
    }

    /**
     * @param devicePath 串口地址
     * @param baudrate 波特率
     * @param dataBits 数据位
     * @param stopBits 停止位
     * @param parity 校验位
     * @param isRead 是否持续监听
     * @return 是否打开成功
     */
    public boolean Open(String devicePath,int baudrate,int dataBits,int stopBits,int parity,boolean isRead){
        boolean isSucc = false;
        try{
            if (sp != null) Close();//关闭
            File device = new File(devicePath);
            sp = SerialPort
                    .newBuilder(device,baudrate)
                    .dataBits(dataBits)
                    .stopBits(stopBits)
                    .parity(parity)
                    .build();//打开串口对象并返回
            inputStream = sp.getInputStream();
            bufferedInputStream = new BufferedInputStream(inputStream);
            outputStream = sp.getOutputStream();
            isSucc = true;
            path = devicePath;
            this.isRead = isRead;
            if (isRead) readData();
        }catch (Throwable tr){
            Close();//关闭sp
            isSucc = false;
        }finally {
            serialInter.connectMsg(path,isSucc);
            return isSucc;
        }
    }

    private  void readData(){
        new Thread(this).start();
    }

    @Override
    public void run(){
        while (this.isRead){
            if (Thread.currentThread().isInterrupted()) continue;
            try{
                int available = inputStream.available();
                if (available == 0) continue;
                if (inputStream == null) continue;
                byte[] received = new byte[1];
                String x="";
                int t = 1;
                while (t>0){
                   t= inputStream.read(received);
                   x+=new String(received);
                }
                if (x!="")
                    serialInter.readData(path,received,t);
                Thread.sleep(20);
            }catch (InterruptedException e){
                Log.e(Tag,"线程异常"+e.toString());
            }catch(IOException e){
                Log.e(Tag,"串口读取异常："+e.toString());
            }
        }

    }

    /**
     * 关闭串口
     */
    public void Close(){
        try {
            if (inputStream!=null) inputStream.close();
        }catch (Exception e){
            Log.e(Tag,"串口输入流对象关闭异常"+e.toString());
        }
        try{
            if (outputStream!=null) outputStream.close();
        }catch (Exception e){
            Log.e(Tag,"串口输出流对象关闭异常"+e.toString());
        }
        try{
            if (sp!=null) sp.close();
        }catch (Exception e){
            Log.e(Tag,"串口对象关闭异常"+e.toString());
        }
    }

    /**
     * 发送指令
     * @param msg
     */
    public void send(String msg){
        byte[] bytes = hexStr2bytes(msg);
        try {
            outputStream.write(bytes);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 把十六进制表示的字节数组字符串，转换成十六进制字节数组
     *
     * @param
     * @return byte[]
     */
    private byte[] hexStr2bytes(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toUpperCase().toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (hexChar2byte(achar[pos]) << 4 | hexChar2byte(achar[pos + 1]));
        }
        return result;
    }

    /**
     * 把16进制字符[0123456789abcde]（含大小写）转成字节
     * @param c
     * @return
     */
    private static int hexChar2byte(char c) {
        switch (c) {
            case '0':
                return 0;
            case '1':
                return 1;
            case '2':
                return 2;
            case '3':
                return 3;
            case '4':
                return 4;
            case '5':
                return 5;
            case '6':
                return 6;
            case '7':
                return 7;
            case '8':
                return 8;
            case '9':
                return 9;
            case 'a':
            case 'A':
                return 10;
            case 'b':
            case 'B':
                return 11;
            case 'c':
            case 'C':
                return 12;
            case 'd':
            case 'D':
                return 13;
            case 'e':
            case 'E':
                return 14;
            case 'f':
            case 'F':
                return 15;
            default:
                return -1;
        }
    }


}
