/// <summary> /// 连接蓝牙 /// </summary> /// <param name="addr"></param> public void ConnectBluetooth(string addr) { Debug.Log("Connection to ..." + name + "with address: " + addr + ", in progress... \n"); BluetoothLEHardwareInterface.ConnectToPeripheral(addr, (address) => { Debug.Log("Succeed Name : " + address); }, (address, serviceUUID) => { Debug.Log("address: " + address + " serviceUUID: " + serviceUUID); connecting = true; }, (address, serviceUUID, characteristicUUID) => { // discovered characteristic if (IsEqual(serviceUUID, _serviceUUID)) { _connectedID = address; isConnected = true; if (IsEqual(characteristicUUID, _readCharacteristicUUID)) { Debug.Log("Read Characteristic"); _readFound = true; } if (IsEqual(characteristicUUID, _writeCharacteristicUUID)) { Debug.Log("Write Characteristic"); _writeFound = true; } Debug.Log("Connected"); BluetoothLEHardwareInterface.StopScan(); } }, (address) => { //当设备断开连接时会调用它 //请注意,当上面调用断开连接时, 也会调用它。两个方法都调用相同的操作 //这是为了向后兼容 Debug.Log("断开连接"); isConnected = false; connecting = false; if (_peripheralList != null) { _peripheralList.Clear(); } ScanBluetooth(); }); }
// Update is called once per frame void Update() { _timeout -= Time.deltaTime; if (_timeout <= 0f) { if (_startScan) { _startScan = false; _timeout = _startScanTimeout; BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, null, (address, name, rssi, bytes) => { BluetoothLEHardwareInterface.Log("item scanned: " + address); if (_scannedItems.ContainsKey(address)) { var scannedItem = _scannedItems[address]; scannedItem.TextRSSIValue.text = rssi.ToString(); BluetoothLEHardwareInterface.Log("already in list " + rssi.ToString()); } else { BluetoothLEHardwareInterface.Log("item new: " + address); var newItem = Instantiate(ScannedItemPrefab); if (newItem != null) { BluetoothLEHardwareInterface.Log("item created: " + address); newItem.transform.parent = transform; var scannedItem = newItem.GetComponent <ScannedItemScript> (); if (scannedItem != null) { BluetoothLEHardwareInterface.Log("item set: " + address); scannedItem.TextAddressValue.text = address; scannedItem.TextNameValue.text = name; scannedItem.TextRSSIValue.text = rssi.ToString(); _scannedItems[address] = scannedItem; } } } }, true); } else { BluetoothLEHardwareInterface.StopScan(); _startScan = true; _timeout = _startScanDelay; } } }
/// <summary> /// Stops scanning for new bluetooth devices /// </summary> public bool StopScanForDice() { if (_state != State.Scanning) { Debug.LogError("Die Manager not scanning, so can't stop scanning"); return(false); } Debug.Log("stop scan"); // Stop scanning BluetoothLEHardwareInterface.StopScan(); _state = State.Idle; return(true); }
public void StopScanForDice() { if (_state == CentralState.Scanning) { BluetoothLEHardwareInterface.StopScan(); if (virtualBluetooth != null) { virtualBluetooth.StopScan(); } _state = CentralState.Idle; } else { Debug.LogError("Central is not currently scanning for devices, current state is " + _state); } }
private void StopScan() { scaning = false; if (isCentral) { BluetoothLEHardwareInterface.StopScan(); CommonTool.GuiHorizontalMove(bluetoothScanResultContent, Screen.width, MoveID.RightOrUp, canvasGroup, false); } else { StopAllCoroutines(); BluetoothLEHardwareInterface.StopAdvertising(() => { CommonTool.GuiHorizontalMove(bluetoothScanResultContent, Screen.width, MoveID.RightOrUp, canvasGroup, false); }); } }
//handles the scan button click public void OnScan() { if (_scanning) {//only scan once BluetoothLEHardwareInterface.StopScan(); ScanButton.GetComponentInChildren <Text>().text = "Scan"; _scanning = false; } else { if (_connectedAddress != null) {//disconnect from a connected device if there is any (only meant to connect to one device?) BluetoothLEHardwareInterface.DisconnectPeripheral(_connectedAddress, null); _connectedName = null; _connectedAddress = null; } theCircle.GetComponent <Renderer>().enabled = false; PanelScrollContents.gameObject.SetActive(true);// GetComponent<Renderer>().enabled = true; SendButton.interactable = false; RemovePeripherals(); DeviceServices.text = "scanning..."; // the first callback will only get called the first time this device is seen // this is because it gets added to a list in the BluetoothDeviceScript // after that only the second callback will get called and only if there is // advertising data available BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { AddPeripheral(name, address); }, (address, name, rssi, advertisingInfo) => { if (advertisingInfo != null) { BluetoothLEHardwareInterface.Log(string.Format("Device: {0} RSSI: {1} Data Length: {2} Bytes: {3}", name, rssi, advertisingInfo.Length, BytesToString(advertisingInfo))); } }); ScanButton.GetComponentInChildren <Text>().text = "Stop"; _scanning = true; } }
void BTconnect(string addr) { BluetoothLEHardwareInterface.ConnectToPeripheral(addr, (address) => {; }, (address, serviceUUID) => {; }, (address, serviceUUID, characteristicUUID) => { // discovered characteristic if (IsEqual(serviceUUID, serviceUUID)) { connectedID = address; if (IsEqual(characteristicUUID, rCharacteristicUUID)) { readFound = true; BTLog += "readTrue \n"; } if (IsEqual(characteristicUUID, wCharacteristicUUID)) { writeFound = true; BTLog += "writeTrue \n"; } if (readFound && writeFound) { BTLog += "Connected! \n"; Invoke("readReady", 1f); } else { BTStatus = false; readStart = false; } BluetoothLEHardwareInterface.StopScan(); } }, (address) => { // this will get called when the device disconnects // be aware that this will also get called when the disconnect // is called above. both methods get call for the same action // this is for backwards compatibility }); }
void SetMode(eMode Mode) { DebugLog("BLEMgr:" + Mode.ToString()); m_Mode = Mode; m_ModeTimer = 0; switch (m_Mode) { case eMode.ScanDevice: ExecScanDevice(); break; case eMode.Connect: ExecConnect(); break; case eMode.ConnectOK: if (m_ScanAndConnectSuccess != null) { m_ScanAndConnectSuccess(); } m_ScanAndConnectSuccess = null; m_ScanAndConnectError = null; m_StatusChangedCallback(Hot2gEnumerations.EnumHot2gDriverCommStsEvent.Connected, m_DeviceAddress); break; case eMode.Error: BluetoothLEHardwareInterface.StopScan(); BluetoothLEHardwareInterface.DeInitialize(() => { if (m_ScanAndConnectError != null) { m_ScanAndConnectError(); } }); break; case eMode.DisConnect: BluetoothLEHardwareInterface.DeInitialize(() => { m_StatusChangedCallback(Hot2gEnumerations.EnumHot2gDriverCommStsEvent.Disconnected, m_DeviceAddress); }); break; } }
private void ConnectDevice(string addr) { BluetoothLEHardwareInterface.ConnectToPeripheral(addr, (address) => { }, (address, serviceUUID) => { }, (address, serviceUUID, characteristicUUID) => { if (IsEqual(serviceUUID, _serviceUUID)) { _connectedID = address; isConnected = true; if (IsEqual(characteristicUUID, _readCharacteristicUUID)) { _readFound = true; } if (IsEqual(characteristicUUID, _writeCharacteristicUUID)) { _writeFound = true; } adressFinal = addr; Debug.Log("BLE Spiro Connected"); BluetoothLEHardwareInterface.StopScan(); } }, (address) => { // this will get called when the device disconnects // be aware that this will also get called when the disconnect // is called above. both methods get call for the same action // this is for backwards compatibility Debug.Log("Connection Lost"); isConnected = false; //we first need to disconnect and deinitialize before we can connect again to the Air next otherwise we can't reconnect. BluetoothLEHardwareInterface.DisconnectAll(); BluetoothLEHardwareInterface.DeInitialize(() => { }); BluetoothLEHardwareInterface.FinishDeInitialize(); DeviceManager.Instance.MakeSpiroControllerNull(); }); }
private void OnDestroy() { Debug.Log("BluetoothManager - OnDestroy()"); if (Instance == this) { try { BluetoothLEHardwareInterface.StopScan(); BluetoothLEHardwareInterface.DisconnectAll(); BluetoothLEHardwareInterface.DeInitialize(() => { Debug.Log("Bluetooth has shut down on destroy."); }); } catch (Exception e) { Debug.Log("Bluetooth has already shut down: " + e.Message); } } }
public void scan() { if (_scanning == true) { BluetoothLEHardwareInterface.StopScan(); _scanning = false; } else { BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { if (name.Contains(DeviceName)) { _deviceAddress = address; connectTo(_deviceAddress); } }, (address, name, rssi, advertisingInfo) => { }); _scanning = true; } }
private void Update() { switch (m_Mode) { case eMode.ScanDevice: m_ModeTimer += Time.deltaTime; if (cScanTime <= m_ModeTimer) { if (m_ScanDeviceList.Count <= 0) { SetMode(eMode.Error); if (m_ScanAndConnectError != null) { m_ScanAndConnectError(); } } else { BluetoothLEHardwareInterface.StopScan(); SetMode(eMode.ScanOK); if (m_ScanAndConnectSuccess != null) { m_ScanAndConnectSuccess(); } } } break; case eMode.Connect: m_ModeTimer += Time.deltaTime; if (cTimeOut <= m_ModeTimer) { SetMode(eMode.Error); } break; } }
void connectBluetooth(string addr, string name) { Debug.Log("Connection to ..." + name + "with address: " + addr + ", in progress... \n"); connecting = true; BluetoothLEHardwareInterface.ConnectToPeripheral(addr, (address) => { }, (address, serviceUUID) => { }, (address, serviceUUID, characteristicUUID) => { // discovered characteristic if (IsEqual(serviceUUID, _serviceUUID)) { _connectedID = address; isConnected = true; if (IsEqual(characteristicUUID, RX_UUID)) { Debug.Log("Read Characteristic"); _readFound = true; } if (IsEqual(characteristicUUID, TX_UUID)) { Debug.Log("Write Characteristic"); _writeFound = true; } Debug.Log("Connected"); BluetoothLEHardwareInterface.StopScan(); } }, (address) => { // this will get called when the device disconnects // be aware that this will also get called when the disconnect // is called above. both methods get call for the same action // this is for backwards compatibility isConnected = false; connecting = false; }); }
/** * Scans for peripherals, stopping once the target peripheral is found */ private void ScanForPeripherals() { logger.DebugLog("Scanning for peripherals..."); string[] serviceUUIDs = new string[1]; serviceUUIDs[0] = _peripheralParams.Value.serviceUUID; BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(serviceUUIDs, (address, name) => { // if your device does not advertise the rssi and manufacturer specific data // then you must use this callback because the next callback only gets called // if you have manufacturer specific data logger.DebugLog("Found peripheral: address=[" + address + "], name=[" + name + "])"); if (name.ToLower().Contains(_peripheralParams.Value.deviceName.ToLower())) { logger.DebugLog("Peripheral matches target device name"); BluetoothLEHardwareInterface.StopScan(); // found a device with the name we want _deviceAddress = address; SetState(States.Connect, 0.5f); } }, (address, name, rssi, bytes) => { // use this one if the device responses with manufacturer specific data and the rssi logger.DebugLog("Found peripheral: address=[" + address + "], name=[" + name + "]) rssi=[" + rssi + "], bytes=[" + bytes + "]"); if (name.ToLower().Contains(_peripheralParams.Value.deviceName.ToLower())) { logger.DebugLog("Peripheral matches target device name"); BluetoothLEHardwareInterface.StopScan(); // found a device with the name we want _deviceAddress = address; SetState(States.Connect, .5f); } }, /*rssi=*/ false); // this last setting allows RFduino to send RSSI without having manufacturer data }
void connectBluetooth(string addr) { BluetoothLEHardwareInterface.ConnectToPeripheral(addr, (address) => { }, (address, serviceUUID) => { }, (address, serviceUUID, characteristicUUID) => { // discovered characteristic if (IsEqual(serviceUUID, _serviceUUID)) { _connectedID = address; isConnected = true; if (IsEqual(characteristicUUID, _readCharacteristicUUID)) { _readFound = true; } if (IsEqual(characteristicUUID, _writeCharacteristicUUID)) { _writeFound = true; } StateChange(States.Connect); BluetoothLEHardwareInterface.Log("Connected. Stop scanning" + address); BluetoothLEHardwareInterface.StopScan(); connectWait?.Invoke(); } }, (address) => { // this will get called when the device disconnects // be aware that this will also get called when the disconnect // is called above. both methods get call for the same action // this is for backwards compatibility isConnected = false; }); }
void connectBluetooth(string addr) { BluetoothLEHardwareInterface.ConnectToPeripheral(addr, (address) => { }, (address, serviceUUID) => { }, (address, serviceUUID, characteristicUUID) => { // discovered characteristic if (IsEqual(serviceUUID, _serviceUUID)) { _connectedID = address; isConnected = true; if (IsEqual(characteristicUUID, _readCharacteristicUUID)) { _readFound = true; txtDebug.text += "readtrue"; } if (IsEqual(characteristicUUID, _writeCharacteristicUUID)) { _writeFound = true; txtDebug.text += "writetrue"; } txtDebug.text += "Connected"; BluetoothLEHardwareInterface.StopScan(); // uiPanel.SetActive(true); } }, (address) => { // this will get called when the device disconnects // be aware that this will also get called when the disconnect // is called above. both methods get call for the same action // this is for backwards compatibility isConnected = false; }); }
// Update is called once per frame void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { _timeout = 0f; switch (_state) { case States.None: break; case States.Scan: BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { if (name == "SmartInsoleL") { device_left.Name = name; device_left.Address = address; device_left.State = DEVICE_STATE.FOUND; } else if (name == "SmartInsoleR") { device_right.Name = name; device_right.Address = address; device_right.State = DEVICE_STATE.FOUND; } if (device_right.State == DEVICE_STATE.FOUND && device_left.State == DEVICE_STATE.FOUND) { BluetoothLEHardwareInterface.StopScan(); SetState(States.Connect, 0.5f); } }, null); break; case States.Connect: BluetoothLEHardwareInterface.ConnectToPeripheral(device_left.Address, null, null, (address, serviceUUID, characteristicUUID) => { if (IsEqual(serviceUUID, ServiceUUID)) { device_left.FoundSubscribeID = device_left.FoundSubscribeID || IsEqual(characteristicUUID, SubscribeCharacteristic); device_left.FoundWriteID = device_left.FoundWriteID || IsEqual(characteristicUUID, WriteCharacteristic); // if we have found both characteristics that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe if (device_left.FoundSubscribeID && device_left.FoundWriteID) { device_left.State = DEVICE_STATE.CONNECTED; SetState(States.Subscribe, 0.5f); } } }); BluetoothLEHardwareInterface.ConnectToPeripheral(device_right.Address, null, null, (address, serviceUUID, characteristicUUID) => { if (IsEqual(serviceUUID, ServiceUUID)) { device_right.FoundSubscribeID = device_right.FoundSubscribeID || IsEqual(characteristicUUID, SubscribeCharacteristic); device_right.FoundWriteID = device_right.FoundWriteID || IsEqual(characteristicUUID, WriteCharacteristic); // if we have found both characteristics that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe if (device_right.FoundSubscribeID && device_right.FoundWriteID) { device_right.State = DEVICE_STATE.CONNECTED; SetState(States.Subscribe, 0.5f); } } }); break; case States.Subscribe: BluetoothLEHardwareInterface.SubscribeCharacteristic(device_left.Address, FullUUID(ServiceUUID), FullUUID(SubscribeCharacteristic), null, (characteristic, bytes) => { //string s = ASCIIEncoding.UTF8.GetString(bytes); //left_foot_data.text = s; device_left.DataBytes = ASCIIEncoding.UTF8.GetString(bytes); device_left.State = DEVICE_STATE.SUBSCRIBED; device_left.NewData = true; SetState(States.None, 2f); }); BluetoothLEHardwareInterface.SubscribeCharacteristic(device_right.Address, FullUUID(ServiceUUID), FullUUID(SubscribeCharacteristic), null, (characteristic, bytes) => { //string s = ASCIIEncoding.UTF8.GetString(bytes); //right_foot_data.text = s; device_right.DataBytes = ASCIIEncoding.UTF8.GetString(bytes); device_right.State = DEVICE_STATE.SUBSCRIBED; device_right.NewData = true; SetState(States.None, 2f); }); _connected = true; break; case States.Unsubscribe: BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null); SetState(States.Disconnect, 4f); break; case States.Disconnect: if (_connected) { BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => { BluetoothLEHardwareInterface.DeInitialize(() => { _connected = false; _state = States.None; }); }); } else { BluetoothLEHardwareInterface.DeInitialize(() => { _state = States.None; }); } break; } } } }
/// <summary> /// Update /// </summary> void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout > 0f) { return; } _timeout = 0f; switch (_state) { //None case States.None: break; //Scan case States.Scan: BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { // if your device does not advertise the rssi and manufacturer specific data // then you must use this callback because the next callback only gets called // if you have manufacturer specific data // デバイスがrssiおよびメーカー固有のデータをアドバタイズしない場合、次のコールバックはメーカー固有のデータがある場合にのみ呼び出されるため、このコールバックを使用する必要があります。 _deviceName += string.Format(",{0} ", name); if (!_rssiOnly) { if (name.Contains(DeviceName)) { _deviceName += string.Format("[FIND]-{0}\n", _deviceAddress); BluetoothLEHardwareInterface.StopScan(); // found a device with the name we want // this example does not deal with finding more than one _deviceAddress = address; SetState(States.Connect, 0.5f); } else { _deviceName += "\n"; } } if (LogText != null) { LogText.text = _deviceName; } }, (address, name, rssi, bytes) => { // use this one if the device responses with manufacturer specific data and the rssi // デバイスがメーカー固有のデータとrssiで応答する場合、これを使用します if (name.Contains(DeviceName)) { if (_rssiOnly) { _rssi = rssi; } else { BluetoothLEHardwareInterface.StopScan(); // found a device with the name we want // this example does not deal with finding more than one _deviceAddress = address; SetState(States.Connect, 0.5f); } } }, _rssiOnly); // this last setting allows RFduino to send RSSI without having manufacturer data if (_rssiOnly) { SetState(States.ScanRSSI, 0.5f); } break; //ScanRSSI case States.ScanRSSI: break; //Connect case States.Connect: // set these flags _foundSubscribeID = false; _foundWriteID = false; // note that the first parameter is the address, not the name. I have not fixed this because // of backwards compatiblity. // also note that I am note using the first 2 callbacks. If you are not looking for specific characteristics you can use one of // the first 2, but keep in mind that the device will enumerate everything and so you will want to have a timeout // large enough that it will be finished enumerating before you try to subscribe or do any other operations. // 最初のパラメータは名前ではなくアドレスであることに注意してください。後方互換性のため、これは修正していません。 // また、最初の2つのコールバックを使用していることに注意してください。特定の特性を探していない場合は、最初の2つのいずれかを使用できますが、 // デバイスはすべてを列挙するので、サブスクライブする前に列挙が完了するまでタイムアウトを大きくする必要があることに注意してください。他の操作を行います。 BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, null, null, (address, serviceUUID, characteristicUUID) => { _serviceName += string.Format("{0} ", serviceUUID); if (IsEqual(serviceUUID, ServiceUUID)) { _serviceName += string.Format("[FIND]-{0}\n", _deviceAddress); _foundSubscribeID = _foundSubscribeID || IsEqual(characteristicUUID, SubscribeCharacteristic); _foundWriteID = _foundWriteID || IsEqual(characteristicUUID, WriteCharacteristic); _serviceName += string.Format("<{0}>,{1},{2}\n", characteristicUUID, _foundSubscribeID, _foundWriteID); // if we have found both characteristics that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe //if (_foundSubscribeID && _foundWriteID) if (_foundSubscribeID) { _connected = true; SetState(States.Subscribe, 2f); } } else { _serviceName += "\n"; } if (Log2Text != null) { Log2Text.text = _serviceName; } }); break; // Subscribe case States.Subscribe: BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null, (address, characteristicUUID, bytes) => { // we don't have a great way to set the state other than waiting until we actually got // some data back. For this demo with the rfduino that means pressing the button // on the rfduino at least once before the GUI will update. // 実際にデータが返されるまで待つ以外に、状態を設定する優れた方法はありません。このrfduinoのデモでは、GUIが更新される前にrfduinoのボタンを少なくとも1回押すことを意味します。 _state = States.None; // we received some data from the device _dataBytes = bytes; }); break; // Unsubscribe case States.Unsubscribe: BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null); SetState(States.Disconnect, 4f); break; // Disconnect case States.Disconnect: if (_connected) { BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => { BluetoothLEHardwareInterface.DeInitialize(() => { _connected = false; _state = States.None; }); }); } else { BluetoothLEHardwareInterface.DeInitialize(() => { _state = States.None; }); } break; } } }
// public GUISkin skin; // // void OnGUI(){ // GUI.skin = skin; // GUIStyle myButtonStyle = new GUIStyle(GUI.skin.button); // myButtonStyle.fontSize = 20; // GUI.Button (new Rect (10, 0, 300, 100), string.Format ("sta:{0} id:{1}", State, deviceAddress), myButtonStyle); // GUI.Button (new Rect (10, 0, 300, 200), string.Format ("xor:{0}", BitConverter.ToString(addressXor)), myButtonStyle); // GUI.Button (new Rect (10, 0, 300, 300), string.Format ("data:{0}", lastData.ToString()), myButtonStyle); // GUI.Button (new Rect (10, 0, 300, 400), string.Format ("timeout:{0}", timeout), myButtonStyle); // } // Update is called once per frame void Update() { if (state != States.Subscribe) { if (restarttime <= Time.realtimeSinceStartup) { Disconnect(deviceAddress); } } if (timeout != 0 && timeout <= Time.realtimeSinceStartup) { timeout = 0; switch (state) { case States.None: break; case States.Init: StartProcess(); break; case States.Scan: Time.timeScale = 0; Alert.Show("Can't fine the ArGun, Scaning...", null, false); // TODO 这里暂停事件 BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(new string[] { BluetoothLEHardwareInterface.FullUUID(broadcastUUID) }, (_address, _name) => { if (!illegalDevices.Contains(_address)) { BluetoothLEHardwareInterface.StopScan(); deviceAddress = _address; Alert.Show("Connectting the ar gun : " + _name, null, false); SetState(States.Connect, 0.2f); } }); break; case States.Connect: BluetoothLEHardwareInterface.ConnectToPeripheral(deviceAddress, null, null, (_address, _serviceUUID, _characteristicUUID) => { if (IsEqual(serviceUUID, _serviceUUID) && IsEqual(characteristicUUID, _characteristicUUID)) { #if UNITY_ANDROID string[] addressArr = _address.Split(':'); for (int i = 0; i < addressArr.Length; i++) { addressXor [i] = (byte)(Convert.ToByte(addressArr [i], 16) ^ saveTable [i]); } #endif Alert.Show("connect success!", (_value) => { SetState(States.Subscribe, 1f); }); } }, (_address) => { SetState(States.Scan, 0.5f); }); break; case States.Subscribe: // TODO 这里恢复事件 Time.timeScale = 1f; BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(deviceAddress, serviceUUID, characteristicUUID, null, (_address, _characteristicUUID, _bytes) => { if (_bytes.Length == addressXor.Length + 1) { #if UNITY_ANDROID for (int i = 0; i < addressXor.Length; i++) { if (!_bytes [i].Equals(addressXor [i])) { Disconnect(_address); return; } } #endif ReadData(_bytes [addressXor.Length]); } else { Disconnect(_address); } }); break; } } }
// Update is called once per frame void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { _timeout = 0f; switch (_state) { case States.None: break; case States.Scan: StatusMessage = "Scanning for " + DeviceName; BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { // if your device does not advertise the rssi and manufacturer specific data // then you must use this callback because the next callback only gets called // if you have manufacturer specific data if (!_rssiOnly) { if (name.Contains(DeviceName)) { StatusMessage = "Found " + name; BluetoothLEHardwareInterface.StopScan(); // found a device with the name we want // this example does not deal with finding more than one _deviceAddress = address; SetState(States.Connect, 0.5f); } } }, (address, name, rssi, bytes) => { // use this one if the device responses with manufacturer specific data and the rssi if (name.Contains(DeviceName)) { StatusMessage = "Found " + name; if (_rssiOnly) { _rssi = rssi; } else { BluetoothLEHardwareInterface.StopScan(); // found a device with the name we want // this example does not deal with finding more than one _deviceAddress = address; SetState(States.Connect, 0.5f); } } }, _rssiOnly); // this last setting allows RFduino to send RSSI without having manufacturer data if (_rssiOnly) { SetState(States.ScanRSSI, 0.5f); } break; case States.ScanRSSI: break; case States.Connect: StatusMessage = "Connecting..."; // set these flags _foundButtonUUID = false; _foundLedUUID = false; // note that the first parameter is the address, not the name. I have not fixed this because // of backwards compatiblity. // also note that I am note using the first 2 callbacks. If you are not looking for specific characteristics you can use one of // the first 2, but keep in mind that the device will enumerate everything and so you will want to have a timeout // large enough that it will be finished enumerating before you try to subscribe or do any other operations. BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, null, null, (address, serviceUUID, characteristicUUID) => { StatusMessage = "Connected..."; if (IsEqual(serviceUUID, ServiceUUID)) { StatusMessage = "Found Service UUID"; _foundButtonUUID = _foundButtonUUID || IsEqual(characteristicUUID, ButtonUUID); _foundLedUUID = _foundLedUUID || IsEqual(characteristicUUID, LedUUID); // if we have found both characteristics that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe if (_foundButtonUUID && _foundLedUUID) { _connected = true; SetState(States.Subscribe, 2f); } } }); break; case States.Subscribe: StatusMessage = "Subscribing to characteristics..."; BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, ButtonUUID, (notifyAddress, notifyCharacteristic) => { StatusMessage = "Waiting for user action (1)..."; _state = States.None; // read the initial state of the button BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddress, ServiceUUID, ButtonUUID, (characteristic, bytes) => { ProcessButton(bytes); }); }, (address, characteristicUUID, bytes) => { if (_state != States.None) { // some devices do not properly send the notification state change which calls // the lambda just above this one so in those cases we don't have a great way to // set the state other than waiting until we actually got some data back. // The esp32 sends the notification above, but if yuor device doesn't you would have // to send data like pressing the button on the esp32 as the sketch for this demo // would then send data to trigger this. StatusMessage = "Waiting for user action (2)..."; _state = States.None; } // we received some data from the device ProcessButton(bytes); }); break; case States.Unsubscribe: BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, ButtonUUID, null); SetState(States.Disconnect, 4f); break; case States.Disconnect: StatusMessage = "Commanded disconnect."; if (_connected) { BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => { StatusMessage = "Device disconnected"; BluetoothLEHardwareInterface.DeInitialize(() => { _connected = false; _state = States.None; }); }); } else { BluetoothLEHardwareInterface.DeInitialize(() => { _state = States.None; }); } break; } } } }
// Update is called once per frame void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { _timeout = 0f; switch (_state) { case States.None: break; case States.Scan: BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, deviceName) => { if (deviceName.Contains(DeviceName)) { StatusMessage = "Found a MetaMotion"; BluetoothLEHardwareInterface.StopScan(); TopPanel.SetActive(true); // found a device with the name we want // this example does not deal with finding more than one _deviceAddress = address; SetState(States.Connect, 0.5f); } }, null, true); break; case States.Connect: StatusMessage = "Connecting to MetaMotion..."; BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, null, null, (address, serviceUUID, characteristicUUID) => { var characteristic = GetCharacteristic(serviceUUID, characteristicUUID); if (characteristic != null) { BluetoothLEHardwareInterface.Log(string.Format("Found {0}, {1}", serviceUUID, characteristicUUID)); characteristic.Found = true; if (AllCharacteristicsFound) { _connected = true; SetState(States.ConfigureAccelerometer, 0.1f); } } }, (disconnectAddress) => { StatusMessage = "Disconnected from MetaMotion"; Reset(); SetState(States.Scan, 1f); }); break; case States.ConfigureAccelerometer: StatusMessage = "Configuring Accelerometer..."; BluetoothLEHardwareInterface.WriteCharacteristic(_deviceAddress, ReadWriteCharacteristic.ServiceUUID, ReadWriteCharacteristic.CharacteristicUUID, CommandAccelerometerConfigure, CommandAccelerometerConfigure.Length, true, (____) => { StatusMessage = "Enable data output"; BluetoothLEHardwareInterface.WriteCharacteristic(_deviceAddress, ReadWriteCharacteristic.ServiceUUID, ReadWriteCharacteristic.CharacteristicUUID, CommandAccelerometerEnableDataInterrupt, CommandAccelerometerEnableDataInterrupt.Length, true, (_____) => { StatusMessage = "Enable data interrupt"; BluetoothLEHardwareInterface.WriteCharacteristic(_deviceAddress, ReadWriteCharacteristic.ServiceUUID, ReadWriteCharacteristic.CharacteristicUUID, CommandAccelerometerEnableDataOutput, CommandAccelerometerEnableDataOutput.Length, true, (______) => { StatusMessage = "Enable power"; BluetoothLEHardwareInterface.WriteCharacteristic(_deviceAddress, ReadWriteCharacteristic.ServiceUUID, ReadWriteCharacteristic.CharacteristicUUID, CommandAccelerometerEnablePower, CommandAccelerometerEnablePower.Length, true, (_______) => { StatusMessage = "Accelerometer configured"; SetState(States.SubscribeToAccelerometer, 0.1f); }); }); }); }); /* * StatusMessage = "Configuring Gyro..."; * BluetoothLEHardwareInterface.WriteCharacteristic (_deviceAddress, ReadWriteCharacteristic.ServiceUUID, ReadWriteCharacteristic.CharacteristicUUID, CommandGyroConfigure, CommandGyroConfigure.Length, true, (_) => { * StatusMessage = "Enable data output"; * BluetoothLEHardwareInterface.WriteCharacteristic (_deviceAddress, ReadWriteCharacteristic.ServiceUUID, ReadWriteCharacteristic.CharacteristicUUID, CommandGyroEnableDataOutput, CommandGyroEnableDataOutput.Length, true, (__) => { * StatusMessage = "Enable data interrupt"; * BluetoothLEHardwareInterface.WriteCharacteristic (_deviceAddress, ReadWriteCharacteristic.ServiceUUID, ReadWriteCharacteristic.CharacteristicUUID, CommandGyroEnableDataInterrupt, CommandGyroEnableDataInterrupt.Length, true, (___) => { * StatusMessage = "Enable power"; * BluetoothLEHardwareInterface.WriteCharacteristic (_deviceAddress, ReadWriteCharacteristic.ServiceUUID, ReadWriteCharacteristic.CharacteristicUUID, CommandGyroEnablePower, CommandGyroEnablePower.Length, true, (____) => { * StatusMessage = "Accelerometer configured"; * SetState (States.SubscribeToAccelerometer, 0.1f); * }); * }); * }); * }); */ break; case States.SubscribeToAccelerometer: SetState(States.SubscribingToAccelerometer, 5f); StatusMessage = "Subscribing to MetaMotion Accelerometer..."; BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, SubscribeCharacteristic.ServiceUUID, SubscribeCharacteristic.CharacteristicUUID, null, (deviceAddress, characteristric, bytes) => { _state = States.None; MiddlePanel.SetActive(true); var vector = AccelerometerBmi160.GetVector3(bytes); AccelerometerText.text = string.Format("Accelerometer: x:{0}, y:{1}, z:{2}", vector.x, vector.y, vector.z); }); break; case States.SubscribingToAccelerometer: // if we got here it means we timed out subscribing to the accelerometer SetState(States.Disconnect, 0.5f); break; case States.Disconnect: SetState(States.Disconnecting, 5f); if (_connected) { BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => { // since we have a callback for disconnect in the connect method above, we don't // need to process the callback here. }); } else { Reset(); SetState(States.Scan, 1f); } break; case States.Disconnecting: // if we got here we timed out disconnecting, so just go to disconnected state Reset(); SetState(States.Scan, 1f); break; } } } }
public void OnStopScanning() { BluetoothLEHardwareInterface.Log("**************** stopping"); BluetoothLEHardwareInterface.StopScan(); }
void TaskOnClick() { // Stop device Scan BluetoothLEHardwareInterface.StopScan(); connectToDevice.OnConnect(address); }
void Update() { RotatePlayer(); if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { _timeout = 0f; switch (_state) { case States.None: break; case States.Scan: HM10_Status.text = "Scanning for HM10 devices..."; BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { if (name.Contains(DeviceName)) { _workingFoundDevice = true; BluetoothLEHardwareInterface.StopScan(); // stop scanning while you connect to a device _hm10 = address; // add it to the list and set to connect to it HM10_Status.text = "Found HM10"; SetState(States.Connect, 0.5f); _workingFoundDevice = false; } }, null, false, false); break; case States.Connect: HM10_Status.text = "Connecting to HM10"; BluetoothLEHardwareInterface.ConnectToPeripheral(_hm10, null, null, (address, serviceUUID, characteristicUUID) => { if (IsEqual(serviceUUID, ServiceUUID)) { if (IsEqual(characteristicUUID, Characteristic)) { _connected = true; SetState(States.Subscribe, 2f); } } }, (disconnectedAddress) => { BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress); HM10_Status.text = "Disconnected"; }); break; case States.Subscribe: HM10_Status.text = "Connected to HM10"; enabled = true; BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_hm10, ServiceUUID, Characteristic, null, (address, characteristicUUID, bytes) => {}); _state = States.None; // set to the none state and the user can start sending and receiving data break; case States.Unsubscribe: BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_hm10, ServiceUUID, Characteristic, null); SetState(States.Disconnect, 4f); break; case States.Disconnect: if (_connected) { BluetoothLEHardwareInterface.DisconnectPeripheral(_hm10, (address) => { BluetoothLEHardwareInterface.DeInitialize(() => { _connected = false; _state = States.None; }); }); } else { BluetoothLEHardwareInterface.DeInitialize(() => { _state = States.None; }); enabled = false; } break; } } } }
// Update is called once per frame void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { _timeout = 0f; switch (_state) { case States.None: break; case States.Scan: BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { // if your device does not advertise the rssi and manufacturer specific data // then you must use this callback because the next callback only gets called // if you have manufacturer specific data if (name.Contains(DeviceName)) { BluetoothLEHardwareInterface.StopScan(); // found a device with the name we want // this example does not deal with finding more than one _deviceAddress = address; SetState(States.Connect, 0.5f); } }, (address, name, rssi, bytes) => { // use this one if the device responses with manufacturer specific data and the rssi }); break; case States.Connect: // set these flags _foundSubscribeID = false; _foundWriteID = false; // note that the first parameter is the address, not the name. I have not fixed this because // of backwards compatiblity. // also note that I am note using the first 2 callbacks. If you are not looking for specific characteristics you can use one of // the first 2, but keep in mind that the device will enumerate everything and so you will want to have a timeout // large enough that it will be finished enumerating before you try to subscribe or do any other operations. BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, null, null, (address, serviceUUID, characteristicUUID) => { if (IsEqual(serviceUUID, ServiceUUID)) { _foundSubscribeID = _foundSubscribeID || IsEqual(characteristicUUID, SubscribeCharacteristic); _foundWriteID = _foundWriteID || IsEqual(characteristicUUID, WriteCharacteristic); // if we have found both characteristics that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe if (_foundSubscribeID && _foundWriteID) { _connected = true; SetState(States.Subscribe, 2f); } } }); break; case States.Subscribe: BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null, (address, characteristicUUID, bytes) => { // we don't have a great way to set the state other than waiting until we actually got // some data back. For this demo with the rfduino that means pressing the button // on the rfduino at least once before the GUI will update. _state = States.None; // we received some data from the device _dataBytes = bytes; }); break; case States.Unsubscribe: BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null); SetState(States.Disconnect, 4f); break; case States.Disconnect: BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => { BluetoothLEHardwareInterface.Log("1"); BluetoothLEHardwareInterface.DeInitialize(() => { _connected = false; _state = States.None; }); }); break; } } } }
void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { UpdateGUI(); switch (_state) { case States.Disconnected: { Log("Disconnected"); break; } case States.Scanning: { Log("Scanning"); string[] UUIDs = { ServiceUUID }; BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(UUIDs, (address, name) => { if (address.Equals(DeviceAddress)) { BluetoothLEHardwareInterface.StopScan(); SetState(States.Connecting, 0.5f); } }); break; } case States.Connecting: { Log("Connecting"); BluetoothLEHardwareInterface.ConnectToPeripheral(DeviceAddress, null, null, (address, service, characteristicUUID) => { foreach (var c in _characteristics) { if (c.UUID.Equals(characteristicUUID)) { c.Discovered = true; } } if (_characteristics.All(c => c.Discovered)) { SetState(States.Subscribing, 0.5f); } }); break; } case States.Subscribing: { Log("Subscribing"); try { var c = _characteristics.First(ch => !ch.Subscribed); BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(DeviceAddress, ServiceUUID, c.UUID, null, (address, charUUID, bytes) => { c.UpdateValue(bytes); if (!c.Subscribed) { c.Subscribed = true; SetState(States.Subscribing, 0.5f); } }); } catch (InvalidOperationException) { // Subscribed to every characteristic SetState(States.Subscribed, 0.1f); } break; } case States.Subscribed: { Log("Subscribed"); break; } default: break; } } } }
//This function stops scanning for sensors public void ToStopScanning() { BluetoothLEHardwareInterface.StopScan(); Sup.text = "Not scanning"; }
void Bluetooth_Baglan() { if (Bluetooth_Bilgileri.State_Timeout > 0f) { Bluetooth_Bilgileri.State_Timeout -= Time.deltaTime; if (Bluetooth_Bilgileri.State_Timeout <= 0f) { Bluetooth_Bilgileri.State_Timeout = 0f; switch (Bluetooth_Bilgileri.State) { case Bluetooth_States.None: break; case Bluetooth_States.Scan: Status_Update(Bluetooth_DeviceName + " aranıyor..."); BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => { // we only want to look at devices that have the name we are looking for // this is the best way to filter out devices if (name.Contains(Bluetooth_DeviceName)) { // it is always a good idea to stop scanning while you connect to a device // and get things set up BluetoothLEHardwareInterface.StopScan(); Status_Update(Bluetooth_DeviceName + " bulundu..."); // add it to the list and set to connect to it Bluetooth_Bilgileri.Device_Address = address; SetState(Bluetooth_States.Connect, 0.5f); } }, null, false, false); break; case Bluetooth_States.Connect: // set these flags Status_Update(Bluetooth_DeviceName + " cihazına bağlanılıyor..."); // note that the first parameter is the address, not the name. I have not fixed this because // of backwards compatiblity. // also note that I am note using the first 2 callbacks. If you are not looking for specific characteristics you can use one of // the first 2, but keep in mind that the device will enumerate everything and so you will want to have a timeout // large enough that it will be finished enumerating before you try to subscribe or do any other operations. BluetoothLEHardwareInterface.ConnectToPeripheral(Bluetooth_Bilgileri.Device_Address, null, null, (address, serviceUUID, characteristicUUID) => { if (UUIDIsEqual(serviceUUID, Bluetooth_ServiceUUID)) { // if we have found the characteristic that we are waiting for // set the state. make sure there is enough timeout that if the // device is still enumerating other characteristics it finishes // before we try to subscribe if (UUIDIsEqual(characteristicUUID, Bluetooth_Characteristic)) { Bluetooth_Bilgileri.Connected = true; SetState(Bluetooth_States.Subscribe, 2f); Status_Update(Bluetooth_DeviceName + " cihazına bağlanıldı."); } } }, (disconnectedAddress) => { BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress); Status_Update(Bluetooth_DeviceName + " cihazı ile bağlantı kesildi!"); }); break; case Bluetooth_States.Subscribe: Status_Update("Veri alımına kaydolunuyor..."); BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(Bluetooth_Bilgileri.Device_Address, Bluetooth_ServiceUUID, Bluetooth_Characteristic, null, (address, characteristicUUID, bytes) => { Bluetooth_Bilgileri.Receive_Count++; BluetoothLEHardwareInterface.Log("Alinan: " + Encoding.UTF8.GetString(bytes)); Status_Update("Alınan veri: " + Encoding.UTF8.GetString(bytes)); Bluetooth_Verilerini_Isle(bytes); }); // set to the none state and the user can start sending and receiving data SetState(Bluetooth_States.None, 0); Status_Update("Veri bekleniyor..."); break; case Bluetooth_States.Unsubscribe: BluetoothLEHardwareInterface.UnSubscribeCharacteristic(Bluetooth_Bilgileri.Device_Address, Bluetooth_ServiceUUID, Bluetooth_Characteristic, null); SetState(Bluetooth_States.Disconnect, 4f); break; case Bluetooth_States.Disconnect: if (Bluetooth_Bilgileri.Connected) { BluetoothLEHardwareInterface.DisconnectPeripheral(Bluetooth_Bilgileri.Device_Address, (address) => { BluetoothLEHardwareInterface.DeInitialize(() => { Bluetooth_Bilgileri.Connected = false; SetState(Bluetooth_States.None, 0); }); }); } else { BluetoothLEHardwareInterface.DeInitialize(() => { SetState(Bluetooth_States.None, 0); }); } break; } } } }
// Update is called once per frame void Update() { if (_timeout > 0f) { _timeout -= Time.deltaTime; if (_timeout <= 0f) { if (_startScan) { _startScan = false; _timeout = _startScanTimeout; // scanning for iBeacon devices requires that you know the Proximity UUID and provide an Identifier BluetoothLEHardwareInterface.ScanForBeacons(new string[] { "01020304-0506-0708-0910-111213141516:Pit01" }, (iBeaconData) => { if (!_iBeaconItems.ContainsKey(iBeaconData.UUID)) { BluetoothLEHardwareInterface.Log("item new: " + iBeaconData.UUID); var newItem = Instantiate(iBeaconItemPrefab); if (newItem != null) { BluetoothLEHardwareInterface.Log("item created: " + iBeaconData.UUID); newItem.transform.SetParent(transform); newItem.transform.localScale = new Vector3(1f, 1f, 1f); var iBeaconItem = newItem.GetComponent <iBeaconItemScript> (); if (iBeaconItem != null) { _iBeaconItems[iBeaconData.UUID] = iBeaconItem; } } } if (_iBeaconItems.ContainsKey(iBeaconData.UUID)) { var iBeaconItem = _iBeaconItems[iBeaconData.UUID]; iBeaconItem.TextUUID.text = iBeaconData.UUID; iBeaconItem.TextRSSIValue.text = iBeaconData.RSSI.ToString(); // Android returns the signal power or measured power, iOS hides this and there is no way to get it iBeaconItem.TextAndroidSignalPower.text = iBeaconData.AndroidSignalPower.ToString(); // iOS returns an enum of unknown, far, near, immediate, Android does not return this iBeaconItem.TextiOSProximity.text = iBeaconData.iOSProximity.ToString(); // we can only calculate a distance if we have the signal power which iOS does not provide if (iBeaconData.AndroidSignalPower != 0) { iBeaconItem.TextDistance.text = Distance(iBeaconData.AndroidSignalPower, iBeaconData.RSSI, 2.5f).ToString(); } } }); } else { BluetoothLEHardwareInterface.StopScan(); _startScan = true; _timeout = _startScanDelay; } } } }
private void CancelScanning() { BluetoothLEHardwareInterface.StopScan(); SetState(States.Disconnected, 0.1f); }