Unity pc蓝牙和安卓蓝牙通信

pc是客户端,安卓是服务端。
pc端需要拖入一个 InTheHand.Net.Bluetooth.dll 文件放在Plugins文件夹里。dll文件下载链接
pc端参考资料
https://blog.csdn.net/oqzuser12345678923/article/details/51252545/
http://t.zoukankan.com/buptzym-p-2169858.html

安卓端使用是 NativeBT 插件,这个插件网上就可以下载

下面是pc客户端的代码

using UnityEngine;
using System.Threading;
using System;
using System.IO;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;

public class PC_BLT : MonoBehaviour
{
    // 80:19:31:8C:6B:22
    //F0:C8:14:33:8B:99
    private Thread ReceiveThread;
    private BluetoothClient bluetoothClient = null;
    private Stream peerStream;

    public byte[] buffer = new byte[128]; //接收数据

    private bool isConnecting = true;


    private BluetoothAddress sendAddress = new BluetoothAddress(new byte[] { 0x22, 0x6B, 0x8C, 0x31, 0x19, 0x80 }); //发送目的地址 地址要反着写

    // Start is called before the first frame update
    void Start()
    {
        BluetoothRadio bluetoothRadio =  BluetoothRadio.Default;
        if (bluetoothRadio == null)
        {
            Debug.Log("没有找到本机蓝牙设备!");
        }
        else
        {
            Debug.Log("ClassOfDevice: " + bluetoothRadio);
            Debug.Log("Name: " + bluetoothRadio.Name);
            Debug.Log(bluetoothRadio.LocalAddress);
            Debug.Log(bluetoothRadio.LmpSubversion);
            Guid guid = BluetoothService.Handsfree;
            Debug.Log(guid);
            
        }
        Console.ReadKey();

        OpenPort();
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            WriteMethod();
        }
    }

    /// <summary>
    /// 打开端口
    /// </summary>
    /// <param name="Name">端口名称</param>
    /// <returns>成功否</returns>
    public bool OpenPort()
    {

        BluetoothRadio.Default.Mode = RadioMode.Connectable;
        bluetoothClient = new BluetoothClient();
        Guid mGUID = Guid.Parse("c1db6770-a359-11e6-80f5-76304dec7eb7");

        // mGUID2 = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");
        //bluetoothClient.Connect(sendAddress, mGUID2);//客户端对地址实现连接,这是一个阻塞线程,需要服务器端的回应

        bluetoothClient.Connect(sendAddress, mGUID);//客户端对地址实现连接,这是一个阻塞线程,需要服务器端的回应

        if (bluetoothClient.Connected)
        {
            Debug.Log("连接成功");

            if (ReceiveThread != null && ReceiveThread.IsAlive)
            {
                ReceiveThread.Abort();

            }
            ReceiveThread = new Thread(new ThreadStart(ReceiveMethod));
            ReceiveThread.Start();

           
        }
        else
        {
            Debug.Log("连接未成功");
        }
        return true;
    }

    
    /// <summary>
    /// 接收数据
    /// </summary>
    public void ReceiveMethod()
    {
        while (isConnecting)
        {

            try
            {
                peerStream = bluetoothClient.GetStream();
                
                int a = peerStream.Read(buffer, 0, buffer.Length);

            }
            catch (Exception ex)
            {
                isConnecting = false;

                if (ReceiveThread != null && ReceiveThread.IsAlive)
                {
                    ReceiveThread.Abort();

                }

                Debug.Log(ex);
            }

        }
    }

    /// <summary>
    /// 发送数据
    /// </summary>
    public void WriteMethod()
    {
        byte[] data = new byte[3] { 0x0A, 0x02, 0x03};
        peerStream.Write(data,0 , data.Length);
    }
    

    public void OnDestroy()
    {
        
        if (ReceiveThread != null && ReceiveThread.IsAlive)
        {
            ReceiveThread.Abort();

        }

        BluetoothRadio.Default.Mode = RadioMode.PowerOff;

        if (bluetoothClient != null && bluetoothClient.Connected)
        {
            bluetoothClient.Dispose();
            bluetoothClient.Close();
        }
    }
}

下面是安卓服务端代码

using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;

using leithidev.unityassets.nativebt.android.entities;

public class BTChat : MonoBehaviour
{
    public Text _connectedToText;
    public Text _listeningOnText;
    public Text _chatText;
    public InputField _sendInputField;
    public Text _sendText;
    public PairedDeviceButton _pairedDeviceListButton;
    public RectTransform _pairedDeviceList;
    public RectTransform _btnDisconnect;
    public RectTransform _btnPairedDevices;
    public string uuid = "c1db6770-a359-11e6-80f5-76304dec7eb7";

    // Use this for initialization
    void Start()
    {
        NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTMessageReceived += OnMessageReceived;
        NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTMessageSent += OnMessageSent;
        NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTDeviceConnected += OnBtDeviceConnected;
        NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTDeviceDisconnected += OnBtDeviceDisconnected;
        NativeBTRuntime.NBTR.BTHandler.BTEventsHandler.BTDeviceConnectingFailed += OnBTDeviceConnectingFailed;

        this._pairedDeviceList.gameObject.SetActive(false);
        this._btnDisconnect.gameObject.SetActive(false);
    }

    private void OnBTDeviceConnectingFailed(LWBluetoothDevice device)
    {
        this._connectedToText.text = "Connecting to " + device.GetName() + " failed!";
    }

    private void OnBtDeviceConnected(LWBluetoothDevice device)
    {
        this._connectedTo = device;
        this._connectedToText.text = device.GetName();
        this._btnDisconnect.gameObject.SetActive(true);
        this._btnPairedDevices.gameObject.SetActive(false);
    }

    private void OnBtDeviceDisconnected(LWBluetoothDevice device)
    {
        this._connectedTo = null;
        this._connectedToText.text = "";
        this._btnDisconnect.gameObject.SetActive(false);
        this._btnPairedDevices.gameObject.SetActive(true);
    }

    private void OnMessageSent(string msg)
    {
        this._chatText.text += "\n" + NativeBTRuntime.NBTR.BTWrapper.GetBTAdapter().GetName() + ": " + msg;
    }

    /// <summary>
    /// 接收数据
    /// </summary>
    /// <param name="msg"></param>
    private void OnMessageReceived(string msg)
    {
        Debug.Log("数据:" + msg + "长度:" + msg.Length);

        if (msg.Length > 0)
        {
            System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();

            for (int i = 0; i < asciiEncoding.GetBytes(msg).Length; i++)
            {
                Debug.Log(asciiEncoding.GetBytes(msg)[i]);
            }

        }


        //this._chatText.text += "\n" + this._connectedTo.GetName() + ": " + msg;
    }

    public void OnDisconnectButtonClicked()
    {
        NativeBTRuntime.NBTR.BTWrapper.Disconnect();
    }

    public void OnSendButtonClicked()
    {
        string msg = this._sendInputField.text;
        this._sendInputField.text = "";

        NativeBTRuntime.NBTR.BTWrapper.Send(msg + System.Environment.NewLine);
    }

    public void OnPairedDeviceButtonClicked(LWBluetoothDevice btDevice)
    {
        NativeBTRuntime.NBTR.BTWrapper.Connect(btDevice, this.uuid);
        this._pairedDeviceList.gameObject.SetActive(false);
    }

    public void OnPairedDevicesClicked()
    {
        if (!NativeBTRuntime.NBTR.BTWrapper.GetBTAdapter().IsEnabled())
        {
            NativeBTRuntime.NBTR.BTWrapper.ShowBTEnableRequest();
        }
        else
        {
            IList<LWBluetoothDevice> devices = NativeBTRuntime.NBTR.BTWrapper.GetPairedDevices();
            this._pairedDeviceList.gameObject.SetActive(true);
            this.ClearPairedDevicesList();
            if (devices.Count == 0)
            {
                this._pairedDeviceList.gameObject.SetActive(false);
            }
            foreach (LWBluetoothDevice device in devices)
            {
                PairedDeviceButton pdb = Instantiate<PairedDeviceButton>(this._pairedDeviceListButton);
                pdb._device = device;
                pdb.GetComponent<Button>().GetComponentInChildren<Text>().text = device.GetName() + "|" + device.GetAddress();
                pdb.GetComponent<Button>().onClick.AddListener(() => OnPairedDeviceButtonClicked(pdb._device));
                pdb.transform.SetParent(this._pairedDeviceList);
            }
        }
    }

    private void ClearPairedDevicesList()
    {
        IList<GameObject> objsToDestroy = new List<GameObject>();
        for (int x = 0; x < this._pairedDeviceList.transform.childCount; x++)
        {
            objsToDestroy.Add(this._pairedDeviceList.transform.GetChild(x).gameObject);
        }

        foreach (GameObject go in objsToDestroy)
        {
            Destroy(go);
        }
    }

    public void OnListenClicked()
    {
        NativeBTRuntime.NBTR.BTWrapper.Disconnect();
        if (!NativeBTRuntime.NBTR.BTWrapper.GetBTAdapter().IsEnabled())
        {
            NativeBTRuntime.NBTR.BTWrapper.ShowBTEnableRequest();
        }
        else
        {
            NativeBTRuntime.NBTR.BTWrapper.Listen(true, this.uuid);
            this._listeningOnText.text = "Listen on: " + uuid;
        }
    }

    private LWBluetoothDevice _connectedTo;
}

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值