package com.common.bluetooth.service.bt;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.util.Log;

import com.common.bluetooth.BtConstants;
import com.common.bluetooth.callback.BtMsgListener;

import java.util.concurrent.Executors;

/**
 * 经典蓝牙客户端，与服务端建立长连接
 *
 * @author wangym
 * @since 2021-12-1
 */
public class BluetoothClassicClient extends BluetoothClassicBase {
    private static final String TAG = "BtClient";

    public BluetoothClassicClient(Context context) {
        super(context);
    }

    /**
     * 与远端设备建立长连接
     *
     * @param mac 设备MAC
     */
    public void connect(String mac) {
        Log.d(TAG, "start connect mac:" + mac);
        BluetoothDevice bluetoothDevice = getBtDeviceByMac(mac);
        if (bluetoothDevice == null) {
            Log.e(TAG, "connect got device is null : mac is " + mac);
            notifyUI(BtMsgListener.DISCONNECTED, mac);
            return;
        }
        if (isConnected(mac)) {
            Log.i(TAG, "connected, no need to close socket");
            return;
        }
        closeSilence();
        try {
//             final BluetoothSocket socket = dev.createRfcommSocketToServiceRecord(SPP_UUID); //加密传输，Android系统强制配对，弹窗显示配对码
            final BluetoothSocket socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(
                    BtConstants.INSTANCE.getCLASSIC_BT_UUID()); //明文传输(不安全)，无需配对
            // 开启子线程
            Executors.newCachedThreadPool().execute(() -> {
                loopRead(socket); //循环读取
            });
        } catch (Throwable e) {
            close();
        }
    }
}