package com.siwei.recyclebox.deviceUtils;

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

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 继电器
 */
public class RelayControllerDevice extends BaseDeviceEntity {
    private static final String TAG = "relayControllerDevice";

    public RelayControllerDevice(UsbManager usbManager, UsbSerialDriver driver) {
        super(usbManager, driver);
    }

    /**
     * 串口的连接参数：
     * baudRate: 波特率
     * dataBits: 数据位 一般为8
     * stopBits: 停止位 一般为1
     * parity: 奇偶校验 UsbSerialPort.PARITY_ODD、UsbSerialPort.PARITY_EVEN、UsbSerialPort.PARITY_NONE
     */
    @Override
    int getBaudRate() {
        return 9600;
    }

    @Override
    int getDataBits() {
        return UsbSerialPort.DATABITS_8;
    }

    @Override
    int getStopBits() {
        return UsbSerialPort.STOPBITS_1;
    }

    @Override
    int getParity() {
        return UsbSerialPort.PARITY_NONE;
    }

    @Override
    int getVendorId() {
        return 1659;
    }

    @Override
    void onDataReceived(byte[] response) {

    }


    /**
     * 获取继电器所有口的状态
     * @return
     */
    public List readRelayControllerStatus(){
        try {
             port.write(new byte[]{0x33, 0x01, 0x17, 0x00,0x00, 0x00, (byte) 0x00, 0x4B},2000);//继电器读取所有开关

            List<byte[]> resList = new ArrayList<>();

            long startTimeMillis =System.currentTimeMillis();
            int readLengthCache = 0;
            byte[] responseCache = new byte[8];
            while (System.currentTimeMillis()-startTimeMillis  < 100 ){
                byte[] response = new byte[8];
                int len = port.read(response,20);
                System.out.println("读取到："+ByteUtil.bytesToString(response)+"  len:"+len);
                if(len>0){
                    if(readLengthCache == 0 && response[0] != 0x22){//一个包的起始为0x22
                        continue;
                    }
                    for(int i = 0 ;i<len;i++){
                        if(readLengthCache>=8)
                            break;
                        responseCache[readLengthCache] = response[i];
                        readLengthCache++;
                    }
                    if(readLengthCache>=8){//读够了一帧。做校验。
                        byte rex = 0x00;
                        for(int i = 0 ;i< 7;i++){
                            rex += responseCache[i];
                        }
                        if(rex == responseCache[7]){
                            Log.i(TAG, "继电器回包校验成功");
                            resList.add(responseCache);
                        }else{
                            Log.i(TAG, "继电器回包校验失败！");
                        }
                        System.out.println(ByteUtil.bytesToString(responseCache));
                        responseCache = new byte[8];
                        readLengthCache = 0;        //复位，从头又开始读。
                    }
                }
            }
            return resList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 断开继电器一个端口
     * @param index 需要断电的端口的index
     * @throws IOException
     */
    public void closeOne( short index) throws IOException {
        if(index>3|| index<0){
            Log.e(TAG,"index的值须在0-3之间。");
            return;
        }
        byte[] closeBytes = new byte[8];
        closeBytes[0] = 0x33;//帧头
        closeBytes[1] = 0x01;//地址
        closeBytes[2] = 0x11;//功能码：11-断开  12-吸合  13-全断开  14-全吸合  15-互锁  16-组合功能 17-查询所有继电器状态。
        byte[] indexBytes = ByteUtil.int2byte(index);
        System.arraycopy(indexBytes,0,closeBytes,3,4);
        byte xor = 0x00;
        for (int i = 0 ; i <7 ; i++){
            xor+= closeBytes[i];
        }
        closeBytes[7] = xor;//最后一位是校验码，前7个数据相加的和，
        port.write(closeBytes,200);
        List<byte[]> responseBytes = readBytes();
        if(responseBytes.size()!= 0){
            byte[] response = responseBytes.get(0);
            Arrays.equals(response,closeBytes);
        }
    }

    /**
     * 给继电器的一个端口通电。
     * @param index 需要通电的端口的index
     */
    public void openOne( short index ) throws IOException {
        if(index>3|| index<0){
            Log.e(TAG,"index的值须在0-3之间。");
            return;
        }
        byte[] openBytes = new byte[8];
        openBytes[0] = 0x33;//帧头
        openBytes[1] = 0x01;//地址
        openBytes[2] = 0x12;//功能码：11-断开  12-吸合  13-全断开  14-全吸合  15-互锁  16-组合功能 17-查询所有继电器状态。
        byte[] indexBytes = ByteUtil.int2byte(index);
        System.arraycopy(indexBytes,0,openBytes,3,4);
        byte xor = 0x00;
        for (int i = 0 ; i <7 ; i++){
            xor+= openBytes[i];
        }
        openBytes[7] = xor;//最后一位是校验码，前7个数据相加的和，
        System.out.println("打开端口的完整命令:"+ByteUtil.bytesToString(openBytes));
        port.write(openBytes,200);
        List<byte[]> responseBytes = readBytes();
        if(responseBytes.size()!= 0){
            byte[] response = responseBytes.get(0);
            Arrays.equals(response,openBytes);
        }

    }

    private List<byte[]> readBytes( ){
        List<byte[]> resList = new ArrayList<>();
        try {
            long startTimeMillis =System.currentTimeMillis();
            int readLengthCache = 0;
            byte[] responseCache = new byte[8];
            while (System.currentTimeMillis()-startTimeMillis  < 70 ){
                byte[] response = new byte[8];
                int len = port.read(response,10);
                System.out.println("读取到："+ByteUtil.bytesToString(response)+"  len:"+len);
                if(len>0){
                    if(readLengthCache == 0 && response[0] != 0x22){//一个包的起始为0x22
                        continue;
                    }
                    for(int i = 0 ;i<len;i++){
                        if(readLengthCache>=8)
                            break;
                        responseCache[readLengthCache] = response[i];
                        readLengthCache++;
                    }
                    if(readLengthCache>=8){//读够了一帧。做校验。
                        byte rex = 0x00;
                        for(int i = 0 ;i< 7;i++){
                            rex += responseCache[i];
                        }
                        if(rex == responseCache[7]){
                            Log.i(TAG, "继电器回包校验成功");
                            resList.add(responseCache);
                        }else{
                            Log.i(TAG, "继电器回包校验失败！");
                        }
                        System.out.println(ByteUtil.bytesToString(responseCache));
                        responseCache = new byte[8];
                        readLengthCache = 0;        //复位，从头又开始读。
                    }
                }
            }
        }catch (Exception e ){
            Log.e(TAG,e.getMessage(),e);
        }
        return resList;
    }


}
