package com.motse.fengshui_compass.common;

import android.os.Handler;
import android.os.SystemClock;

import com.licheedev.hwutils.ByteUtil;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

public class SerialReadThread extends Thread {
    private static final String TAG = "SerialReadThread";

    private final BufferedInputStream mInputStream;
    private Handler dataHandler;

    public SerialReadThread(InputStream is) {
        mInputStream = new BufferedInputStream(is);
    }

    public SerialReadThread(InputStream is, Handler dataHandler) {
        mInputStream = new BufferedInputStream(is);
        this.dataHandler = dataHandler;
    }

    @Override
    public void run() {
//        super.run();
        byte[] received = new byte[1024];
        int size;

//        LogPlus.e("开始读线程");
        System.out.println("开始读线程");
        while (!Thread.currentThread().isInterrupted()) {
            try {

                int available = mInputStream.available();

                if (available > 0) {
                    size = mInputStream.read(received);
                    if (size > 0) {
                        // TODO: onDataReceive(received, size);
                    }
                } else {
                    // 暂停一点时间，免得一直循环造成CPU占用率过高
                    SystemClock.sleep(1);
                }
            } catch (IOException e) {
//                LogPlus.e("读取数据失败", e);
                e.printStackTrace();
                System.out.println("读取数据失败");
            }
            //Thread.yield();
        }

//        LogPlus.e("结束读进程");
        System.out.println("结束读线程");
    }


    /**
     * 处理获取到的数据
     *
     * @param received
     * @param size
     */
    private void onDataReceive(byte[] received, int size) {
        // TODO: 2018/3/22 解决粘包、分包等
        String hexStr = ByteUtil.bytes2HexStr(received, 0, size);
        // LogManager.instance().post(new RecvMessage(hexStr));
    }

    /**
     * 停止读线程
     */
    public void close() {
        try {
            mInputStream.close();
        } catch (IOException e) {
//            LogPlus.e("异常", e);
            e.printStackTrace();
            System.out.println("异常");
        } finally {
            super.interrupt();
        }
    }
}
