package com.miya.weighing;

import android.content.Context;
import android.os.Build;
import android.os.CountDownTimer;
import android.util.Log;

import pupu.chuangjieweighing.ReadSerialPort;
import pupu.chuangjieweighing.SerialPortFunction;


/**
 * 创捷称重驱动
 *
 * @author pupu
 * @time 2018/11/06
 */
public class ChuangjieWeighing extends BaseWeighing {

    final static String TAG = ChuangjieWeighing.class.getSimpleName();

    /**
     * 方法提供类
     */
    SerialPortFunction serialPortFunction;

    /**
     * 标志是否正在置零
     */
    boolean isResetZeroing = false;

    @Override
    public boolean init(Context context) {
        //根据序列号判断是否是创捷机器
        if (!Build.SERIAL.startsWith("CCL")) {
            return false;
        }
        serialPortFunction = SerialPortFunction.getInstance();
        serialPortFunction.setContext(context);
        try {
            serialPortFunction.getWeighingSerialPort("/dev/ttyS4", 9600);
            serialPortFunction.startReadWeight(new ReadSerialPort.DataWeight() {
                @Override
                public void weight(String s, boolean isStable) {
                    Log.i(TAG, "当前重量为：" + s);
                    curWeight = parseKg2g(s.trim());
                    if (weighingCallback != null && curWeight >= 0) {
                        weighingCallback.returnWeight(curWeight, isStable);
                    }
                    if (curWeight < 0) {
                        //发送置零指令
                        if (isResetZeroing == false) {
                            resetZero();
                        }
                    }
                }
            });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean resetZero() {
        if (serialPortFunction != null && isResetZeroing == false) {
            isResetZeroing = true;
            //发送置零指令，有2s的耗时，内部为线程池异步操作
            serialPortFunction.sendEle("410D0A");
            //3s后改变状态
            new CountDownTimer(3000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    isResetZeroing = false;
                }
            }.start();
            return true;
        }
        return false;
    }

    @Override
    public boolean release() {
        super.release();
        weighingCallback = null;
        if (serialPortFunction != null) {
            serialPortFunction.closeEle();
        }
        return true;
    }
}
