using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using ArduinoBluetoothAPI; public class BluetoothBC_Old : MonoBehaviour { private BluetoothHelper bluetoothHelper; private BluetoothHelperCharacteristic characteristicWrite; private string deviceName = "PBox-000000b"; private bool canConnect = true; [SerializeField] string targetDeviceName = "BGBox_202012"; [SerializeField] Text textUI; void OnDestroy() { if (bluetoothHelper != null) { bluetoothHelper.Disconnect(); } } void FixedUpdate() { this.Connect(); } void Connect() { if (!canConnect) { return; } canConnect = false; try { BluetoothHelper.BLE = true; bluetoothHelper = BluetoothHelper.GetNewInstance(); bluetoothHelper.setFixedLengthBasedStream(20); bluetoothHelper.OnConnected += (BluetoothHelper helper) => { Log("连接成功\n" + helper.getDeviceName()); bluetoothHelper.StartListening(); foreach(BluetoothHelperService service in helper.getGattServices()) { foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics()) { if (service.getName().ToLower().StartsWith("0000fff0")) { if (characteristic.getName().ToLower().StartsWith("0000fff2")) { characteristicWrite = characteristic; } else if (characteristic.getName().ToLower().StartsWith("0000fff1")) { bluetoothHelper.Subscribe(characteristic); bluetoothHelper.ReadCharacteristic(characteristic); } } } } Invoke("OpenReceiveData", 2); Invoke("SetReceiveDataInterval20", 4); }; bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) => { canConnect = true; Log("连接失败\n" + helper.getDeviceName()); }; bluetoothHelper.OnDataReceived += (BluetoothHelper helper) => { byte[] bytes = helper.ReadBytes(); // float ax = ToAcceleratedSpeed(bytes[4], bytes[5]); // float ay = ToAcceleratedSpeed(bytes[6], bytes[7]); // float az = ToAcceleratedSpeed(bytes[8], bytes[9]); }; bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList nearbyDevices) => { foreach (BluetoothDevice device in nearbyDevices) { if (device.DeviceName == targetDeviceName) { deviceName = device.DeviceName; bluetoothHelper.setDeviceName(deviceName); bluetoothHelper.Connect(); Log("发现设备\n" + device.DeviceName); return; } } canConnect = true; Log("没有发现设备"); }; bluetoothHelper.ScanNearbyDevices(); Log("正在扫描设备"); } catch (Exception e) { Debug.Log(e.Message); canConnect = true; Log("请打开蓝牙"); } } void OpenReceiveData() { bluetoothHelper.WriteCharacteristic(characteristicWrite, "3"); Log("开始接收信息\n" + deviceName); } void SetReceiveDataInterval20() { bluetoothHelper.WriteCharacteristic(characteristicWrite, "b"); Log("修改接收频率\n" + deviceName); } int TwoByteToInt(byte b1, byte b2) { ushort twoByte = (ushort) (b1 * 256 + b2); short shortNum = (short) twoByte; return (int) shortNum; } float ToAcceleratedSpeed(byte b1, byte b2) { int value = TwoByteToInt(b1, b2); return (float) value / 32768 * 16; } void Log(string text) { if (textUI != null) { textUI.text = text; } } }