Exemplo n.º 1
0
 public void ToConnect3()
 {
     Sup.text = "Connecting to sensor 3...";
     BluetoothLEHardwareInterface.ConnectToPeripheral(Address3, (address) =>
     {
     }, (address, serviceUUID) =>
     {
     }, (address, serviceUUID, characteristicUUID) =>
     {
         Sup.text = "Connected to sensor 3.";
         StartCoroutine(SubscribeSensor3());                                 //Subscribes the sensor(=get data from it)
     }, (address) =>
     {
     });
 }
Exemplo n.º 2
0
 public IEnumerator ToConnect4()
 {
     Sup.text = "Connecting to sensor 4...";
     BluetoothLEHardwareInterface.ConnectToPeripheral(Address4, (address) =>
     {
     }, (address, serviceUUID) =>
     {
     }, (address, serviceUUID, characteristicUUID) =>
     {
         Sup.text = "Connected to sensor 4.";
     }, (address) =>
     {
     });
     yield return(null);
 }
Exemplo n.º 3
0
    public void OnConnect()
    {
        if (!_connecting)
        {
            if (Connected)
            {
                disconnect((Address) => {
                    Connected = false;
                });
            }
            else
            {
                _readFound  = false;
                _writeFound = false;

                BluetoothLEHardwareInterface.ConnectToPeripheral(Address.text, (address) => {
                },
                                                                 (address, serviceUUID) => {
                },
                                                                 (address, serviceUUID, characteristicUUID) => {
                    // discovered characteristic
                    if (IsEqual(serviceUUID, _serviceUUID))
                    {
                        _connectedID = address;

                        Connected = true;

                        if (IsEqual(characteristicUUID, _readCharacteristicUUID))
                        {
                            _readFound = true;
                        }
                        else if (IsEqual(characteristicUUID, _writeCharacteristicUUID))
                        {
                            _writeFound = 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
                    Connected = false;
                });

                _connecting = true;
            }
        }
    }
Exemplo n.º 4
0
 /// <summary>
 /// 连接到蓝牙
 /// </summary>
 public void ConnectBluetooth(string bleAddress)
 {
     Show("开始连接到蓝牙... ...");
     BluetoothLEHardwareInterface.ConnectToPeripheral(bleAddress, (address) => { }, (address, serviceUUID) => { }, (address, serviceUUID, characteristicUUID) =>
     {
         Show("蓝牙连接成功!");
         SubscribeBluetoothMsg(bleAddress);
     }, (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;
     });
 }
Exemplo n.º 5
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);
                }
            }
        }
    }
Exemplo n.º 6
0
 public void ConnectToDevice(Device device)
 {
     if (!_connecting)
     {
         if (Connected)
         {
             DisconnectDevice(_connectedDevice);
         }
         else
         {
             BluetoothLEHardwareInterface.Log("Connecting to peripheral");
             _connecting = true;
             BluetoothLEHardwareInterface.ConnectToPeripheral(device.address, (address) => {
             },
                                                              (address, serviceUUID) => {
             },
                                                              (address, serviceUUID, characteristicUUID) => {
                 BluetoothLEHardwareInterface.Log("uuidFound: " + serviceUUID + " uuidExpected: " + _heartRateServiceUUID);
                 // discovered characteristic
                 if (IsEqual(serviceUUID, _heartRateServiceUUID))
                 {
                     _connectedID     = address;
                     _connectedDevice = new HRMDevice(device.name, device.address);
                     Connected        = true;
                     BluetoothLEHardwareInterface.Log("^^^Connected to peripheral");
                     if (IsEqual(characteristicUUID, _readHRCharacteristicUUID))
                     {
                         BluetoothLEHardwareInterface.Log("Subscribing to HR characteristic");
                         BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_connectedID, _heartRateServiceUUID, _readHRCharacteristicUUID, (deviceAddress, notification) => {
                         }, (deviceAddress2, characteristic, data) => {
                             OnNewHRMeasurement(deviceAddress2, characteristic, data);
                         });
                     }
                 }
             }, (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 = false;
         }
     }
 }
Exemplo n.º 7
0
    public IEnumerator ToConnect3()
    {
        Sup.text = "Connecting to sensor 3...";

        statusImageSensor2.texture = orangeLight;

        BluetoothLEHardwareInterface.ConnectToPeripheral(Address3, (address) =>
        {
        }, (address, serviceUUID) =>
        {
        }, (address, serviceUUID, characteristicUUID) =>
        {
            Sup.text = "Connected to sensor 3.";
        }, (address) =>
        {
        });
        yield return(null);
    }
Exemplo n.º 8
0
 public void Connect(int index)
 {
     this.StopScan();
     this.connectedDevice         = index;
     BluetoothLE.connectDataState = false;
     BluetoothLE.connectState     = false;
     BluetoothLE.connecting       = true;
     if (this.jDebug)
     {
         Debug.Log(string.Concat("connecting to ", index));
     }
     if (this.jDebug)
     {
         Debug.Log(this.uuids[this.connectedDevice]);
     }
     BluetoothLEHardwareInterface.ConnectToPeripheral(this.uuids[this.connectedDevice], new Action <string>(this.Connected), new Action <string, string>(this.Service), new Action <string, string, string>(this.Characteristic), null);
     base.Invoke("timeOut", 30f);
 }
Exemplo n.º 9
0
    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
        });
    }
Exemplo n.º 10
0
    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();
        });
    }
    void connectToDevice()
    {
        bluetoothStatus.text = "Connecting...";

        BluetoothLEHardwareInterface.ConnectToPeripheral(_JDY16, null, null, (address, serviceUUID, characteristicUUID) => {
            if (IsEqual(serviceUUID, ServiceUUID))
            {
                if (IsEqual(characteristicUUID, Characteristic))
                {
                    _connected           = true;
                    _state               = States.Subscribe;
                    bluetoothStatus.text = "Connected!";
                }
            }
        }, (disconnectedAddress) => {
            BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress);
            bluetoothStatus.text = "Disconnected!";
            StartProcess();
        });
    }
Exemplo n.º 12
0
 public static void ConnectBSN()
 {
     Debug.Log("entrando conect");
     foreach (DeviceObject deviceBiox in FoundDeviceList.DeviceAddressList)
     {
         Debug.Log("entrando device");
         //Buttons[buttonID++].text = device.Name
         if (deviceBiox.Name.Contains("Biox") || deviceBiox.Name.Contains("BIOX") || deviceBiox.Name.Contains("bsn") || deviceBiox.Name.Contains("BSN"))
         {
             bsnDevice = deviceBiox;
             Debug.Log(bsnDevice.Name);
             BluetoothLEHardwareInterface.ConnectToPeripheral(bsnDevice.Address, (address) =>
             {
             }, null, (address, service, characteristic) =>
             {
                 Debug.Log("xDDAdress: " + address + " Service: " + service + " Characteristic: " + characteristic);
             }, null);
         }
     }
 }
Exemplo n.º 13
0
    // Init connection
    void beginConnection(System.Action <bool> action)
    {
        if (!_connecting)
        {
            BluetoothLEHardwareInterface.ConnectToPeripheral(_connectedID,
                                                             (address) => {
                // On Connection Action
            },
                                                             (address, serviceUUID) => {
                // Service detection
            },
                                                             (address, serviceUUID, characteristicUUID) => {
                // Characteristis detection
                urbanDetected = true;
                if (count < serviceLimit)
                {
                    count++;
                }
                else
                {
                    action(true);
                }
            }, (error) => {
                //On connection error
                action(false);
            },
                                                             (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;
        }
        else
        {
            action(true);
        }
    }
Exemplo n.º 14
0
    void StartConnection()
    {
        EventDispatcher.SendEvent(eBT_CONNECTION_STATUS, "Подключаемся.");

        BluetoothLEHardwareInterface.ConnectToPeripheral(deviceAddress, (str) =>
        {
            Debug.Log("StartConnection deviceAddress = " + deviceAddress + " str = " + str);
            if (str.Equals(deviceAddress))
            {
                SetState(BtStates.Subscribe, 2.0f);
            }
            else
            {
                Debug.Log("ConnectToPeripheral failed. Connection error 1 " + str);
                SetState(BtStates.ConnectingError, 0.3f);
            }
        }, null, null, (str) =>
        {
            Debug.Log("ConnectToPeripheral failed. Connection error 2 " + str);
            SetState(BtStates.ConnectingError, 0.3f);
        });
    }
Exemplo n.º 15
0
    void Connect(string _deviceID, Action _complete = null)
    {
        BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceID, (str) =>
        {
            Debug.Log("Connected: " + str);
            if (null != _complete)
            {
                _complete();
            }
        }, (address, service) =>
        {
#if UNITY_ANDROID
            service = service.Substring(4, 4).ToUpper();
#endif
            //  等待所有服务开启后,就可以进行下一步(FFC0 和 FFF0)
            //  TODO: 未完成
            if ("FFF0" == service)
            {
                FFF0_enabled = true;
            }
            else if ("FFC0" == service)
            {
                FFC0_enabled = true;
            }
            if (FFC0_enabled || FFF0_enabled)
            {
                connected = true;
            }
        }, null, (str) =>
        {
            if (isLegal)
            {
                Debug.Log("Reconnecting: " + str);
                connected = false;
                Connect(str, () => { StartCoroutine(Subscribe(m_deviceID, "FFF0", "FFF8", MsgHandler)); });
            }
        });
    }
Exemplo n.º 16
0
    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;
        });
    }
Exemplo n.º 17
0
    public void OnConnect(string bleAddress)
    {
        if (!_connecting)
        {
            if (Connected)
            {
                return;
            }
            else
            {
                BluetoothLEHardwareInterface.ConnectToPeripheral(bleAddress, (address) =>
                {
                },
                                                                 (address, serviceUUID) =>
                {
                },
                                                                 (address, serviceUUID, characteristicUUID) =>
                {
                    Show("蓝牙连接成功!");
                    SubscribeBluetoothMsg(bleAddress);
                }, (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

                    Shoot.isFire01 = false;
                    Show("蓝牙已断开,请尝试重新连接......");
                    //InitBluetooth();
                    Connected = false;
                });

                _connecting = true;
            }
        }
    }
Exemplo n.º 18
0
    /// <summary>
    /// Connect to a die
    /// </summary>
    void DoConnectDie(
        IDie die,
        System.Action <IDie, bool, string> connectionResultCallback,
        System.Action <IDie, byte[]> onDataCallback,
        System.Action <IDie, string> onUnexpectedDisconnectionCallback)
    {
        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;
            }

            ddie.state           = Die.State.Connecting;
            ddie.startTime       = Time.time;
            ddie.deviceConnected = false;
            ddie.messageReadCharacteristicFound  = false;
            ddie.messageWriteCharacteristicFound = false;
            ddie.onConnectionResult        = connectionResultCallback;
            ddie.onData                    = onDataCallback;
            ddie.onUnexpectedDisconnection = onUnexpectedDisconnectionCallback;

            Debug.Log("Connecting to die " + ddie.name);

            _state = State.Connecting;

            // And kick off the connection!
            BluetoothLEHardwareInterface.ConnectToPeripheral(die.address, OnDeviceConnected, OnServiceDiscovered, OnCharacteristicDiscovered, OnDeviceDisconnected);
        }
        else
        {
            string errorMessage = "Trying to connect to unknown die " + die.name;
            Debug.LogError(errorMessage);
            connectionResultCallback?.Invoke(die, false, errorMessage);
        }
    }
Exemplo n.º 19
0
    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;
        });
    }
Exemplo n.º 20
0
    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;
        });
    }
Exemplo n.º 21
0
    /// <summary>
    /// Connect to a die
    /// </summary>
    public void ConnectDie(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;
            }

            ddie.state           = Die.State.Connecting;
            ddie.startTime       = Time.time;
            ddie.deviceConnected = false;
            ddie.messageReadCharacteristicFound  = false;
            ddie.messageWriteCharacteristicFound = false;

            // And kick off the connection!
            BluetoothLEHardwareInterface.ConnectToPeripheral(die.address, OnDeviceConnected, OnServiceDiscovered, OnCharacteristicDiscovered, OnDeviceDisconnected);
        }
        else
        {
            Debug.LogError("Trying to connect to unknown die " + die.name);
        }
    }
Exemplo n.º 22
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;
                }
            }
        }
    }
Exemplo n.º 23
0
//	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;
            }
        }
    }
Exemplo n.º 24
0
    /// <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;
            }
        }
    }
Exemplo n.º 25
0
    void Update()
    {
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;
            if (_timeout <= 0f)
            {
                _timeout = 0f;

                switch (_state)
                {
                case States.None:
                    if (_dataBytes != null)
                    {
                        msg        = "\nData Received: " + BitConverter.ToString(_dataBytes);
                        _dataBytes = null;
                    }
                    break;

                case States.Scan:
                    /* ScanForPeripheralsWithServices (string[]serviceUUIDs, Action<string, string> action,
                     * Action<string, string, int, byte[]> actionAdvertisingInfo =null,
                     * bool rssiOnly = false, bool clearPeripheralList =true)
                     */
                    BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ServiceUUIDs, (address, name) => {
                        FoundDeviceList.DeviceInfoList.Add(new DeviceObject(address, name));
                    }
                                                                                );
                    break;

                case  States.ScanRSSI:
                    //Not planning to support this any time soon
                    break;

                case States.Connect:
                    // note that the first parameter is the address, not the name - error in API.
                    BluetoothLEHardwareInterface.ConnectToPeripheral(_addressToConnect, null, null, (address, serviceUUID, characteristicUUID) => {
                        if (IsEqual(serviceUUID, ServiceUUIDs[0]))
                        {
                            _foundNotifyUUID = _foundNotifyUUID || IsEqual(characteristicUUID, notifyUUID);
                            msg             = ("_foundNotifyUUID: " + _foundNotifyUUID + " ");
                            _foundWriteUUID = _foundWriteUUID || IsEqual(characteristicUUID, writeUUID);
                            msg            += ("_foundWriteUUID: " + _foundWriteUUID);

                            // 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 (_foundNotifyUUID && _foundWriteUUID)
                            {
                                connected = true;
                                msg       = "Connected Succesfully";
                                SetState(States.CommSetup, 2f);
                            }
                        }
                    });
                    break;

                case States.Subscribe:
                    msg = "Subscribing..";
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_addressToConnect, ServiceUUIDs[0], notifyUUID, 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;
                        SetState(States.None, 0.1f);

                        // we received some data from the device
                        _dataBytes = bytes;
                    });
                    msg = "Subscribed. Robot Ready";
                    SetState(States.None, 0.1f);
                    break;

                case States.Unsubscribe:
                    break;

                case States.Disconnect:
                    break;

                case States.CommSetup:
                    msg = "Telling 3DoT to set up Comms...";
                    byte[] tempData = { 0x00 };
                    SendCommand(CommandID.COMM_SETUP, tempData);
                    SetState(States.Subscribe, 2f);
                    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;
                }
            }
        }
    }
Exemplo n.º 27
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;
                }
            }
        }
    }
Exemplo n.º 28
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 (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;
                }
            }
        }
    }
Exemplo n.º 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;
                }
            }
        }
    }
    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;
                }
            }
        }
    }