package cn.wintec.wtandroidjar;

import java.io.IOException;
import java.text.DecimalFormat;
import android.util.Log;

public class SCL {
    private ComIO comio;

    public SCL(String devicePath) {
        // comio = new ComIO("/dev/ttySAC0");//3
        comio = new ComIO(devicePath);
        comio.setSerialBaudrate(9600);
        // 打开流控
    }

    public SCL(String devicePath, ComIO.Baudrate baudrate) {
        comio = new ComIO(devicePath);
        comio.setSerialBaudrate(baudrate);
        // 打开流控
    }

    private boolean OutPutSerialPort(String bytes) {
        try {
            comio.write(bytes.getBytes("ASCII"));
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

    public void PAUSE() {
        OutPutSerialPort("PAUSE\r\n");
    }

    public void RESUME() {
        OutPutSerialPort("RESUME\r\n");
    }

    public String ASCII2HexString(byte[] src, int n) {
        char[] data = new char[n];
        for (int i = 0; i < src.length; i++) {
            data[i] = (char) ((int) (src[i]));
        }
        return new String(data);
    }

    public byte[] ReadData() {

        byte[] line = new byte[22];
        int index = 0;
        byte[] content = new byte[2];
        for (; ; ) {
            if (comio.read(content, 0, 1, 100) != 0) {
                line[index] = content[0];
                index++;
                if (index >= 22) // 防止读取超出地址
                {
                    break;
                }
                if (content[0] == 10)// read end
                {
                    break;
                }
            } else {
                // WGT:3 0.000P 0.000\r\n
                line[0] = 'E';
                for (int i = 1; i < 22; i++) {
                    line[i] = 0;

                }
                return line;
            }
        }
        return line;
    }

    /**
     * 打印byte数组
     */
    String printByte(byte[] byteData) {
        Log.i("pupu原始数据", "byteData length==>" + byteData.length);
        String result = "";
        for (int i = 0; i < byteData.length; i++) {
            Log.i("pupu原始数据", "byteData[i]==>" + Integer.toBinaryString(((int) byteData[i])));
            result = result + byteData[i];
        }
        return result;
    }

    /**
     * 标准读取
     *
     * @param buf
     * @return 标志位（1个字节）+净重（6个字节）+P+皮重（6个字节）
     */
    public int read_standard(byte[] buf) {
        byte[] content = ReadData();
//        Log.i("pupu原始数据", printByte(content));
        Log.i("13", ASCII2HexString(content, 22));
        if (content[0] == 'W') {// 称重数据
            byte status = content[4];
            byte[] net_weight = new byte[7];
            byte sep = 'P';
            byte[] tare_weight = new byte[7];
            System.arraycopy(content, 5, net_weight, 0, 6);
            System.arraycopy(content, 12, tare_weight, 0, 6);
            buf[0] = status;
            for (int i = 0; i < 6; i++) {
                buf[i + 1] = net_weight[i];
            }
            buf[7] = sep;
            for (int j = 0; j < 6; j++) {
                buf[j + 8] = tare_weight[j];
            }
            return 0;
        } else if (content[0] == 'R') {// 指令结果
            System.arraycopy(content, 0, buf, 0, 12);
            return 1;
        } else if (content[0] == 'E') {// 错误
            System.arraycopy(content, 0, buf, 0, 12);
            return 2;
        }

        return 2;
    }

    /**
     * 供外部判断是否已经成功连接
     *
     * @return
     */
    public boolean isConnected() {
        return !new String(ReadData()).startsWith("E");
    }

    /**
     * 重置零点
     *
     * @return true：指令发送成功；false：指令发送失败
     * @author pupu
     */
    public boolean resetZero() {
        return OutPutSerialPort("ZERO\r\n");
    }

    /**
     * 设置皮重
     *
     * @param tare 皮重，单位kg
     * @return
     * @author pupu
     */
    public boolean setTare(double tare) {
        DecimalFormat df = new DecimalFormat("######0.000");
        return OutPutSerialPort("YTARE " + df.format(tare) + "\r\n");
    }

    /**
     * 重量标定
     *
     * @param weight 标准重量
     * @return
     * @author pupu
     */
    public boolean markWeight(double weight) {
        DecimalFormat df = new DecimalFormat("######0.000");
        return OutPutSerialPort("CALL " + df.format(weight) + "\r\n");
    }

    /**
     * 设置重力系数
     *
     * @param gravity 重力系数
     * @return
     * @author pupu
     */
    public boolean setGravity(double gravity) {
        return OutPutSerialPort("GSET " + gravity + "\r\n");
    }

    // 置零
    public void send_zero() {
        OutPutSerialPort("ZERO\r\n");
    }

    // 零位标定
    public void calibration_zero() {
        OutPutSerialPort("CALZ\r\n");

    }

    // 量程标定
    public void calibration_range(double weight) {
        DecimalFormat df = new DecimalFormat("######0.000");
        OutPutSerialPort("CALL " + df.format(weight) + "\r\n");

    }

    // 设置重力

    public void calibration_gravity(double d) {
        OutPutSerialPort("GSET " + d + "\r\n");

    }

    // 去皮

    public void send_tare() {
        OutPutSerialPort("TARE\r\n");

    }

    // 设置皮重

    public void send_ytare(double d) {
        DecimalFormat df = new DecimalFormat("######0.000");

        OutPutSerialPort("YTARE " + df.format(d) + "\r\n");

    }

    // 设置其他参数

    public void send_other(int x1, int x2, int x3, int x4) {

        OutPutSerialPort("PSET" + x1 + x2 + x3 + x4 + "\r\n");
    }

    // 参数设定

    public void send_parameter(int model, int full, int mid, int deci, int div, int div2) {

        OutPutSerialPort("SETALL " + model + " " + full + " " + mid + " " + deci + " " + div + " " + div2 + " \r\n");

    }

    // 获取标定状态

    public void calibration() {

        OutPutSerialPort("KSGET\r\n");

    }

    // 获取AD版本号

    public void get_version() {

        OutPutSerialPort("version\r\n");

    }

    public void SCL_close() {
        comio.readFinish();

    }
}
