Exemplo n.º 1
0
        /// <summary>
        /// Unregister from a given characteristic
        /// </summary>
        public static void Unsubscribe(Characteristic characteristic)
        {
            CheckIfInitialized();

            BluetoothLEHardwareInterface.UnSubscribeCharacteristic(characteristic.Device.Address,
                                                                   characteristic.ServiceUuid, characteristic.CharacteristicUuid, null);
        }
Exemplo n.º 2
0
 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);
 }
Exemplo n.º 3
0
    //  TODO: 是否需要修改?
    public IEnumerator UnSubscribe(string _service, string _channel)
    {
        bool complete = false;

        if (subscribeHandlers.ContainsKey(_channel.ToUpper()))
        {
            subscribeHandlers.Remove(_channel.ToUpper());
        }
        BluetoothLEHardwareInterface.UnSubscribeCharacteristic(m_deviceID, _service, _channel, (str) => { complete = true; });
        yield return(new WaitUntil(() => complete));
    }
Exemplo n.º 4
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.º 5
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);
    }
Exemplo n.º 6
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.º 7
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.º 8
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.º 9
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.º 10
0
    void Update()
    {
        RotatePlayer();
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;
            if (_timeout <= 0f)
            {
                _timeout = 0f;
                switch (_state)
                {
                case States.None:
                    break;

                case States.Scan:
                    HM10_Status.text = "Scanning for HM10 devices...";
                    BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => {
                        if (name.Contains(DeviceName))
                        {
                            _workingFoundDevice = true;
                            BluetoothLEHardwareInterface.StopScan(); // stop scanning while you connect to a device
                            _hm10            = address;              // add it to the list and set to connect to it
                            HM10_Status.text = "Found HM10";
                            SetState(States.Connect, 0.5f);
                            _workingFoundDevice = false;
                        }
                    }, null, false, false);
                    break;

                case States.Connect:
                    HM10_Status.text = "Connecting to HM10";
                    BluetoothLEHardwareInterface.ConnectToPeripheral(_hm10, null, null, (address, serviceUUID, characteristicUUID) => {
                        if (IsEqual(serviceUUID, ServiceUUID))
                        {
                            if (IsEqual(characteristicUUID, Characteristic))
                            {
                                _connected = true;
                                SetState(States.Subscribe, 2f);
                            }
                        }
                    }, (disconnectedAddress) => {
                        BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress);
                        HM10_Status.text = "Disconnected";
                    });
                    break;

                case States.Subscribe:
                    HM10_Status.text = "Connected to HM10";
                    enabled          = true;
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_hm10, ServiceUUID, Characteristic, null, (address, characteristicUUID, bytes) => {});
                    _state = States.None;    // set to the none state and the user can start sending and receiving data

                    break;

                case States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_hm10, ServiceUUID, Characteristic, null);
                    SetState(States.Disconnect, 4f);
                    break;

                case States.Disconnect:
                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_hm10, (address) => {
                            BluetoothLEHardwareInterface.DeInitialize(() => {
                                _connected = false;
                                _state     = States.None;
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _state = States.None;
                        });
                        enabled = false;
                    }
                    break;
                }
            }
        }
    }
Exemplo n.º 11
0
    // Update is called once per frame
    void Update()
    {
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;

            if (_timeout <= 0f)
            {
                _timeout = 0f;

                switch (_state)
                {
                case machineState.None:
                    break;

                case machineState.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
                        Debug.Log("Found Device : " + address + " / Name : " + name);

                        if (name.Contains(DeviceName))
                        {
                            BluetoothLEHardwareInterface.StopScan();

                            state       = State.DeviceFound;
                            device_name = name;

                            // found a device with the name we want
                            // this example does not deal with finding more than one
                            _deviceAddress = address;
                            SetState(machineState.Connect, 0.5f);
                        }
                    }, (address, name, rssi, bytes) =>
                    {
                        // APIdou does not broadcast manufacturer specific data
                    }
                                                                                );
                    break;

                case machineState.Connect:
                    // set these flags
                    _foundAccel = false;
                    _foundGyro  = false;
                    _foundTouch = 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, foundServiceUUID, foundCharUUID) => {
                        if (IsEqual(foundServiceUUID, ServiceUUID))
                        {
                            _foundAccel = _foundAccel || IsEqual(foundCharUUID, AccelUUID);
                            _foundGyro  = _foundGyro || IsEqual(foundCharUUID, GyroUUID);
                            _foundTouch = _foundTouch || IsEqual(foundCharUUID, TouchUUID);

                            // if we have found all 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 (_foundAccel && _foundGyro && _foundTouch)
                            {
                                Debug.Log("Connected");
                                state = State.Connected;
                                SetState(machineState.Subscribe, 3f);
                            }
                        }
                    });
                    break;

                case machineState.Subscribe:
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, FullUUID(ServiceUUID), FullUUID(TouchUUID), null, onNotification);
                    System.Threading.Thread.Sleep(500);
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, FullUUID(ServiceUUID), FullUUID(AccelUUID), null, onNotification);
                    System.Threading.Thread.Sleep(500);
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, FullUUID(ServiceUUID), FullUUID(GyroUUID), null, onNotification);
                    break;

                case machineState.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, AccelUUID, null);
                    SetState(machineState.Disconnect, 4f);
                    break;

                case machineState.Disconnect:
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _state = machineState.None;
                        });
                    });
                    break;
                }
            }
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;
            if (_timeout <= 0f)
            {
                _timeout = 0f;

                switch (_state)
                {
                case States.None:
                    break;

                case States.Scan:
                    BluetoothStatus.text = "Looking for the Ezzence device...";

                    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(DeviceName))
                        {
                            _workingFoundDevice = true;

                            // it is always a good idea to stop scanning while you connect to a device
                            // and get things set up
                            BluetoothLEHardwareInterface.StopScan();
                            BluetoothStatus.text = "";

                            // add it to the list and set to connect to it
                            _ezzence = address;

                            Ezzence_Status.text = "Found Ezzence! Address: " + address;

                            SetState(States.Connect, 3f);

                            _workingFoundDevice = false;
                        }
                    }, null, false, false);
                    break;

                case States.Connect:

                    _foundID = false;

                    Ezzence_Status.text = "Connecting to Ezzence";
                    Debug.Log("Connection to ..." + DeviceName + "with address: " + _ezzence + ", in progress... \n");
                    BluetoothStatus.text = "Connection to ..." + DeviceName + "with address: " + _ezzence + ", in progress... \n";

                    //_ezzence = string name, null = Action <string> connectAction, null = Action<string, string> serviceAction, characteristicAction = Action<string, string, string>
                    BluetoothLEHardwareInterface.ConnectToPeripheral(_ezzence, null, null, (address, serviceUUID, characteristicUUID) => {
                        Debug.Log("Conect to Peripheral: serviceUUID: " + serviceUUID + ", characteristicUUID: " + characteristicUUID);
                        BluetoothStatus.text = "Is equal? " + serviceUUID + "," + ServiceUUID;

                        if (IsEqual(serviceUUID, ServiceUUID))
                        {
                            Debug.Log("Found service.");
                            BluetoothStatus.text = "Found service.";
                            Ezzence_Status.text  = "Found service.";

                            // 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

                            _connected           = true;
                            BluetoothStatus.text = "UUID: " + characteristicUUID + "Send: " + Characteristic + "Receive: " + CharacteristicRX;
                            //Debug.Log ("UUID: "+characteristicUUID + ". Send: "+Characteristic + ". Receive: "+CharacteristicRX);

                            if (IsEqual(characteristicUUID, Characteristic))
                            {
                                BluetoothStatus.text = "Send characteristic. CONNECTED!";
                                Ezzence_Status.text  = "Send characteristic. CONNECTED!.";
                                Debug.Log("Send characteristic. CONNECTED!.");
                                SetState(States.Subscribe, 2f);
                            }

                            if (IsEqual(characteristicUUID, CharacteristicRX))
                            {
                                BluetoothStatus.text = "Receive characteristic. CONNECTED!";
                                Ezzence_Status.text  = "RX Characteristic. SUBSCRIBE!";
                                Debug.Log("RX Characteristic. SUBSCRIBE!");
                                SetState(States.Subscribe, 2f);
                            }
                        }
                        // disconnectedAddress = Action<string> disconnectAction
                    }, (disconnectedAddress) => {
                        BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress);
                        Ezzence_Status.text = "Disconnected";
                        Debug.Log("Disconnected");
                    });
                    break;

                case States.Subscribe:
                    BluetoothStatus.text = "Subscribing to Ezzence";
                    Ezzence_Status.text  = "Subscribing to Ezzence";
                    Debug.Log("Subscribing to Ezzence");

                    //Receive data from Ezzence
                    //It receives IMU data with the following format I specified in Arduino:
                    //[t:millis(),AccX:valueAccelerometerX,AccY:valueAccelerometerY,AccZ:valueAccelerometerZ,GyX:valueGyroscopeX,GyY:valueGyroscopeY,GyZ:valueGyroscopeZ,
                    //millis() = time,
                    //"time" returns the number of milliseconds passed since the Ezzence board began running the current program. This number will overflow (go back to zero), after approximately 50 days.

                    //Note: BLE is limited to 20 bytes in a single BLE packet.
                    //It automatically break larger strings up into 20 byte or smaller packets and send multiple packets over the air.


                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_ezzence, ServiceUUID, CharacteristicRX, null, (address, characteristicUUID, bytes) => {
                        BluetoothStatus.text = Encoding.UTF8.GetString(bytes);
                        Ezzence_Status.text  = Encoding.UTF8.GetString(bytes);
                        //print(Encoding.UTF8.GetString (bytes));
                        messageEzzence = Encoding.UTF8.GetString(bytes);
                        print("Stream Data: " + messageEzzence);
                    });

                    // set to the none state and the user can start sending and receiving data
                    _state = States.None;
                    //Ezzence_Status.text = "Waiting...";
                    BluetoothStatus.text = "Start sending and receiving data...";

                    PanelMiddle.SetActive(true);
                    break;

                case States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_ezzence, ServiceUUID, Characteristic, null);
                    SetState(States.Disconnect, 4f);
                    break;

                case States.Disconnect:
                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_ezzence, (address) => {
                            BluetoothLEHardwareInterface.DeInitialize(() => {
                                _connected          = false;
                                _state              = States.None;
                                Ezzence_Status.text = "Disconnected";
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _state = States.None;
                        });
                    }
                    break;
                }
            }
        }
    }
Exemplo n.º 13
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:
                    BluetoothStatus.text = "Scanning for HM10 devices...";

                    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(DeviceName))
                        {
                            _workingFoundDevice = true;

                            // it is always a good idea to stop scanning while you connect to a device
                            // and get things set up
                            BluetoothLEHardwareInterface.StopScan();
                            BluetoothStatus.text = "";

                            // add it to the list and set to connect to it
                            _hm10 = address;

                            HM10_Status.text = "Found HM10";

                            SetState(States.Connect, 0.5f);

                            _workingFoundDevice = false;
                        }
                    }, null, false, false);
                    break;

                case States.Connect:
                    // set these flags
                    _foundID = false;

                    HM10_Status.text = "Connecting to HM10";

                    // 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(_hm10, null, null, (address, serviceUUID, characteristicUUID) => {
                        if (IsEqual(serviceUUID, 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 (IsEqual(characteristicUUID, Characteristic))
                            {
                                _connected = true;
                                SetState(States.Subscribe, 2f);

                                HM10_Status.text = "Connected to HM10";
                            }
                        }
                    }, (disconnectedAddress) => {
                        BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress);
                        HM10_Status.text = "Disconnected";
                    });
                    break;

                case States.Subscribe:
                    HM10_Status.text = "Subscribing to HM10";

                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_hm10, ServiceUUID, Characteristic, null, (address, characteristicUUID, bytes) => {
                        HM10_Status.text = "Received Serial: " + Encoding.UTF8.GetString(bytes);
                    });

                    // set to the none state and the user can start sending and receiving data
                    _state           = States.None;
                    HM10_Status.text = "Waiting...";

                    PanelMiddle.SetActive(true);
                    break;

                case States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_hm10, ServiceUUID, Characteristic, null);
                    SetState(States.Disconnect, 4f);
                    break;

                case States.Disconnect:
                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_hm10, (address) => {
                            BluetoothLEHardwareInterface.DeInitialize(() => {
                                _connected = false;
                                _state     = States.None;
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _state = States.None;
                        });
                    }
                    break;
                }
            }
        }
    }
Exemplo n.º 14
0
    // Update is called once per frame
    void Update()
    {
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;
            if (_timeout <= 0f)
            {
                _timeout = 0f;

                string state = _state.ToString();
                print("running state " + state);                 // + state); //+ _state.ToString ());// + _state.ToString());

                switch (_state)
                {
                case States.None:
                    break;

                case States.Scan:
                    print("Scan running");
                    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

                        print("Found 1.0 " + name);

                        print(name);
                        print(DeviceName);
                        if (name.Contains("Blue"))
                        {
                            print("Connecting " + 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
                        print("Found 2.0  " + name);

                        if (name.Contains(DeviceName))
                        {
                            print("Connecting " + 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);
                        }
                    }, _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.Send:
                    //SendString ("Hello Scott");
                    ReadString();
                    SetState(States.Send, 0.5f);
                    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) => {
                        //print("connecting to device");
                        //print(_deviceAddress);
                        //print(address);
                        print("ServiceUUID " + serviceUUID);

                        if (IsEqual(characteristicUUID, WriteCharacteristic))
                        {
                            SetState(States.None, 0.5f);
                        }
                        else if (IsEqual(characteristicUUID, ReadCharacteristic))
                        {
                            print("subscribing . . . ");
                            BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, serviceUUID, ReadCharacteristic, null, (address2, characteristicUUID2, bytes) => {
                                ReactToInput(bytes);
                            });
                        }
                    });
                    break;

                case States.Subscribe:

                    print("waiting for input. . . ");
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, ReadCharacteristic, null, (address, characteristicUUID, bytes) => {
                        print("input recieved");
                        // 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, ReadCharacteristic, 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.º 15
0
    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 (!_rssiOnly)
                        {
                            Debug.Log("TOAN1: Scanned " + name);
                            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
                        Debug.Log("TOAN2: Scanned " + name);
                        MyLog("Scanned " + name);
                        if (name.Contains(DeviceName))
                        {
                            if (_rssiOnly)
                            {
                                _rssi = rssi;
                            }
                            else
                            {
                                BluetoothLEHardwareInterface.StopScan();
                                _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:
                    // 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.
//#if UNITY_IOS
//						Debug.Log("TOAN: Changed address from " + _deviceAddress + " to");
//						_deviceAddress = "5C:31:3E:03:5E:B7";
//#endif
                    if (!_is_get_auto && TOGGLE_AUTO.isOn)
                    {
                        _is_get_auto = true;
                        MyLog("Starting StartCoroutine after 4 seconds");
                        StartCoroutine(GetAllInfor(4f));
                    }
                    Debug.Log("TOAN3: Trying to connect to address " + _deviceAddress);
                    MyLog("Trying to connect to address " + _deviceAddress);
                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, (connectAction) =>
                    {
                        Debug.Log("TOAN1441: Connect OK to " + connectAction);
                        MyLog("Connected to address " + connectAction);
                    },
                                                                     (serviceAction, serviceActio2) =>
                    {
                        Debug.Log("TOAN1442: " + serviceAction + " " + serviceActio2);
                        MyLog("Finish getting information: " + serviceAction + " " + serviceActio2);
                        if (_is_get_auto == false)
                        {
                            _is_get_auto = true;
                        }
                    }
                                                                     , (address, serviceUUID2, characteristicUUID) =>
                    {
                        Debug.Log("TOAN1444:  " + address + " ; " + serviceUUID2 + " ; " + characteristicUUID);
                        MyLog("Found UUID: " + serviceUUID2 + " ;characteristicUUID=" + characteristicUUID);
                        CharateristicItem i = AddCharaterisItem(address, serviceUUID2, characteristicUUID);
                        INFOs.Add(new CharaterisInfo(address, serviceUUID2, characteristicUUID, i));
                    },
                                                                     (s1) =>
                    {
                        Debug.Log("TOAN1445: DISCONNECTED");
                        MyLog("DISCONNECTED");
                    });
                    break;

                case States.Subscribe:
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null, (address, characteristicUUID, bytes) =>
                    {
                        Debug.Log("TOAN5: SubscribeCharacteristicWithDeviceAddress to " + _deviceAddress);
                        _state     = States.None;
                        _dataBytes = bytes;
                    });
                    break;

                case States.Unsubscribe:
                    Debug.Log("TOAN6: Unsubscribe to " + _deviceAddress);
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null);
                    SetState(States.Disconnect, 4f);
                    break;

                case States.Disconnect:
                    Debug.Log("TOAN7: Disconnect to " + _deviceAddress);
                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
                            BluetoothLEHardwareInterface.DeInitialize(() => {
                                _connected = false;
                                _state     = States.None;
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _state = States.None;
                        });
                    }
                    break;
                }
            }
        }
    }
Exemplo n.º 16
0
    // Update is called once per frame
    void Update()
    {
        if (_timeout > 0f)
        {
            _timeout -= Time.deltaTime;
            if (_timeout <= 0f)
            {
                _timeout = 0f;

                string state = _state.ToString();
                print("running state " + state);                 // + state); //+ _state.ToString ());// + _state.ToString());

                switch (_state)
                {
                case States.None:
                    break;

                case States.Scan:
                    print("Scan running");

                    if (ConnectedLeft == null || !ConnectedLeft)
                    {
                        _deviceAddressLeft = "";
                    }

                    if (ConnectedRight == null || !ConnectedRight)
                    {
                        _deviceAddressRight = "";
                    }

                    print("Scan running");
                    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

                        print("Found " + name);
                        if (!name.Contains("fruit"))
                        {
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressLeft) && string.IsNullOrEmpty(storedDeviceAddressRight))
                        {
                            storedDeviceAddressLeft = address;
                            _deviceAddressLeft      = address;
                            LeftName = name;
                            ++found;
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressRight) && !address.Equals(storedDeviceAddressLeft))
                        {
                            storedDeviceAddressRight = address;
                            _deviceAddressRight      = address;
                            RightName = name;
                            ++found;
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressLeft) && !address.Equals(storedDeviceAddressRight))
                        {
                            storedDeviceAddressLeft = address;
                            _deviceAddressLeft      = address;
                            LeftName = name;
                            ++found;
                        }
                        else if (address.Equals(storedDeviceAddressLeft) && ConnectedLeft != null && !ConnectedLeft)
                        {
                            LeftName           = name;
                            _deviceAddressLeft = address;
                            ++found;
                        }
                        else if (address.Equals(storedDeviceAddressRight) && ConnectedRight != null && !ConnectedRight)
                        {
                            RightName           = name;
                            _deviceAddressRight = address;
                            ++found;
                        }
                        if (found >= 2 || _timeout < -4)
                        {
                            found = 0;
                            SetState(States.Connect, 0.5f);
                            BluetoothLEHardwareInterface.StopScan();
                        }
                    }, (address, name, rssi, bytes) => {
                        print("Found " + name);
                        if (string.IsNullOrEmpty(storedDeviceAddressLeft) && string.IsNullOrEmpty(storedDeviceAddressRight))
                        {
                            storedDeviceAddressLeft = address;
                            _deviceAddressLeft      = address;
                            LeftName = name;
                            ++found;
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressRight) && !address.Equals(storedDeviceAddressLeft))
                        {
                            storedDeviceAddressRight = address;
                            _deviceAddressRight      = address;
                            RightName = name;
                            ++found;
                        }
                        else if (string.IsNullOrEmpty(storedDeviceAddressLeft) && !address.Equals(storedDeviceAddressRight))
                        {
                            storedDeviceAddressLeft = address;
                            _deviceAddressLeft      = address;
                            LeftName = name;
                            ++found;
                        }
                        else if (address.Equals(storedDeviceAddressLeft) && ConnectedLeft != null && !ConnectedLeft)
                        {
                            LeftName           = name;
                            _deviceAddressLeft = address;
                            ++found;
                        }
                        else if (address.Equals(storedDeviceAddressRight) && ConnectedRight != null && !ConnectedRight)
                        {
                            RightName           = name;
                            _deviceAddressRight = address;
                            ++found;
                        }
                        if (found >= 2 || _timeout < -4)
                        {
                            found = 0;
                            SetState(States.Connect, 0.5f);
                            BluetoothLEHardwareInterface.StopScan();
                        }
                    }, _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.Send:
                    //SendString ("Hello Scott");
                    ReadString();
                    SetState(States.Send, 0.5f);
                    break;


                case States.Connect:
                    // set these flags
                    _foundSubscribeID = false;
                    _foundWriteID     = false;

                    print("Connect Primary running for Left! " + LeftName);

                    print("Scott12: Connected LEFT: " + ConnectedLeft + " Connected Right " + ConnectedRight + " Device Address Left: " + _deviceAddressLeft + " Device Address Right: " + _deviceAddressRight);

                    if (ConnectedLeft == null)
                    {
                        ConnectedLeft = false;
                    }
                    if (ConnectedLeft || string.IsNullOrEmpty(_deviceAddressLeft))
                    {
                        SetState(States.ConnectSecondary, 0.1f);
                        return;
                    }

                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddressLeft, (address) => {
                    },
                                                                     (address, serviceUUID) => {
                    },
                                                                     (address, serviceUUID, characteristicUUID) => {
                        print("connecting to characteristic Blue!" + characteristicUUID);
                        if (IsEqual(characteristicUUID, ReadCharacteristic))
                        {
                            //print ("subscribing . . . ");
                            print("Blue!: Device Address Blue: " + _deviceAddressLeft + "\n" +
                                  "Blue: Service UUID: " + serviceUUID + "/n" +
                                  "Blue: Read Characteristic: " + ReadCharacteristic + "\n");

//							BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress (_deviceAddressLeft, serviceUUID, ReadCharacteristic, null, (address2, characteristicUUID2, bytes) => {
//								print ("Blue frame update");
//								ReactToInput (bytes, address2);
//
                            SetState(States.ConnectSecondary, 0.5f);
                            ConnectedLeft = 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
                        if (address.Equals(_deviceAddressLeft))
                        {
                            ConnectedLeft      = false;
                            subscribedLeft     = false;
                            _deviceAddressLeft = "";
                        }
                        else if (address.Equals(_deviceAddressRight))
                        {
                            ConnectedRight      = false;
                            subscribedRight     = false;
                            _deviceAddressRight = "";
                        }
                    });

                    break;

                case States.ConnectPrimary:
                    // set these flags
                    print("Connect Primary running for Left! " + LeftName);

                    if (ConnectedLeft == null)
                    {
                        ConnectedLeft = false;
                    }
                    if (ConnectedLeft || string.IsNullOrEmpty(_deviceAddressLeft))
                    {
                        return;
                    }

                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddressLeft, (address) => {
                    },
                                                                     (address, serviceUUID) => {
                    },
                                                                     (address, serviceUUID, characteristicUUID) => {
                        print("connecting to characteristic Blue!" + characteristicUUID);
                        if (IsEqual(characteristicUUID, ReadCharacteristic))
                        {
                            //print ("subscribing . . . ");
                            print("Blue!: Device Address Blue: " + _deviceAddressLeft + "\n" +
                                  "Blue: Service UUID: " + serviceUUID + "/n" +
                                  "Blue: Read Characteristic: " + ReadCharacteristic + "\n");

                            //							BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress (_deviceAddressLeft, serviceUUID, ReadCharacteristic, null, (address2, characteristicUUID2, bytes) => {
                            //								print ("Blue frame update");
                            //								ReactToInput (bytes, address2);
                            //
                            //							SetState (States.ConnectSecondary, 0.5f);
                            ConnectedLeft = 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
                        if (address.Equals(_deviceAddressLeft))
                        {
                            ConnectedLeft      = false;
                            subscribedLeft     = false;
                            _deviceAddressLeft = "";
                        }
                        else if (address.Equals(_deviceAddressRight))
                        {
                            ConnectedRight      = false;
                            subscribedRight     = false;
                            _deviceAddressRight = "";
                        }
                    });

                    break;

                case States.ConnectSecondary:
                    _foundSubscribeID = false;
                    _foundWriteID     = false;

                    print("Connect Secondary running for " + RightName);

                    if (ConnectedRight || string.IsNullOrEmpty(_deviceAddressRight))
                    {
                        //TODO: hook this up to normal mode
                        return;
                    }

                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddressRight, null, null, (address2, serviceUUID2, characteristicUUID2) => {
                        //print("connecting to device");
                        //print(_deviceAddress);
                        //print(address);
                        print("connecting to characteristic " + characteristicUUID2);

                        /*if (IsEqual (characteristicUUID2, WriteCharacteristic)) {
                         *      SetState (States.None, 0.5f);
                         * } else */
                        if (IsEqual(characteristicUUID2, ReadCharacteristic))
                        {
//							print ("subscribing . . . ");
                            print("Red!: Device Address Red: " + _deviceAddressRight + "\n" +
                                  "Red: Service UUID: " + serviceUUID2 + "/n" +
                                  "Red: Read Characteristic: " + ReadCharacteristic + "\n");
//							BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress (_deviceAddressRight, serviceUUID2, ReadCharacteristic, null, (address3, characteristicUUID3, bytes) => {
//								print ("Red frame update");
//								ReactToInput (bytes, address3);
//							});
                            print("connected right");
                            ConnectedRight = true;

                            //TODO: hook this up to normal mode
                        }
                    }, (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

                        if (address.Equals(_deviceAddressLeft))
                        {
                            ConnectedLeft      = false;
                            subscribedLeft     = false;
                            _deviceAddressLeft = "";
                        }
                        else if (address.Equals(_deviceAddressRight))
                        {
                            ConnectedRight      = false;
                            subscribedRight     = false;
                            _deviceAddressRight = "";
                        }
                    });
                    break;

                case States.Subscribe:

                    if (ConnectedLeft && !subscribedLeft)
                    {
                        BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddressLeft, ServiceUUID, ReadCharacteristic, null, (address, characteristicUUID, bytes) => {
                            print("input recieved");
                            // 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;
                        });
                        subscribedLeft = true;
                    }

                    if (ConnectedRight && !subscribedRight)
                    {
                        BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddressRight, ServiceUUID, ReadCharacteristic, null, (address, characteristicUUID, bytes) => {
                            print("input recieved");
                            // 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;
                        });
                        subscribedRight = true;
                    }
                    break;

                case States.ReadLeft:
                    BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressLeft, ServiceUUID, ReadCharacteristic, (characteristicUUID, bytes) => {
                        ReactToInput(bytes, _deviceAddressLeft);
                        if (reading)
                        {
                            SetState(States.ReadLeft, 0.01f);
                        }
                    });
                    //SetState (States.ReadLeft, 0.01f);
                    break;

                case States.ReadRight:
                    BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressRight, ServiceUUID, ReadCharacteristic, (characteristicUUID, bytes) => {
                        ReactToInput(bytes, _deviceAddressRight);
                        if (reading)
                        {
                            SetState(States.ReadRight, 0.01f);
                        }
                    });
                    //SetState (States.ReadRight, 0.01f);
                    break;

                case States.ReadBoth:
                    BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressRight, ServiceUUID, ReadCharacteristic, (characteristicUUID, bytes) => {
                        ReactToInput(bytes, _deviceAddressRight);
                        BluetoothLEHardwareInterface.ReadCharacteristic(_deviceAddressLeft, ServiceUUID, ReadCharacteristic, (charUID, bits) => {
                            ReactToInput(bits, _deviceAddressLeft);
                            if (reading)
                            {
                                SetState(States.ReadBoth, 0.001f);
                            }
                        });
                    });
                    //SetState (States.ReadBoth, 0.02f);
                    break;


                case States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddressLeft, ServiceUUID, ReadCharacteristic, null);
                    // no red support
                    SetState(States.DisconnectLeft, 4f);
                    break;

                case States.DisconnectLeft:
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddressLeft, (address) => {});
                    break;

                case States.DisconnectRight:
                    BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddressRight, (address) => {});
                    break;
                }
            }
        }
        else
        {
            _timeout -= Time.deltaTime;

            if (_state == States.Scan && _timeout < -5.0f)
            {
                BluetoothLEHardwareInterface.StopScan();
                SetState(States.Connect, 0.1f);
            }
        }
    }
Exemplo n.º 17
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:
                    setStateText("Scanning for ESP32 devices...");

                    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(DeviceName))
                        {
                            // it is always a good idea to stop scanning while you connect to a device
                            // and get things set up
                            BluetoothLEHardwareInterface.StopScan();

                            // add it to the list and set to connect to it
                            _deviceAddress = address;
                            SetState(States.Connect, 0.5f);

                            _waitingStableTime = 3;
                        }
                    }, null, false, false);
                    break;

                case States.Connect:
                    // set these flags
                    _foundID = false;

                    setStateText("Connecting to ESP32");

                    // 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))
                        {
                            // 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 (IsEqual(characteristicUUID, Characteristic))
                            {
                                _connected = true;
                                SetState(States.Subscribe, 2f);
                                setStateText("Connected to ESP32");
                            }
                        }
                    }, (disconnectedAddress) =>
                    {
                        BluetoothLEHardwareInterface.Log("Device disconnected: " + disconnectedAddress);
                        setStateText("Disconnected");
                        StartProcess();
                    });
                    break;

                case States.Subscribe:
                    setStateText("Subscribing to ESP32");

                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress,
                                                                                          ServiceUUID,
                                                                                          Characteristic, null,
                                                                                          (address, characteristicUUID, bytes) =>
                    {
                        float qx = BitConverter.ToSingle(bytes, 0);
                        float qy = BitConverter.ToSingle(bytes, 4);
                        float qz = BitConverter.ToSingle(bytes, 8);
                        float qw = BitConverter.ToSingle(bytes, 12) * -1;

                        if (_waitingStableTime <= 0)
                        {
                            FindObjectOfType <ReelController>()
                            .updateQuaternion(new Quaternion(qz, -qx, qy, qw));
                        }

                        _waitingStableTime -= Time.deltaTime;
                    });

                    // set to the none state and the user can start sending and receiving data
                    _state = States.None;
                    break;

                case States.Unsubscribe:
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID,
                                                                           Characteristic,
                                                                           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.º 18
0
    void EvaluateBLEStates()
    {
        switch (_state)
        {
        case States.None:
            break;

        case States.Scan:
            BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => {
                DeviceNameFoundedText.text += name + "\n";

                // 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))
                    {
                        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))
                {
                    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:
            // 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;
                float qx   = System.BitConverter.ToSingle(bytes, 0);
                float qy   = System.BitConverter.ToSingle(bytes, 8);
                float qz   = System.BitConverter.ToSingle(bytes, 4);
                float qw   = System.BitConverter.ToSingle(bytes, 12) * -1;

                rawQuat = new Quaternion(qx, qy, qz, qw);
                cubeTransform.rotation = quatLookAtCam * rawQuat;

                //DeviceNameFoundedText.text = qx.ToString() + " " + qy.ToString() + " " + qz.ToString() + " " + qw.ToString()+"\n";
                DeviceNameFoundedText.text  = "raw : " + rawQuat.ToString() + "\n";
                DeviceNameFoundedText.text += "cube : " + cubeTransform.rotation.ToString();
            });
            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.º 19
0
    void OnGUI()
    {
        GUI.skin = skin;

        if (GUI.Button(new Rect(10, 0, 600, 100), "DeInitialize"))
        {
            BluetoothLEHardwareInterface.DeInitialize(null);
        }

        if (GUI.Button(new Rect(10, 100, 300, 50), "Initialize Central"))
        {
            bluetoothDeviceScript = BluetoothLEHardwareInterface.Initialize(true, false, null, null);
        }

        if (GUI.Button(new Rect(10, 150, 300, 50), "Scan for 1851"))
        {
            BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(new string[] { serviceUUID }, null);
        }

        if (GUI.Button(new Rect(10, 200, 300, 50), "Scan for Any"))
        {
            BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, null);
        }

        if (GUI.Button(new Rect(10, 250, 300, 50), "Retrieve Connected"))
        {
            BluetoothLEHardwareInterface.RetrieveListOfPeripheralsWithServices(new string[] { serviceUUID }, null);
        }

        if (GUI.Button(new Rect(10, 300, 300, 50), "Stop Scan"))
        {
            BluetoothLEHardwareInterface.StopScan();
        }

        if (GUI.Button(new Rect(10, 350, 300, 50), "Connect") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0)
        {
            BluetoothLEHardwareInterface.ConnectToPeripheral(bluetoothDeviceScript.DiscoveredDeviceList[0], null, null, null);
        }

        if (GUI.Button(new Rect(10, 400, 300, 50), "Disconnect") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0)
        {
            BluetoothLEHardwareInterface.DisconnectPeripheral(bluetoothDeviceScript.DiscoveredDeviceList[0], null);
        }

        if (GUI.Button(new Rect(10, 450, 300, 50), "Read Characteristic") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0)
        {
            BluetoothLEHardwareInterface.ReadCharacteristic(bluetoothDeviceScript.DiscoveredDeviceList[0], serviceUUID, characteristicUUID, null);
        }

        if (GUI.Button(new Rect(10, 500, 300, 50), "Write Characteristic") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0)
        {
            if (data == null)
            {
                data = new byte[64];
                for (int i = 0; i < 64; ++i)
                {
                    data[i] = (byte)i;
                }
            }

            BluetoothLEHardwareInterface.WriteCharacteristic(bluetoothDeviceScript.DiscoveredDeviceList[0], serviceUUID, characteristicUUID, data, data.Length, true, null);
        }

        if (GUI.Button(new Rect(10, 550, 300, 50), "Subscribe Characteristic") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0)
        {
            BluetoothLEHardwareInterface.SubscribeCharacteristic(bluetoothDeviceScript.DiscoveredDeviceList[0], serviceUUID, characteristicUUID, null, null);
        }

        if (GUI.Button(new Rect(10, 600, 300, 50), "UnSubscribe Characteristic") && bluetoothDeviceScript != null && bluetoothDeviceScript.DiscoveredDeviceList != null && bluetoothDeviceScript.DiscoveredDeviceList.Count > 0)
        {
            BluetoothLEHardwareInterface.UnSubscribeCharacteristic(bluetoothDeviceScript.DiscoveredDeviceList[0], serviceUUID, characteristicUUID, null);
        }

        if (GUI.Button(new Rect(310, 100, 300, 100), "Initialize Peripheral"))
        {
            BluetoothLEHardwareInterface.Initialize(false, true, null, null);
        }

        if (GUI.Button(new Rect(310, 200, 300, 100), "Create Service\nand Characteristic"))
        {
            BluetoothLEHardwareInterface.PeripheralName("Test Device");

            if (data == null)
            {
                data = new byte[64];
                for (int i = 0; i < 64; ++i)
                {
                    data[i] = (byte)i;
                }
            }

            BluetoothLEHardwareInterface.CreateCharacteristic(characteristicUUID,
                                                              BluetoothLEHardwareInterface.CBCharacteristicProperties.CBCharacteristicPropertyRead |
                                                              BluetoothLEHardwareInterface.CBCharacteristicProperties.CBCharacteristicPropertyWrite |
                                                              BluetoothLEHardwareInterface.CBCharacteristicProperties.CBCharacteristicPropertyNotify,
                                                              BluetoothLEHardwareInterface.CBAttributePermissions.CBAttributePermissionsReadable |
                                                              BluetoothLEHardwareInterface.CBAttributePermissions.CBAttributePermissionsWriteable,
                                                              null, 0, null);

            BluetoothLEHardwareInterface.CreateService(serviceUUID, true, null);
        }

        if (GUI.Button(new Rect(310, 300, 300, 100), "Start Advertising"))
        {
            BluetoothLEHardwareInterface.StartAdvertising(null);
        }

        if (GUI.Button(new Rect(310, 400, 300, 100), "Stop Advertising"))
        {
            BluetoothLEHardwareInterface.StopAdvertising(null);
        }

        if (GUI.Button(new Rect(310, 500, 300, 100), "Update Characteristic Value"))
        {
            for (int i = 0; i < data.Length; ++i)
            {
                data[i] = (byte)(data[i] + 1);
            }

            BluetoothLEHardwareInterface.UpdateCharacteristicValue(characteristicUUID, data, data.Length);
        }
    }
 void unsubscribeToDevice()
 {
     BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_JDY16, ServiceUUID, Characteristic, null);
     _state = States.Disconnect;
 }
Exemplo n.º 21
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;
                }
            }
        }
    }
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:
                    TEXT_TITLE.text = "Scanning device " + DEVICEINFO.MAC.STR;
                    BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(null, (address, name) => {
                        if (!_rssiOnly)
                        {
                            Debug.Log("TOAN1: Scanned " + name);
                            if (address.Equals(DEVICEINFO.MAC.STR))
                            {
                                TEXT_TITLE.text = "Scanned device " + DEVICEINFO.MAC.STR;
                                BluetoothLEHardwareInterface.StopScan();
                                _deviceAddress = address;
                                SetState(States.Connect, 0.5f);
                            }
                        }
                    }, (address, name, rssi, bytes) => {
                        Debug.Log("TOAN2: Scanned " + name);
                        if (address.Equals(DEVICEINFO.MAC.STR))
                        {
                            if (_rssiOnly)
                            {
                                _rssi = rssi;
                            }
                            else
                            {
                                TEXT_TITLE.text = "Scanned device " + DEVICEINFO.MAC.STR;
                                BluetoothLEHardwareInterface.StopScan();
                                _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:
                    // set these flags
                    _foundSubscribeID = false;
                    _foundWriteID     = false;
                    //if (!_is_get_auto)
                    //{
                    //	_is_get_auto = true;

                    //	StartCoroutine(GetAllInfor(4f));

                    //}
                    TEXT_TITLE.text = "Connecting to device " + DEVICEINFO.MAC.STR;
                    BluetoothLEHardwareInterface.ConnectToPeripheral(_deviceAddress, (connectAction) =>
                    {
                        TEXT_TITLE.text = "Connected to device " + DEVICEINFO.MAC.STR;
                        Debug.Log("TOAN3441: Connect OK to " + connectAction);
                    },
                                                                     (serviceAction, serviceActio2) =>
                    {
                        Debug.Log("TOAN3442: " + serviceAction + " " + serviceActio2);
                        if (_is_get_auto == false)
                        {
                            _is_get_auto = true;
                        }
                    }
                                                                     , (address, serviceUUID2, characteristicUUID) =>
                    {
                        Debug.Log("TOAN3444:  " + address + " ; " + serviceUUID2 + " ; " + characteristicUUID);
                        TEXT_TITLE.text = "Reading characteristic information ";
                        if (IsEqual(characteristicUUID, "2a9d"))
                        {
                            ServiceUUID             = serviceUUID2;
                            SubscribeCharacteristic = characteristicUUID;
                            _connected = true;
                            SetState(States.Subscribe, 2f);
                        }
                    },
                                                                     (s1) =>
                    {
                        Debug.Log("TOAN1445: DISCONNECTED");
                    });
                    break;

                case States.Subscribe:
                    TEXT_TITLE.text = "Reading weight's characteristic";
                    Debug.Log("TOAN3445: SubscribeCharacteristicWithDeviceAddress to " + _deviceAddress + " " + ServiceUUID + " " + SubscribeCharacteristic);
                    BluetoothLEHardwareInterface.SubscribeCharacteristicWithDeviceAddress(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null, (address, characteristicUUID, bytes) =>
                    {
                        Debug.Log("TOAN3446: SubscribeCharacteristicWithDeviceAddress to " + _deviceAddress);
                        _state     = States.None;
                        _dataBytes = bytes;

                        string data = "";
                        foreach (var b in _dataBytes)
                        {
                            data += b.ToString("X") + " ";
                        }

                        TEXT_TITLE.text = "Weight";

                        ShowInfo(data);
                    });
                    break;

                case States.Unsubscribe:
                    Debug.Log("TOAN6: Unsubscribe to " + _deviceAddress);
                    BluetoothLEHardwareInterface.UnSubscribeCharacteristic(_deviceAddress, ServiceUUID, SubscribeCharacteristic, null);
                    SetState(States.Disconnect, 4f);
                    break;

                case States.Disconnect:
                    Debug.Log("TOAN7: Disconnect to " + _deviceAddress);
                    if (_connected)
                    {
                        BluetoothLEHardwareInterface.DisconnectPeripheral(_deviceAddress, (address) => {
                            BluetoothLEHardwareInterface.DeInitialize(() => {
                                _connected = false;
                                _state     = States.None;
                            });
                        });
                    }
                    else
                    {
                        BluetoothLEHardwareInterface.DeInitialize(() => {
                            _state = States.None;
                        });
                    }
                    break;
                }
            }
        }
    }