package com.siwei.recyclebox.deviceUtils;

import android.hardware.usb.UsbManager;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import com.aliyuncs.exceptions.ClientException;
import com.siwei.recyclebox.ui.main.MainViewModel;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;

import android.os.Handler;

import java.io.IOException;
import java.util.Spliterator;
import java.util.logging.LogRecord;

import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.Utils;


public class UltrasonicDevice extends BaseDeviceEntity {

    public UltrasonicDevice(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 6790;
    }

    @Override
    void onDataReceived(byte[] response) {

    }

    String TAG = "超声波";

    /**
     * 超声波读数
     * 01 03 01 02 00 01 24 36
     */
    public Integer ultRead() {
        int disInt = 0;
        while (true){
            try {
//                Thread.sleep(500);
                byte[] bytes = new byte[]{(byte) 0x01, (byte) 0x03, 0x01, 0x02, 0x00, 0x01, 0x24, (byte) 0x36};
                port.write(bytes, 100);
                Log.i(TAG,"发 ："+ ByteUtil.bytesToString(bytes));
                byte[] response = new byte[12];
                int len = port.read(response, 100);
                Log.i(TAG, "收 :"+ByteUtil.bytesToString(response));
                Log.i(TAG, "数组长度 :" + len);
                byte[] disBytes = new byte[4];
                disBytes[2] = response[3];
                disBytes[3] = response[4];
                disInt = ByteUtil.bytes2Int(disBytes);
                Log.i(TAG, "距离 :" + disInt);
//                if (response[4] == 85 && response[5] == 1) {
                if (len == 7) {
                    Log.i(TAG, "ultRead: "+disInt);
                    return disInt;
                } else {
                    SPUtils.getInstance().put("RunningState", 5);
//                    MainViewModel.SendSmsResponse("温度超声波失灵");
                    Thread.sleep(200);
                }
            } catch (Exception e) {
                e.printStackTrace();
                SPUtils.getInstance().put("RunningState", 1);
                MainViewModel.SendSmsResponse("其他设备未检测到");
                return 0;
            }
        }
//        return (Integer)disInt;
    }
}
    
