package com.common.bluetooth.service.bt;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;

import com.common.bluetooth.BtConstants;

import java.util.concurrent.Executors;

/**
 * 服务端监听和连接线程，只连接一个设备
 *
 * @author wangym
 * @version 2021-12-2
 */
public class BluetoothClassicServer extends BluetoothClassicBase {
    private static final String TAG = BluetoothClassicServer.class.getSimpleName();
    private BluetoothServerSocket mSSocket;

    BluetoothClassicServer(Context context) {
        super(context);
    }

    /**
     * 监听客户端发起的连接
     */
    public void listen() {
        try {
            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
//            mSSocket = adapter.listenUsingRfcommWithServiceRecord(TAG, SPP_UUID); //加密传输，Android强制执行配对，弹窗显示配对码
            mSSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(TAG,
                    BtConstants.INSTANCE.getCLASSIC_BT_UUID()); //明文传输(不安全)，无需配对
            // 开启子线程
            Executors.newCachedThreadPool().execute(() -> {
                try {
                    BluetoothSocket socket = mSSocket.accept(); // 监听连接
                    mSSocket.close(); // 关闭监听，只连接一个设备
                    loopRead(socket); // 循环读取
                } catch (Throwable e) {
                    close();
                }
            });
        } catch (Throwable e) {
            close();
        }
    }

    @Override
    public void close() {
        try {
            mSSocket.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        super.close();
    }
}