package com.develop.foodcooking;

import android.serialport.SerialPort;
import android.util.Log;

import com.kuyuntech.cofarcooking.device.sdk.protocol.core.BaseDecoder;
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK;


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


public class ProtocolListener implements Runnable {

    private final SerialPort serialPort;


    public ProtocolListener(SerialPort serialPort){
        this.serialPort = serialPort;
    }

    @Override
    public void run() {
        try{
            byte[] tmp = new byte[1024];
            int len = -1 ;
            List<Byte> bytes = new ArrayList<>();
            while ((len = this.serialPort.getInputStream().read(tmp)) != -1){
                byte[] cmdTmp  = Arrays.copyOf(tmp,len);
                tmp = new byte[1024];
                for (byte b : cmdTmp) {
                        if(b == 0x7e){
                            if(bytes.size() == 0){
                                bytes.add(b);
                            }else{
                                bytes.add(b);

                                try {
                                    byte[] cmd = new byte[bytes.size()];
                                    for (int i = 0; i < bytes.size(); i++) {
                                        cmd[i] = bytes.get(i);
                                    }

                                    BaseDecoder baseDecoder = new BaseDecoder(cmd);
                                    Log.i("mcu2dev:",baseDecoder.escapeBytesStr());
                                    CofarSDK.post2Dev(baseDecoder.getBaseBody());
                                    bytes.clear();

                                }catch (Exception e){
                                    e.printStackTrace();
                                    Log.i("weilai-protocol",e.getMessage());
                                    bytes.clear();
                                    bytes.add(b);
                                }



                            }
                        }else if (bytes.size() != 0){
                            bytes.add(b);
                        }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
            Log.i("weilai-protocol",e.getMessage());
        }


    }

}
