コード例 #1
0
 private void DisconnectFromDevice()
 {
     BluetoothLEHardwareInterface.DisconnectPeripheral(DeviceAddress, (address) =>
     {
         SetState(States.Disconnected, 0.1f);
     });
 }
コード例 #2
0
 public void DisconnectPeripheral(
     string name,
     Action <string> action
     )
 {
     BluetoothLEHardwareInterface.DisconnectPeripheral(name, action);
 }
コード例 #3
0
 private void ResetState(Action afterResetAction)
 {
     if (_peripheralParams.HasValue)
     {
         if (_connected)
         {
             logger.DebugLog("Disconnecting from peripheral with device address: " + _deviceAddress);
             BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
                 logger.DebugLog("De-initializing bluetooth hardware interface");
                 BluetoothLEHardwareInterface.DeInitialize(() => {
                     ResetStateVars();
                     afterResetAction();
                 });
             });
         }
         else
         {
             logger.DebugLog("De-initializing bluetooth hardware interface");
             BluetoothLEHardwareInterface.DeInitialize(() => {
                 ResetStateVars();
                 afterResetAction();
             });
         }
     }
     else
     {
         ResetStateVars();
         afterResetAction();
     }
 }
コード例 #4
0
ファイル: Central.cs プロジェクト: ManicDesigns/Dice4
    void CheckDieCharacteristics(Die die)
    {
        // Check that the die has the read and write characteristics
        if (die.deviceConnected &&
            die.messageReadCharacteristicFound &&
            die.messageWriteCharacteristicFound)
        {
            die.state = Die.State.Connected;

            // Subscribe, but only subscribe to one characteristic at a time
            StartNextSubscribeToCharacteristic();
        }
        else
        {
            // Check timeout!
            if (Time.time - die.startTime > DiscoverCharacteristicsTimeout)
            {
                // Wrong characteristics, we can't talk to this die!
                Debug.LogError("Timeout looking for characteristics on Die " + die.die.name);

                // Temporarily add the die to the connected list to avoid an error message during the disconnect
                die.state = Die.State.Disconnecting;

                // And force a disconnect
                BluetoothLEHardwareInterface.DisconnectPeripheral(die.die.address, null);
            }
            // Else just keep waiting
        }
    }
コード例 #5
0
ファイル: BlueToothMotor.cs プロジェクト: cimn1989/ARSG2_222
 void Disconnect(string address)
 {
     BluetoothLEHardwareInterface.UnSubscribeCharacteristic(address, serviceUUID, characteristicUUID, null);
     BluetoothLEHardwareInterface.DisconnectPeripheral(address, null);
     // BluetoothLEHardwareInterface.DeInitialize(null);
     // illegalDevices.Add(address);
     SetState(States.Scan, 0.5f);
 }
コード例 #6
0
ファイル: BlunoDevice.cs プロジェクト: thisisvictor/UnityBLE
    //handles Connect
    //connect the device as a peripheral, and set up the characteristics for I/O properly
    public void OnConnect(string dName, string dAddress)
    {
        _connectedName    = (string)dName.Clone();
        _connectedAddress = (string)dAddress.Clone();

        if (!_connecting)
        {     //perform a connection only if it is not doing it
            if (_connected)
            { //if already connected, disconnect it
                if (_connectedAddress != null)
                {
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_connectedAddress, null);
                }
                _connected = false;
            }
            else
            {
                _readFound  = false;
                _writeFound = false;

                //connect to the device with the address provided
                BluetoothLEHardwareInterface.ConnectToPeripheral(_connectedAddress,
                                                                 (address) => {//gets called when the connection is successful
                    _connectedAddress = address;
                    _connected        = true;
                    _connecting       = false;
                    _bleManager.IndicateConnected(dName, dAddress);     //let the manager know it is connected

                    //stop scanning if a connection is established
                    BluetoothLEHardwareInterface.StopScan();
                },
                                                                 (address, serviceUUID) => {//gets called for each service the device supports
                    BluetoothLEHardwareInterface.Log(_connectedName + " supports service: " + serviceUUID);
                },
                                                                 (address, serviceUUID, characteristicUUID) => {//gets called for each characteristic the device supports
                    BluetoothLEHardwareInterface.Log(serviceUUID + " supports characteristic: " + characteristicUUID);

                    if (serviceUUID.ToUpper().CompareTo(_serviceUUID.ToUpper()) == 0)
                    {    //the _serviceUUID is a hardware-specific value indicating a certain characteristic,
                         // i.e., different from hardware to hardware
                        if (characteristicUUID.ToUpper().CompareTo(_characteristicUUID.ToUpper()) == 0)
                        {
                            _writeFound = true;     //write characteristic of Bluno?
                        }
                    }
                }, (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
                    _connected = false;
                }
                                                                 );

                _connecting = true;
            }
        }
    }
コード例 #7
0
 /**
  * Disconnect currently connected device
  */
 public void DisconnectDevice()
 {
     if (Connected)
     {
         BluetoothLEHardwareInterface.DisconnectPeripheral(_connectedDevice.address, null);
         Connected = false;
         Initialize();
     }
 }
コード例 #8
0
ファイル: BlunoDevice.cs プロジェクト: thisisvictor/UnityBLE
 //handles Disconnect
 //disconnect the device as a peripheral
 public void OnDisconnect()
 {
     if (_connectedAddress != null)
     {//disconnect from a connected device if there is any
         BluetoothLEHardwareInterface.DisconnectPeripheral(_connectedAddress, null);
         _connectedAddress = null;
     }
     _connected = false;
 }
コード例 #9
0
 //deinitialize the bluetooth system when the script is destroyed
 private void OnDestroy()
 {
     if (_connectedAddress != null)
     {//disconnect from a connected device if there is any
         BluetoothLEHardwareInterface.DisconnectPeripheral(_connectedAddress, null);
         _connectedAddress = null;
         _connected        = false;
         _connecting       = false;
     }
     BluetoothLEHardwareInterface.DeInitialize(null);
 }
コード例 #10
0
 void disconnect(Action <string> action)
 {
     if (TemperatureEnabled || AccelerometerEnabled)
     {
         TemperatureEnabled   = false;
         AccelerometerEnabled = false;
     }
     else
     {
         BluetoothLEHardwareInterface.DisconnectPeripheral(Address.text, action);
     }
 }
コード例 #11
0
 void disconnectToDevice()
 {
     if (_connected)
     {
         BluetoothLEHardwareInterface.DisconnectPeripheral(_JDY16, (address) => {
             BluetoothLEHardwareInterface.DeInitialize(() => { _connected = false; _state = States.None; });
         });
     }
     else
     {
         BluetoothLEHardwareInterface.DeInitialize(() => { _state = States.None; });
     }
 }
コード例 #12
0
 public static void disConnect()
 {
     if (!BTStatus)
     {
         return;
     }
     BluetoothLEHardwareInterface.DisconnectPeripheral(linkData.address,
                                                       (deviceAddress) =>
     {
         BTLog       = "Disconnect " + deviceAddress + " \n";
         isConnected = false;
         BTStatus    = false;
     });
 }
コード例 #13
0
ファイル: Central.cs プロジェクト: ManicDesigns/Dice4
    void CheckSubscriptionState(Die die)
    {
        if (Time.time - die.startTime > SubscribeCharacteristicsTimeout)
        {
            Debug.LogError("Timeout trying to subscribe to die " + die.name);
            onBluetoothError -= OnCharacteristicSubscriptionError;

            // Temporarily add the die to the connected list to avoid an error message during the disconnect
            // And force a disconnect
            die.state = Die.State.Disconnecting;
            BluetoothLEHardwareInterface.DisconnectPeripheral(die.address, null);

            StartNextSubscribeToCharacteristic();
        }
    }
コード例 #14
0
 private void HandleDisconnected()
 {
     if (ConnectedToAdr != "NULL")
     {
         BluetoothLEHardwareInterface.DisconnectPeripheral(ConnectedToAdr, null);
     }
     // Reset state, go back to Scan:
     CurRoll         = 0.0f;
     CurPitch        = 0.0f;
     CurYaw          = 0.0f;
     PendingResponse = false;
     ConnectTimer    = 0.0f;
     ConnectedToAdr  = "NULL";
     ResetPeripherals();
     UpdateState(States.Scan);
 }
コード例 #15
0
    public void OnButtonClick(int buttonID)
    {
        if (buttonID >= 0 && buttonID < 4)
        {
            DeviceObject device                   = FoundDeviceListScript.DeviceAddressList[buttonID];
            Text         button                   = Buttons[buttonID];
            string       subscribedService        = Services[buttonID];
            string       subscribedCharacteristic = Characteristics[buttonID];

            if (device != null && button != null)
            {
                if (button.text.Contains("connected"))
                {
                    if (!string.IsNullOrEmpty(subscribedService) && !string.IsNullOrEmpty(subscribedCharacteristic))
                    {
                        BluetoothLEHardwareInterface.UnSubscribeCharacteristic(device.Address, subscribedService, subscribedCharacteristic, (characteristic) => {
                            Services[buttonID]        = null;
                            Characteristics[buttonID] = null;

                            BluetoothLEHardwareInterface.DisconnectPeripheral(device.Address, (disconnectAddress) => {
                                button.text = device.Name;
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(device.Address, (disconnectAddress) => {
                            button.text = device.Name;
                        });
                    }
                }
                else
                {
                    BluetoothLEHardwareInterface.ConnectToPeripheral(device.Address, (address) => {
                    }, null, (address, service, characteristic) => {
                        if (string.IsNullOrEmpty(Services[buttonID]) && string.IsNullOrEmpty(Characteristics[buttonID]))
                        {
                            Services[buttonID]        = FullUUID(service);
                            Characteristics[buttonID] = FullUUID(characteristic);
                            button.text = device.Name + " connected";
                        }
                    }, null);
                }
            }
        }
    }
コード例 #16
0
    public static void BTreadOff()
    {
        if (!BTStatus)
        {
            return;
        }

        /*BluetoothLEHardwareInterface.UnSubscribeCharacteristic(connectedID, FullUUID(serviceUUID), FullUUID(rCharacteristicUUID),
         *      (unSubscribe) =>
         *      {
         *              readStart = true;
         *      });*/
        BluetoothLEHardwareInterface.DisconnectPeripheral(connectedID,
                                                          (disconnect) =>
        {
            BTStatus  = false;
            readStart = false;
        });
    }
コード例 #17
0
ファイル: Central.cs プロジェクト: ManicDesigns/Dice4
    /// <summary>
    /// Disconnect from a given die
    /// </summary>
    public void DisconnectDie(IDie die)
    {
        if (_dice.TryGetValue(die.address, out Die ddie))
        {
            if (ddie.state == Die.State.Advertising)
            {
                Debug.LogError("Die " + die.name + " in invalid state " + ddie.state);
                return;
            }

            // And kick off the disconnection!
            ddie.state = Die.State.Disconnecting;
            BluetoothLEHardwareInterface.DisconnectPeripheral(die.address, null);
        }
        else
        {
            Debug.LogError("Trying to disconnect unknown die " + die.name);
        }
    }
コード例 #18
0
    //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;
        }
    }
コード例 #19
0
        /// <summary>
        /// Disconnects the whole BLE Service.
        /// </summary>
        /// <param name="device"></param>
        public static void Disconnect(Device device)
        {
            CheckIfInitialized();

            if (CurrentState < State.Connected)
            {
                throw new Exception("You need to be connected to be able to disconnect");
            }

            SetState(State.Disconnecting);
            Observable
            .Timer(TimeSpan.FromSeconds(4f))
            .Subscribe(_ =>
            {
                BluetoothLEHardwareInterface.DisconnectPeripheral(device.Address, address => {
                    DeInitialize();
                    SetState(State.ReadyToScan);
                    IsInitialized = false;
                });
            });
        }
コード例 #20
0
 void ForceDisconnect()
 {
     if (_connected)
     {
         BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
             BluetoothLEHardwareInterface.DeInitialize(() => {
                 is_quit_ok = true;
                 _connected = false;
                 _state     = States.None;
             });
         });
     }
     else
     {
         BluetoothLEHardwareInterface.DeInitialize(() => {
             _state     = States.None;
             is_quit_ok = true;
         });
     }
     Reset();
 }
コード例 #21
0
ファイル: Central.cs プロジェクト: ManicDesigns/Dice4
    void OnCharacteristicSubscriptionError(string error)
    {
        Die sub = _dice.Values.FirstOrDefault(d => d.state == Die.State.Subscribing);

        if (sub != null)
        {
            Debug.LogError("Die " + sub.name + " couldn't subscribe to read characteristic!");
            onBluetoothError -= OnCharacteristicSubscriptionError;

            // Temporarily add the die to the connected list to avoid an error message during the disconnect
            // And force a disconnect
            sub.state = Die.State.Disconnecting;
            BluetoothLEHardwareInterface.DisconnectPeripheral(sub.address, null);

            StartNextSubscribeToCharacteristic();
        }
        else
        {
            Debug.LogError("Subscription error but no subscribing die");
        }
    }
コード例 #22
0
    void CheckSubscriptionState(Die die)
    {
        if (Time.time - die.startTime > SubscribeCharacteristicsTimeout)
        {
            Debug.Assert(_state == State.Connecting);
            _state = State.Idle;
            string errorString = "Timeout trying to subscribe to die";
            Debug.LogError("Characteristic Error: " + die.name + ": " + errorString);
            die.onConnectionResult?.Invoke(die, false, errorString);
            die.onConnectionResult        = null;
            die.onUnexpectedDisconnection = null;
            die.onData = null;

            // Temporarily add the die to the connected list to avoid an error message during the disconnect
            // And force a disconnect
            die.state = Die.State.Disconnecting;
            _state    = State.Disconnecting;
            BluetoothLEHardwareInterface.DisconnectPeripheral(die.address, null);

            StartNextSubscribeToCharacteristic();
        }
    }
コード例 #23
0
    public void Disconnect()
    {
        if (this.debugOutput)
        {
            Debug.Log("*** BLE Disconnect");
        }
        try
        {
            BluetoothLEHardwareInterface.DisconnectPeripheral(this.uuids[this.connectedDevice], this.disconnectCallback);
        }
        catch (Exception exception1)
        {
            Exception exception = exception1;
            Debug.LogError("DisconnectPeripheral failed 2");
            Debug.LogException(exception);
            if (exception.Message.Contains("out of range"))
            {
                Debug.Log("Out of Range disconnect, break out");
                base.CancelInvoke("timeOut");
                this.m_skipTimeoutDisconnect = true;
                return;
            }
        }
        base.CancelInvoke("SendPIN");
        base.CancelInvoke("timeOut");
        BluetoothLE.connecting       = false;
        BluetoothLE.connectDataState = false;
        BluetoothLE.connectState     = false;
        this.connectedDevice         = -1;
        this.setWriteState(false);

        if (this.waitingForSequenceFeedback)
        {
            this.waitingForSequenceFeedback = false;
            return;
        }
        base.Invoke("disconnectCB", 2f);
    }
コード例 #24
0
    public void OnBluetoothFightFinish()
    {
        MyDebug.LogGreen("OnBluetoothFightFinish");
        if (isCentral)
        {
            MyDebug.LogGreen("OnBluetoothFightFinish:Central");
            BluetoothLEHardwareInterface.UnSubscribeCharacteristic(CurPeripheralInstance.address,
                                                                   ServiceUUID,
                                                                   ReadUUID,
                                                                   (characteristic) =>
            {
                MyDebug.LogGreen("UnSubscribeCharacteristic Success :" + characteristic);
            });

            BluetoothLEHardwareInterface.DisconnectPeripheral(CurPeripheralInstance.address,
                                                              (disconnectAddress) =>
            {
                MyDebug.LogGreen("DisconnectPeripheral Success:" + disconnectAddress);
            });
        }
        else
        {
            MyDebug.LogGreen("OnBluetoothFightFinish:Peripheral");
            BluetoothLEHardwareInterface.StopAdvertising(() =>
            {
                MyDebug.LogGreen("Stop Advertising!");
            });
        }

        BluetoothLEHardwareInterface.RemoveCharacteristics();
        BluetoothLEHardwareInterface.RemoveServices();

        BluetoothLEHardwareInterface.DeInitialize(() =>
        {
            MyDebug.LogGreen("DeInitialize Success!");
        });
        BluetoothLEHardwareInterface.BluetoothEnable(false);
    }
コード例 #25
0
    /// <summary>
    /// Disconnect from a given die
    /// </summary>
    void DoDisconnectDie(IDie die, System.Action <IDie, bool, string> onDisconnectionResult)
    {
        if (_dice.TryGetValue(die.address, out Die ddie))
        {
            Debug.Log("Disconnecting die " + die.name);
            if (ddie.state == Die.State.Advertising)
            {
                Debug.LogError("Die " + die.name + " in invalid state " + ddie.state);
                return;
            }

            _state = State.Disconnecting;

            // And kick off the disconnection!
            ddie.state = Die.State.Disconnecting;
            ddie.onDisconnectionResult = onDisconnectionResult;
            BluetoothLEHardwareInterface.DisconnectPeripheral(die.address, null); // <-- we don't use this callback, we already have one
        }
        else
        {
            Debug.LogError("Trying to disconnect unknown die " + die.name);
        }
    }
コード例 #26
0
    void CheckDieCharacteristics(Die die)
    {
        // Check that the die has the read and write characteristics
        if (die.deviceConnected &&
            die.messageReadCharacteristicFound &&
            die.messageWriteCharacteristicFound)
        {
            die.state = Die.State.Connected;

            // Subscribe, but only subscribe to one characteristic at a time
            StartNextSubscribeToCharacteristic();
        }
        else
        {
            // Check timeout!
            if (Time.time - die.startTime > DiscoverCharacteristicsTimeout)
            {
                Debug.Assert(_state == State.Connecting);
                _state = State.Idle;
                // Wrong characteristics, we can't talk to this die!
                string errorString = "Timeout looking for characteristics on Die";
                die.onConnectionResult?.Invoke(die, false, errorString);
                die.onConnectionResult        = null;
                die.onUnexpectedDisconnection = null;
                die.onData = null;
                Debug.LogError("Characteristic Error: " + die.name + ": " + errorString);

                // Temporarily add the die to the connected list to avoid an error message during the disconnect
                // And force a disconnect
                die.state = Die.State.Disconnecting;
                _state    = State.Disconnecting;
                BluetoothLEHardwareInterface.DisconnectPeripheral(die.address, null);
            }
            // Else just keep waiting
        }
    }
コード例 #27
0
    public void DisconnectDie(Die die, System.Action <Die> dieDisconnectedCallback)
    {
        System.Action <string> dieDisconnected =
            (ad) =>
        {
            if (ad == die.address)
            {
                if (dieDisconnectedCallback != null)
                {
                    dieDisconnectedCallback(die);
                }
                // Other callbacks are already set
            }
        };

        if (virtualBluetooth == null || !virtualBluetooth.IsVirtualDie(die.address))
        {
            BluetoothLEHardwareInterface.DisconnectPeripheral(die.address, dieDisconnected);
        }
        else
        {
            virtualBluetooth.DisconnectPeripheral(die.address, dieDisconnected);
        }
    }
コード例 #28
0
    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;
                }
            }
        }
    }
コード例 #29
0
    // 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;
                }
            }
        }
    }
コード例 #30
0
    // 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;
                }
            }
        }
    }